##// END OF EJS Templates
Merge with upstream
Fernando Perez -
r1507:2d65d859 merge
parent child Browse files
Show More
@@ -0,0 +1,19 b''
1 """
2 Package for dealing for process execution in a callback environment, in a
3 portable way.
4
5 killable_process.py is a wrapper of subprocess.Popen that allows the
6 subprocess and its children to be killed in a reliable way, including
7 under windows.
8
9 winprocess.py is required by killable_process.py to kill processes under
10 windows.
11
12 piped_process.py wraps process execution with callbacks to print output,
13 in a non-blocking way. It can be used to interact with a subprocess in eg
14 a GUI event loop.
15 """
16
17 from pipedprocess import PipedProcess
18
19
@@ -0,0 +1,168 b''
1 # Addapted from killableprocess.py.
2 #______________________________________________________________________________
3 #
4 # killableprocess - subprocesses which can be reliably killed
5 #
6 # Parts of this module are copied from the subprocess.py file contained
7 # in the Python distribution.
8 #
9 # Copyright (c) 2003-2004 by Peter Astrand <astrand@lysator.liu.se>
10 #
11 # Additions and modifications written by Benjamin Smedberg
12 # <benjamin@smedbergs.us> are Copyright (c) 2006 by the Mozilla Foundation
13 # <http://www.mozilla.org/>
14 #
15 # By obtaining, using, and/or copying this software and/or its
16 # associated documentation, you agree that you have read, understood,
17 # and will comply with the following terms and conditions:
18 #
19 # Permission to use, copy, modify, and distribute this software and
20 # its associated documentation for any purpose and without fee is
21 # hereby granted, provided that the above copyright notice appears in
22 # all copies, and that both that copyright notice and this permission
23 # notice appear in supporting documentation, and that the name of the
24 # author not be used in advertising or publicity pertaining to
25 # distribution of the software without specific, written prior
26 # permission.
27 #
28 # THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
29 # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
30 # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR
31 # CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
32 # OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
33 # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
34 # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
35
36 r"""killableprocess - Subprocesses which can be reliably killed
37
38 This module is a subclass of the builtin "subprocess" module. It allows
39 processes that launch subprocesses to be reliably killed on Windows (via the Popen.kill() method.
40
41 It also adds a timeout argument to Wait() for a limited period of time before
42 forcefully killing the process.
43
44 Note: On Windows, this module requires Windows 2000 or higher (no support for
45 Windows 95, 98, or NT 4.0). It also requires ctypes, which is bundled with
46 Python 2.5+ or available from http://python.net/crew/theller/ctypes/
47 """
48
49 import subprocess
50 from subprocess import PIPE
51 import sys
52 import os
53 import time
54 import types
55
56 try:
57 from subprocess import CalledProcessError
58 except ImportError:
59 # Python 2.4 doesn't implement CalledProcessError
60 class CalledProcessError(Exception):
61 """This exception is raised when a process run by check_call() returns
62 a non-zero exit status. The exit status will be stored in the
63 returncode attribute."""
64 def __init__(self, returncode, cmd):
65 self.returncode = returncode
66 self.cmd = cmd
67 def __str__(self):
68 return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
69
70 mswindows = (sys.platform == "win32")
71
72 if mswindows:
73 import winprocess
74 else:
75 import signal
76
77 if not mswindows:
78 def DoNothing(*args):
79 pass
80
81 class Popen(subprocess.Popen):
82 if not mswindows:
83 # Override __init__ to set a preexec_fn
84 def __init__(self, *args, **kwargs):
85 if len(args) >= 7:
86 raise Exception("Arguments preexec_fn and after must be passed by keyword.")
87
88 real_preexec_fn = kwargs.pop("preexec_fn", None)
89 def setpgid_preexec_fn():
90 os.setpgid(0, 0)
91 if real_preexec_fn:
92 apply(real_preexec_fn)
93
94 kwargs['preexec_fn'] = setpgid_preexec_fn
95
96 subprocess.Popen.__init__(self, *args, **kwargs)
97
98 if mswindows:
99 def _execute_child(self, args, executable, preexec_fn, close_fds,
100 cwd, env, universal_newlines, startupinfo,
101 creationflags, shell,
102 p2cread, p2cwrite,
103 c2pread, c2pwrite,
104 errread, errwrite):
105 if not isinstance(args, types.StringTypes):
106 args = subprocess.list2cmdline(args)
107
108 if startupinfo is None:
109 startupinfo = winprocess.STARTUPINFO()
110
111 if None not in (p2cread, c2pwrite, errwrite):
112 startupinfo.dwFlags |= winprocess.STARTF_USESTDHANDLES
113
114 startupinfo.hStdInput = int(p2cread)
115 startupinfo.hStdOutput = int(c2pwrite)
116 startupinfo.hStdError = int(errwrite)
117 if shell:
118 startupinfo.dwFlags |= winprocess.STARTF_USESHOWWINDOW
119 startupinfo.wShowWindow = winprocess.SW_HIDE
120 comspec = os.environ.get("COMSPEC", "cmd.exe")
121 args = comspec + " /c " + args
122
123 # We create a new job for this process, so that we can kill
124 # the process and any sub-processes
125 self._job = winprocess.CreateJobObject()
126
127 creationflags |= winprocess.CREATE_SUSPENDED
128 creationflags |= winprocess.CREATE_UNICODE_ENVIRONMENT
129
130 hp, ht, pid, tid = winprocess.CreateProcess(
131 executable, args,
132 None, None, # No special security
133 1, # Must inherit handles!
134 creationflags,
135 winprocess.EnvironmentBlock(env),
136 cwd, startupinfo)
137
138 self._child_created = True
139 self._handle = hp
140 self._thread = ht
141 self.pid = pid
142
143 winprocess.AssignProcessToJobObject(self._job, hp)
144 winprocess.ResumeThread(ht)
145
146 if p2cread is not None:
147 p2cread.Close()
148 if c2pwrite is not None:
149 c2pwrite.Close()
150 if errwrite is not None:
151 errwrite.Close()
152
153 def kill(self, group=True):
154 """Kill the process. If group=True, all sub-processes will also be killed."""
155 if mswindows:
156 if group:
157 winprocess.TerminateJobObject(self._job, 127)
158 else:
159 winprocess.TerminateProcess(self._handle, 127)
160 self.returncode = 127
161 else:
162 if group:
163 os.killpg(self.pid, signal.SIGKILL)
164 else:
165 os.kill(self.pid, signal.SIGKILL)
166 self.returncode = -9
167
168
@@ -0,0 +1,74 b''
1 # encoding: utf-8
2 """
3 Object for encapsulating process execution by using callbacks for stdout,
4 stderr and stdin.
5 """
6 __docformat__ = "restructuredtext en"
7
8 #-------------------------------------------------------------------------------
9 # Copyright (C) 2008 The IPython Development Team
10 #
11 # Distributed under the terms of the BSD License. The full license is in
12 # the file COPYING, distributed as part of this software.
13 #-------------------------------------------------------------------------------
14
15 #-------------------------------------------------------------------------------
16 # Imports
17 #-------------------------------------------------------------------------------
18 from killableprocess import Popen, PIPE
19 from threading import Thread
20 from time import sleep
21 import os
22
23 class PipedProcess(Thread):
24 """ Class that encapsulates process execution by using callbacks for
25 stdout, stderr and stdin, and providing a reliable way of
26 killing it.
27 """
28
29 def __init__(self, command_string, out_callback,
30 end_callback=None,):
31 """ command_string: the command line executed to start the
32 process.
33
34 out_callback: the python callable called on stdout/stderr.
35
36 end_callback: an optional callable called when the process
37 finishes.
38
39 These callbacks are called from a different thread as the
40 thread from which is started.
41 """
42 self.command_string = command_string
43 self.out_callback = out_callback
44 self.end_callback = end_callback
45 Thread.__init__(self)
46
47
48 def run(self):
49 """ Start the process and hook up the callbacks.
50 """
51 env = os.environ
52 env['TERM'] = 'xterm'
53 process = Popen((self.command_string + ' 2>&1', ), shell=True,
54 env=env,
55 universal_newlines=True,
56 stdout=PIPE, stdin=PIPE, )
57 self.process = process
58 while True:
59 out_char = process.stdout.read(1)
60 if out_char == '':
61 if process.poll() is not None:
62 # The process has finished
63 break
64 else:
65 # The process is not giving any interesting
66 # output. No use polling it immediatly.
67 sleep(0.1)
68 else:
69 self.out_callback(out_char)
70
71 if self.end_callback is not None:
72 self.end_callback()
73
74
@@ -0,0 +1,264 b''
1 # A module to expose various thread/process/job related structures and
2 # methods from kernel32
3 #
4 # The MIT License
5 #
6 # Copyright (c) 2006 the Mozilla Foundation <http://www.mozilla.org>
7 #
8 # Permission is hereby granted, free of charge, to any person obtaining a
9 # copy of this software and associated documentation files (the "Software"),
10 # to deal in the Software without restriction, including without limitation
11 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 # and/or sell copies of the Software, and to permit persons to whom the
13 # Software is furnished to do so, subject to the following conditions:
14 #
15 # The above copyright notice and this permission notice shall be included in
16 # all copies or substantial portions of the Software.
17 #
18 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 # DEALINGS IN THE SOFTWARE.
25
26 from ctypes import c_void_p, POINTER, sizeof, Structure, windll, WinError, WINFUNCTYPE
27 from ctypes.wintypes import BOOL, BYTE, DWORD, HANDLE, LPCWSTR, LPWSTR, UINT, WORD
28
29 LPVOID = c_void_p
30 LPBYTE = POINTER(BYTE)
31 LPDWORD = POINTER(DWORD)
32
33 SW_HIDE = 0
34
35 def ErrCheckBool(result, func, args):
36 """errcheck function for Windows functions that return a BOOL True
37 on success"""
38 if not result:
39 raise WinError()
40 return args
41
42 # CloseHandle()
43
44 CloseHandleProto = WINFUNCTYPE(BOOL, HANDLE)
45 CloseHandle = CloseHandleProto(("CloseHandle", windll.kernel32))
46 CloseHandle.errcheck = ErrCheckBool
47
48 # AutoHANDLE
49
50 class AutoHANDLE(HANDLE):
51 """Subclass of HANDLE which will call CloseHandle() on deletion."""
52 def Close(self):
53 if self.value:
54 CloseHandle(self)
55 self.value = 0
56
57 def __del__(self):
58 self.Close()
59
60 def __int__(self):
61 return self.value
62
63 def ErrCheckHandle(result, func, args):
64 """errcheck function for Windows functions that return a HANDLE."""
65 if not result:
66 raise WinError()
67 return AutoHANDLE(result)
68
69 # PROCESS_INFORMATION structure
70
71 class PROCESS_INFORMATION(Structure):
72 _fields_ = [("hProcess", HANDLE),
73 ("hThread", HANDLE),
74 ("dwProcessID", DWORD),
75 ("dwThreadID", DWORD)]
76
77 def __init__(self):
78 Structure.__init__(self)
79
80 self.cb = sizeof(self)
81
82 LPPROCESS_INFORMATION = POINTER(PROCESS_INFORMATION)
83
84 # STARTUPINFO structure
85
86 class STARTUPINFO(Structure):
87 _fields_ = [("cb", DWORD),
88 ("lpReserved", LPWSTR),
89 ("lpDesktop", LPWSTR),
90 ("lpTitle", LPWSTR),
91 ("dwX", DWORD),
92 ("dwY", DWORD),
93 ("dwXSize", DWORD),
94 ("dwYSize", DWORD),
95 ("dwXCountChars", DWORD),
96 ("dwYCountChars", DWORD),
97 ("dwFillAttribute", DWORD),
98 ("dwFlags", DWORD),
99 ("wShowWindow", WORD),
100 ("cbReserved2", WORD),
101 ("lpReserved2", LPBYTE),
102 ("hStdInput", HANDLE),
103 ("hStdOutput", HANDLE),
104 ("hStdError", HANDLE)
105 ]
106 LPSTARTUPINFO = POINTER(STARTUPINFO)
107
108 STARTF_USESHOWWINDOW = 0x01
109 STARTF_USESIZE = 0x02
110 STARTF_USEPOSITION = 0x04
111 STARTF_USECOUNTCHARS = 0x08
112 STARTF_USEFILLATTRIBUTE = 0x10
113 STARTF_RUNFULLSCREEN = 0x20
114 STARTF_FORCEONFEEDBACK = 0x40
115 STARTF_FORCEOFFFEEDBACK = 0x80
116 STARTF_USESTDHANDLES = 0x100
117
118 # EnvironmentBlock
119
120 class EnvironmentBlock:
121 """An object which can be passed as the lpEnv parameter of CreateProcess.
122 It is initialized with a dictionary."""
123
124 def __init__(self, dict):
125 if not dict:
126 self._as_parameter_ = None
127 else:
128 values = ["%s=%s" % (key, value)
129 for (key, value) in dict.iteritems()]
130 values.append("")
131 self._as_parameter_ = LPCWSTR("\0".join(values))
132
133 # CreateProcess()
134
135 CreateProcessProto = WINFUNCTYPE(BOOL, # Return type
136 LPCWSTR, # lpApplicationName
137 LPWSTR, # lpCommandLine
138 LPVOID, # lpProcessAttributes
139 LPVOID, # lpThreadAttributes
140 BOOL, # bInheritHandles
141 DWORD, # dwCreationFlags
142 LPVOID, # lpEnvironment
143 LPCWSTR, # lpCurrentDirectory
144 LPSTARTUPINFO, # lpStartupInfo
145 LPPROCESS_INFORMATION # lpProcessInformation
146 )
147
148 CreateProcessFlags = ((1, "lpApplicationName", None),
149 (1, "lpCommandLine"),
150 (1, "lpProcessAttributes", None),
151 (1, "lpThreadAttributes", None),
152 (1, "bInheritHandles", True),
153 (1, "dwCreationFlags", 0),
154 (1, "lpEnvironment", None),
155 (1, "lpCurrentDirectory", None),
156 (1, "lpStartupInfo"),
157 (2, "lpProcessInformation"))
158
159 def ErrCheckCreateProcess(result, func, args):
160 ErrCheckBool(result, func, args)
161 # return a tuple (hProcess, hThread, dwProcessID, dwThreadID)
162 pi = args[9]
163 return AutoHANDLE(pi.hProcess), AutoHANDLE(pi.hThread), pi.dwProcessID, pi.dwThreadID
164
165 CreateProcess = CreateProcessProto(("CreateProcessW", windll.kernel32),
166 CreateProcessFlags)
167 CreateProcess.errcheck = ErrCheckCreateProcess
168
169 CREATE_BREAKAWAY_FROM_JOB = 0x01000000
170 CREATE_DEFAULT_ERROR_MODE = 0x04000000
171 CREATE_NEW_CONSOLE = 0x00000010
172 CREATE_NEW_PROCESS_GROUP = 0x00000200
173 CREATE_NO_WINDOW = 0x08000000
174 CREATE_SUSPENDED = 0x00000004
175 CREATE_UNICODE_ENVIRONMENT = 0x00000400
176 DEBUG_ONLY_THIS_PROCESS = 0x00000002
177 DEBUG_PROCESS = 0x00000001
178 DETACHED_PROCESS = 0x00000008
179
180 # CreateJobObject()
181
182 CreateJobObjectProto = WINFUNCTYPE(HANDLE, # Return type
183 LPVOID, # lpJobAttributes
184 LPCWSTR # lpName
185 )
186
187 CreateJobObjectFlags = ((1, "lpJobAttributes", None),
188 (1, "lpName", None))
189
190 CreateJobObject = CreateJobObjectProto(("CreateJobObjectW", windll.kernel32),
191 CreateJobObjectFlags)
192 CreateJobObject.errcheck = ErrCheckHandle
193
194 # AssignProcessToJobObject()
195
196 AssignProcessToJobObjectProto = WINFUNCTYPE(BOOL, # Return type
197 HANDLE, # hJob
198 HANDLE # hProcess
199 )
200 AssignProcessToJobObjectFlags = ((1, "hJob"),
201 (1, "hProcess"))
202 AssignProcessToJobObject = AssignProcessToJobObjectProto(
203 ("AssignProcessToJobObject", windll.kernel32),
204 AssignProcessToJobObjectFlags)
205 AssignProcessToJobObject.errcheck = ErrCheckBool
206
207 # ResumeThread()
208
209 def ErrCheckResumeThread(result, func, args):
210 if result == -1:
211 raise WinError()
212
213 return args
214
215 ResumeThreadProto = WINFUNCTYPE(DWORD, # Return type
216 HANDLE # hThread
217 )
218 ResumeThreadFlags = ((1, "hThread"),)
219 ResumeThread = ResumeThreadProto(("ResumeThread", windll.kernel32),
220 ResumeThreadFlags)
221 ResumeThread.errcheck = ErrCheckResumeThread
222
223 # TerminateJobObject()
224
225 TerminateJobObjectProto = WINFUNCTYPE(BOOL, # Return type
226 HANDLE, # hJob
227 UINT # uExitCode
228 )
229 TerminateJobObjectFlags = ((1, "hJob"),
230 (1, "uExitCode", 127))
231 TerminateJobObject = TerminateJobObjectProto(
232 ("TerminateJobObject", windll.kernel32),
233 TerminateJobObjectFlags)
234 TerminateJobObject.errcheck = ErrCheckBool
235
236 # WaitForSingleObject()
237
238 WaitForSingleObjectProto = WINFUNCTYPE(DWORD, # Return type
239 HANDLE, # hHandle
240 DWORD, # dwMilliseconds
241 )
242 WaitForSingleObjectFlags = ((1, "hHandle"),
243 (1, "dwMilliseconds", -1))
244 WaitForSingleObject = WaitForSingleObjectProto(
245 ("WaitForSingleObject", windll.kernel32),
246 WaitForSingleObjectFlags)
247
248 INFINITE = -1
249 WAIT_TIMEOUT = 0x0102
250 WAIT_OBJECT_0 = 0x0
251 WAIT_ABANDONED = 0x0080
252
253 # GetExitCodeProcess()
254
255 GetExitCodeProcessProto = WINFUNCTYPE(BOOL, # Return type
256 HANDLE, # hProcess
257 LPDWORD, # lpExitCode
258 )
259 GetExitCodeProcessFlags = ((1, "hProcess"),
260 (2, "lpExitCode"))
261 GetExitCodeProcess = GetExitCodeProcessProto(
262 ("GetExitCodeProcess", windll.kernel32),
263 GetExitCodeProcessFlags)
264 GetExitCodeProcess.errcheck = ErrCheckBool
@@ -0,0 +1,92 b''
1 """
2 Base front end class for all async frontends.
3 """
4 __docformat__ = "restructuredtext en"
5
6 #-------------------------------------------------------------------------------
7 # Copyright (C) 2008 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 #-------------------------------------------------------------------------------
15 # Imports
16 #-------------------------------------------------------------------------------
17 import uuid
18
19 try:
20 from zope.interface import Interface, Attribute, implements, classProvides
21 except ImportError, e:
22 e.message = """%s
23 ________________________________________________________________________________
24 zope.interface is required to run asynchronous frontends.""" % e.message
25 e.args = (e.message, ) + e.args[1:]
26
27 from frontendbase import FrontEndBase, IFrontEnd, IFrontEndFactory
28
29 from IPython.kernel.engineservice import IEngineCore
30 from IPython.kernel.core.history import FrontEndHistory
31
32 try:
33 from twisted.python.failure import Failure
34 except ImportError, e:
35 e.message = """%s
36 ________________________________________________________________________________
37 twisted is required to run asynchronous frontends.""" % e.message
38 e.args = (e.message, ) + e.args[1:]
39
40
41
42
43 class AsyncFrontEndBase(FrontEndBase):
44 """
45 Overrides FrontEndBase to wrap execute in a deferred result.
46 All callbacks are made as callbacks on the deferred result.
47 """
48
49 implements(IFrontEnd)
50 classProvides(IFrontEndFactory)
51
52 def __init__(self, engine=None, history=None):
53 assert(engine==None or IEngineCore.providedBy(engine))
54 self.engine = IEngineCore(engine)
55 if history is None:
56 self.history = FrontEndHistory(input_cache=[''])
57 else:
58 self.history = history
59
60
61 def execute(self, block, blockID=None):
62 """Execute the block and return the deferred result.
63
64 Parameters:
65 block : {str, AST}
66 blockID : any
67 Caller may provide an ID to identify this block.
68 result['blockID'] := blockID
69
70 Result:
71 Deferred result of self.interpreter.execute
72 """
73
74 if(not self.is_complete(block)):
75 return Failure(Exception("Block is not compilable"))
76
77 if(blockID == None):
78 blockID = uuid.uuid4() #random UUID
79
80 d = self.engine.execute(block)
81 d.addCallback(self._add_history, block=block)
82 d.addCallbacks(self._add_block_id_for_result,
83 errback=self._add_block_id_for_failure,
84 callbackArgs=(blockID,),
85 errbackArgs=(blockID,))
86 d.addBoth(self.update_cell_prompt, blockID=blockID)
87 d.addCallbacks(self.render_result,
88 errback=self.render_error)
89
90 return d
91
92
@@ -0,0 +1,294 b''
1 """
2 Base front end class for all line-oriented frontends, rather than
3 block-oriented.
4
5 Currently this focuses on synchronous frontends.
6 """
7 __docformat__ = "restructuredtext en"
8
9 #-------------------------------------------------------------------------------
10 # Copyright (C) 2008 The IPython Development Team
11 #
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
14 #-------------------------------------------------------------------------------
15
16 #-------------------------------------------------------------------------------
17 # Imports
18 #-------------------------------------------------------------------------------
19 import re
20
21 import IPython
22 import sys
23
24 from frontendbase import FrontEndBase
25 from IPython.kernel.core.interpreter import Interpreter
26
27 def common_prefix(strings):
28 """ Given a list of strings, return the common prefix between all
29 these strings.
30 """
31 ref = strings[0]
32 prefix = ''
33 for size in range(len(ref)):
34 test_prefix = ref[:size+1]
35 for string in strings[1:]:
36 if not string.startswith(test_prefix):
37 return prefix
38 prefix = test_prefix
39
40 return prefix
41
42 #-------------------------------------------------------------------------------
43 # Base class for the line-oriented front ends
44 #-------------------------------------------------------------------------------
45 class LineFrontEndBase(FrontEndBase):
46 """ Concrete implementation of the FrontEndBase class. This is meant
47 to be the base class behind all the frontend that are line-oriented,
48 rather than block-oriented.
49 """
50
51 # We need to keep the prompt number, to be able to increment
52 # it when there is an exception.
53 prompt_number = 1
54
55 # We keep a reference to the last result: it helps testing and
56 # programatic control of the frontend.
57 last_result = dict(number=0)
58
59 # The input buffer being edited
60 input_buffer = ''
61
62 # Set to true for debug output
63 debug = False
64
65 # A banner to print at startup
66 banner = None
67
68 #--------------------------------------------------------------------------
69 # FrontEndBase interface
70 #--------------------------------------------------------------------------
71
72 def __init__(self, shell=None, history=None, banner=None, *args, **kwargs):
73 if shell is None:
74 shell = Interpreter()
75 FrontEndBase.__init__(self, shell=shell, history=history)
76
77 if banner is not None:
78 self.banner = banner
79 if self.banner is not None:
80 self.write(self.banner, refresh=False)
81
82 self.new_prompt(self.input_prompt_template.substitute(number=1))
83
84
85 def complete(self, line):
86 """Complete line in engine's user_ns
87
88 Parameters
89 ----------
90 line : string
91
92 Result
93 ------
94 The replacement for the line and the list of possible completions.
95 """
96 completions = self.shell.complete(line)
97 complete_sep = re.compile('[\s\{\}\[\]\(\)\=]')
98 if completions:
99 prefix = common_prefix(completions)
100 residual = complete_sep.split(line)[:-1]
101 line = line[:-len(residual)] + prefix
102 return line, completions
103
104
105 def render_result(self, result):
106 """ Frontend-specific rendering of the result of a calculation
107 that has been sent to an engine.
108 """
109 if 'stdout' in result and result['stdout']:
110 self.write('\n' + result['stdout'])
111 if 'display' in result and result['display']:
112 self.write("%s%s\n" % (
113 self.output_prompt_template.substitute(
114 number=result['number']),
115 result['display']['pprint']
116 ) )
117
118
119 def render_error(self, failure):
120 """ Frontend-specific rendering of error.
121 """
122 self.write('\n\n'+str(failure)+'\n\n')
123 return failure
124
125
126 def is_complete(self, string):
127 """ Check if a string forms a complete, executable set of
128 commands.
129
130 For the line-oriented frontend, multi-line code is not executed
131 as soon as it is complete: the users has to enter two line
132 returns.
133 """
134 if string in ('', '\n'):
135 # Prefiltering, eg through ipython0, may return an empty
136 # string although some operations have been accomplished. We
137 # thus want to consider an empty string as a complete
138 # statement.
139 return True
140 elif ( len(self.input_buffer.split('\n'))>2
141 and not re.findall(r"\n[\t ]*\n[\t ]*$", string)):
142 return False
143 else:
144 # Add line returns here, to make sure that the statement is
145 # complete.
146 return FrontEndBase.is_complete(self, string.rstrip() + '\n\n')
147
148
149 def write(self, string, refresh=True):
150 """ Write some characters to the display.
151
152 Subclass should overide this method.
153
154 The refresh keyword argument is used in frontends with an
155 event loop, to choose whether the write should trigget an UI
156 refresh, and thus be syncrhonous, or not.
157 """
158 print >>sys.__stderr__, string
159
160
161 def execute(self, python_string, raw_string=None):
162 """ Stores the raw_string in the history, and sends the
163 python string to the interpreter.
164 """
165 if raw_string is None:
166 raw_string = python_string
167 # Create a false result, in case there is an exception
168 self.last_result = dict(number=self.prompt_number)
169 try:
170 self.history.input_cache[-1] = raw_string.rstrip()
171 result = self.shell.execute(python_string)
172 self.last_result = result
173 self.render_result(result)
174 except:
175 self.show_traceback()
176 finally:
177 self.after_execute()
178
179 #--------------------------------------------------------------------------
180 # LineFrontEndBase interface
181 #--------------------------------------------------------------------------
182
183 def prefilter_input(self, string):
184 """ Priflter the input to turn it in valid python.
185 """
186 string = string.replace('\r\n', '\n')
187 string = string.replace('\t', 4*' ')
188 # Clean the trailing whitespace
189 string = '\n'.join(l.rstrip() for l in string.split('\n'))
190 return string
191
192
193 def after_execute(self):
194 """ All the operations required after an execution to put the
195 terminal back in a shape where it is usable.
196 """
197 self.prompt_number += 1
198 self.new_prompt(self.input_prompt_template.substitute(
199 number=(self.last_result['number'] + 1)))
200 # Start a new empty history entry
201 self._add_history(None, '')
202 self.history_cursor = len(self.history.input_cache) - 1
203
204
205 def complete_current_input(self):
206 """ Do code completion on current line.
207 """
208 if self.debug:
209 print >>sys.__stdout__, "complete_current_input",
210 line = self.input_buffer
211 new_line, completions = self.complete(line)
212 if len(completions)>1:
213 self.write_completion(completions)
214 self.input_buffer = new_line
215 if self.debug:
216 print >>sys.__stdout__, completions
217
218
219 def get_line_width(self):
220 """ Return the width of the line in characters.
221 """
222 return 80
223
224
225 def write_completion(self, possibilities):
226 """ Write the list of possible completions.
227 """
228 current_buffer = self.input_buffer
229
230 self.write('\n')
231 max_len = len(max(possibilities, key=len)) + 1
232
233 # Now we check how much symbol we can put on a line...
234 chars_per_line = self.get_line_width()
235 symbols_per_line = max(1, chars_per_line/max_len)
236
237 pos = 1
238 buf = []
239 for symbol in possibilities:
240 if pos < symbols_per_line:
241 buf.append(symbol.ljust(max_len))
242 pos += 1
243 else:
244 buf.append(symbol.rstrip() + '\n')
245 pos = 1
246 self.write(''.join(buf))
247 self.new_prompt(self.input_prompt_template.substitute(
248 number=self.last_result['number'] + 1))
249 self.input_buffer = current_buffer
250
251
252 def new_prompt(self, prompt):
253 """ Prints a prompt and starts a new editing buffer.
254
255 Subclasses should use this method to make sure that the
256 terminal is put in a state favorable for a new line
257 input.
258 """
259 self.input_buffer = ''
260 self.write(prompt)
261
262
263 #--------------------------------------------------------------------------
264 # Private API
265 #--------------------------------------------------------------------------
266
267 def _on_enter(self):
268 """ Called when the return key is pressed in a line editing
269 buffer.
270 """
271 current_buffer = self.input_buffer
272 cleaned_buffer = self.prefilter_input(current_buffer)
273 if self.is_complete(cleaned_buffer):
274 self.execute(cleaned_buffer, raw_string=current_buffer)
275 else:
276 self.input_buffer += self._get_indent_string(
277 current_buffer[:-1])
278 if current_buffer[:-1].split('\n')[-1].rstrip().endswith(':'):
279 self.input_buffer += '\t'
280
281
282 def _get_indent_string(self, string):
283 """ Return the string of whitespace that prefixes a line. Used to
284 add the right amount of indendation when creating a new line.
285 """
286 string = string.replace('\t', ' '*4)
287 string = string.split('\n')[-1]
288 indent_chars = len(string) - len(string.lstrip())
289 indent_string = '\t'*(indent_chars // 4) + \
290 ' '*(indent_chars % 4)
291
292 return indent_string
293
294
@@ -0,0 +1,221 b''
1 """
2 Frontend class that uses IPython0 to prefilter the inputs.
3
4 Using the IPython0 mechanism gives us access to the magics.
5
6 This is a transitory class, used here to do the transition between
7 ipython0 and ipython1. This class is meant to be short-lived as more
8 functionnality is abstracted out of ipython0 in reusable functions and
9 is added on the interpreter. This class can be a used to guide this
10 refactoring.
11 """
12 __docformat__ = "restructuredtext en"
13
14 #-------------------------------------------------------------------------------
15 # Copyright (C) 2008 The IPython Development Team
16 #
17 # Distributed under the terms of the BSD License. The full license is in
18 # the file COPYING, distributed as part of this software.
19 #-------------------------------------------------------------------------------
20
21 #-------------------------------------------------------------------------------
22 # Imports
23 #-------------------------------------------------------------------------------
24 import sys
25
26 from linefrontendbase import LineFrontEndBase, common_prefix
27
28 from IPython.ipmaker import make_IPython
29 from IPython.ipapi import IPApi
30 from IPython.kernel.core.redirector_output_trap import RedirectorOutputTrap
31
32 from IPython.kernel.core.sync_traceback_trap import SyncTracebackTrap
33
34 from IPython.genutils import Term
35 import pydoc
36 import os
37
38
39 def mk_system_call(system_call_function, command):
40 """ given a os.system replacement, and a leading string command,
41 returns a function that will execute the command with the given
42 argument string.
43 """
44 def my_system_call(args):
45 system_call_function("%s %s" % (command, args))
46 return my_system_call
47
48 #-------------------------------------------------------------------------------
49 # Frontend class using ipython0 to do the prefiltering.
50 #-------------------------------------------------------------------------------
51 class PrefilterFrontEnd(LineFrontEndBase):
52 """ Class that uses ipython0 to do prefilter the input, do the
53 completion and the magics.
54
55 The core trick is to use an ipython0 instance to prefilter the
56 input, and share the namespace between the interpreter instance used
57 to execute the statements and the ipython0 used for code
58 completion...
59 """
60
61 def __init__(self, ipython0=None, *args, **kwargs):
62 """ Parameters:
63 -----------
64
65 ipython0: an optional ipython0 instance to use for command
66 prefiltering and completion.
67 """
68 self.save_output_hooks()
69 if ipython0 is None:
70 # Instanciate an IPython0 interpreter to be able to use the
71 # prefiltering.
72 # XXX: argv=[] is a bit bold.
73 ipython0 = make_IPython(argv=[])
74 self.ipython0 = ipython0
75 # Set the pager:
76 self.ipython0.set_hook('show_in_pager',
77 lambda s, string: self.write("\n" + string))
78 self.ipython0.write = self.write
79 self._ip = _ip = IPApi(self.ipython0)
80 # Make sure the raw system call doesn't get called, as we don't
81 # have a stdin accessible.
82 self._ip.system = self.system_call
83 # XXX: Muck around with magics so that they work better
84 # in our environment
85 self.ipython0.magic_ls = mk_system_call(self.system_call,
86 'ls -CF')
87 # And now clean up the mess created by ipython0
88 self.release_output()
89 if not 'banner' in kwargs and self.banner is None:
90 kwargs['banner'] = self.ipython0.BANNER + """
91 This is the wx frontend, by Gael Varoquaux. This is EXPERIMENTAL code."""
92
93 LineFrontEndBase.__init__(self, *args, **kwargs)
94 # XXX: Hack: mix the two namespaces
95 self.shell.user_ns = self.ipython0.user_ns
96 self.shell.user_global_ns = self.ipython0.user_global_ns
97
98 self.shell.output_trap = RedirectorOutputTrap(
99 out_callback=self.write,
100 err_callback=self.write,
101 )
102 self.shell.traceback_trap = SyncTracebackTrap(
103 formatters=self.shell.traceback_trap.formatters,
104 )
105
106 #--------------------------------------------------------------------------
107 # FrontEndBase interface
108 #--------------------------------------------------------------------------
109
110 def show_traceback(self):
111 """ Use ipython0 to capture the last traceback and display it.
112 """
113 self.capture_output()
114 self.ipython0.showtraceback()
115 self.release_output()
116
117
118 def execute(self, python_string, raw_string=None):
119 if self.debug:
120 print 'Executing Python code:', repr(python_string)
121 self.capture_output()
122 LineFrontEndBase.execute(self, python_string,
123 raw_string=raw_string)
124 self.release_output()
125
126
127 def save_output_hooks(self):
128 """ Store all the output hooks we can think of, to be able to
129 restore them.
130
131 We need to do this early, as starting the ipython0 instance will
132 screw ouput hooks.
133 """
134 self.__old_cout_write = Term.cout.write
135 self.__old_cerr_write = Term.cerr.write
136 self.__old_stdout = sys.stdout
137 self.__old_stderr= sys.stderr
138 self.__old_help_output = pydoc.help.output
139 self.__old_display_hook = sys.displayhook
140
141
142 def capture_output(self):
143 """ Capture all the output mechanisms we can think of.
144 """
145 self.save_output_hooks()
146 Term.cout.write = self.write
147 Term.cerr.write = self.write
148 sys.stdout = Term.cout
149 sys.stderr = Term.cerr
150 pydoc.help.output = self.shell.output_trap.out
151
152
153 def release_output(self):
154 """ Release all the different captures we have made.
155 """
156 Term.cout.write = self.__old_cout_write
157 Term.cerr.write = self.__old_cerr_write
158 sys.stdout = self.__old_stdout
159 sys.stderr = self.__old_stderr
160 pydoc.help.output = self.__old_help_output
161 sys.displayhook = self.__old_display_hook
162
163
164 def complete(self, line):
165 word = line.split('\n')[-1].split(' ')[-1]
166 completions = self.ipython0.complete(word)
167 # FIXME: The proper sort should be done in the complete method.
168 key = lambda x: x.replace('_', '')
169 completions.sort(key=key)
170 if completions:
171 prefix = common_prefix(completions)
172 line = line[:-len(word)] + prefix
173 return line, completions
174
175
176 #--------------------------------------------------------------------------
177 # LineFrontEndBase interface
178 #--------------------------------------------------------------------------
179
180 def prefilter_input(self, input_string):
181 """ Using IPython0 to prefilter the commands to turn them
182 in executable statements that are valid Python strings.
183 """
184 input_string = LineFrontEndBase.prefilter_input(self, input_string)
185 filtered_lines = []
186 # The IPython0 prefilters sometime produce output. We need to
187 # capture it.
188 self.capture_output()
189 self.last_result = dict(number=self.prompt_number)
190 try:
191 for line in input_string.split('\n'):
192 filtered_lines.append(
193 self.ipython0.prefilter(line, False).rstrip())
194 except:
195 # XXX: probably not the right thing to do.
196 self.ipython0.showsyntaxerror()
197 self.after_execute()
198 finally:
199 self.release_output()
200
201 # Clean up the trailing whitespace, to avoid indentation errors
202 filtered_string = '\n'.join(filtered_lines)
203 return filtered_string
204
205
206 #--------------------------------------------------------------------------
207 # PrefilterFrontEnd interface
208 #--------------------------------------------------------------------------
209
210 def system_call(self, command_string):
211 """ Allows for frontend to define their own system call, to be
212 able capture output and redirect input.
213 """
214 return os.system(command_string)
215
216
217 def do_exit(self):
218 """ Exit the shell, cleanup and save the history.
219 """
220 self.ipython0.atexit_operations()
221
@@ -0,0 +1,157 b''
1 # encoding: utf-8
2 """
3 Test process execution and IO redirection.
4 """
5
6 __docformat__ = "restructuredtext en"
7
8 #-------------------------------------------------------------------------------
9 # Copyright (C) 2008 The IPython Development Team
10 #
11 # Distributed under the terms of the BSD License. The full license is
12 # in the file COPYING, distributed as part of this software.
13 #-------------------------------------------------------------------------------
14
15 from cStringIO import StringIO
16 import string
17
18 from IPython.ipapi import get as get_ipython0
19 from IPython.frontend.prefilterfrontend import PrefilterFrontEnd
20
21 class TestPrefilterFrontEnd(PrefilterFrontEnd):
22
23 input_prompt_template = string.Template('')
24 output_prompt_template = string.Template('')
25 banner = ''
26
27 def __init__(self):
28 ipython0 = get_ipython0().IP
29 self.out = StringIO()
30 PrefilterFrontEnd.__init__(self, ipython0=ipython0)
31 # Clean up the namespace for isolation between tests
32 user_ns = self.ipython0.user_ns
33 # We need to keep references to things so that they don't
34 # get garbage collected (this stinks).
35 self.shadow_ns = dict()
36 for i in self.ipython0.magic_who_ls():
37 self.shadow_ns[i] = user_ns.pop(i)
38 # Some more code for isolation (yeah, crazy)
39 self._on_enter()
40 self.out.flush()
41 self.out.reset()
42 self.out.truncate()
43
44 def write(self, string, *args, **kwargs):
45 self.out.write(string)
46
47 def _on_enter(self):
48 self.input_buffer += '\n'
49 PrefilterFrontEnd._on_enter(self)
50
51
52 def test_execution():
53 """ Test execution of a command.
54 """
55 f = TestPrefilterFrontEnd()
56 f.input_buffer = 'print 1'
57 f._on_enter()
58 out_value = f.out.getvalue()
59 assert out_value == '1\n'
60
61
62 def test_multiline():
63 """ Test execution of a multiline command.
64 """
65 f = TestPrefilterFrontEnd()
66 f.input_buffer = 'if True:'
67 f._on_enter()
68 f.input_buffer += 'print 1'
69 f._on_enter()
70 out_value = f.out.getvalue()
71 assert out_value == ''
72 f._on_enter()
73 out_value = f.out.getvalue()
74 assert out_value == '1\n'
75 f = TestPrefilterFrontEnd()
76 f.input_buffer='(1 +'
77 f._on_enter()
78 f.input_buffer += '0)'
79 f._on_enter()
80 out_value = f.out.getvalue()
81 assert out_value == ''
82 f._on_enter()
83 out_value = f.out.getvalue()
84 assert out_value == '1\n'
85
86
87 def test_capture():
88 """ Test the capture of output in different channels.
89 """
90 # Test on the OS-level stdout, stderr.
91 f = TestPrefilterFrontEnd()
92 f.input_buffer = \
93 'import os; out=os.fdopen(1, "w"); out.write("1") ; out.flush()'
94 f._on_enter()
95 out_value = f.out.getvalue()
96 assert out_value == '1'
97 f = TestPrefilterFrontEnd()
98 f.input_buffer = \
99 'import os; out=os.fdopen(2, "w"); out.write("1") ; out.flush()'
100 f._on_enter()
101 out_value = f.out.getvalue()
102 assert out_value == '1'
103
104
105 def test_magic():
106 """ Test the magic expansion and history.
107
108 This test is fairly fragile and will break when magics change.
109 """
110 f = TestPrefilterFrontEnd()
111 f.input_buffer += '%who'
112 f._on_enter()
113 out_value = f.out.getvalue()
114 assert out_value == 'Interactive namespace is empty.\n'
115
116
117 def test_help():
118 """ Test object inspection.
119 """
120 f = TestPrefilterFrontEnd()
121 f.input_buffer += "def f():"
122 f._on_enter()
123 f.input_buffer += "'foobar'"
124 f._on_enter()
125 f.input_buffer += "pass"
126 f._on_enter()
127 f._on_enter()
128 f.input_buffer += "f?"
129 f._on_enter()
130 assert 'traceback' not in f.last_result
131 ## XXX: ipython doctest magic breaks this. I have no clue why
132 #out_value = f.out.getvalue()
133 #assert out_value.split()[-1] == 'foobar'
134
135
136 def test_completion():
137 """ Test command-line completion.
138 """
139 f = TestPrefilterFrontEnd()
140 f.input_buffer = 'zzza = 1'
141 f._on_enter()
142 f.input_buffer = 'zzzb = 2'
143 f._on_enter()
144 f.input_buffer = 'zz'
145 f.complete_current_input()
146 out_value = f.out.getvalue()
147 assert out_value == '\nzzza zzzb '
148 assert f.input_buffer == 'zzz'
149
150
151 if __name__ == '__main__':
152 test_magic()
153 test_help()
154 test_execution()
155 test_multiline()
156 test_capture()
157 test_completion()
@@ -0,0 +1,63 b''
1 # encoding: utf-8
2 """
3 Test process execution and IO redirection.
4 """
5
6 __docformat__ = "restructuredtext en"
7
8 #-------------------------------------------------------------------------------
9 # Copyright (C) 2008 The IPython Development Team
10 #
11 # Distributed under the terms of the BSD License. The full license is
12 # in the file COPYING, distributed as part of this software.
13 #-------------------------------------------------------------------------------
14
15 from cStringIO import StringIO
16 from time import sleep
17 import sys
18
19 from IPython.frontend._process import PipedProcess
20
21 def test_capture_out():
22 """ A simple test to see if we can execute a process and get the output.
23 """
24 s = StringIO()
25 p = PipedProcess('echo 1', out_callback=s.write, )
26 p.start()
27 p.join()
28 assert s.getvalue() == '1\n'
29
30
31 def test_io():
32 """ Checks that we can send characters on stdin to the process.
33 """
34 s = StringIO()
35 p = PipedProcess(sys.executable + ' -c "a = raw_input(); print a"',
36 out_callback=s.write, )
37 p.start()
38 test_string = '12345\n'
39 while not hasattr(p, 'process'):
40 sleep(0.1)
41 p.process.stdin.write(test_string)
42 p.join()
43 assert s.getvalue() == test_string
44
45
46 def test_kill():
47 """ Check that we can kill a process, and its subprocess.
48 """
49 s = StringIO()
50 p = PipedProcess(sys.executable + ' -c "a = raw_input();"',
51 out_callback=s.write, )
52 p.start()
53 while not hasattr(p, 'process'):
54 sleep(0.1)
55 p.process.kill()
56 assert p.process.poll() is not None
57
58
59 if __name__ == '__main__':
60 test_capture_out()
61 test_io()
62 test_kill()
63
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
@@ -0,0 +1,428 b''
1 # encoding: utf-8
2 """
3 A Wx widget to act as a console and input commands.
4
5 This widget deals with prompts and provides an edit buffer
6 restricted to after the last prompt.
7 """
8
9 __docformat__ = "restructuredtext en"
10
11 #-------------------------------------------------------------------------------
12 # Copyright (C) 2008 The IPython Development Team
13 #
14 # Distributed under the terms of the BSD License. The full license is
15 # in the file COPYING, distributed as part of this software.
16 #-------------------------------------------------------------------------------
17
18 #-------------------------------------------------------------------------------
19 # Imports
20 #-------------------------------------------------------------------------------
21
22 import wx
23 import wx.stc as stc
24
25 from wx.py import editwindow
26 import sys
27 LINESEP = '\n'
28 if sys.platform == 'win32':
29 LINESEP = '\n\r'
30
31 import re
32
33 # FIXME: Need to provide an API for non user-generated display on the
34 # screen: this should not be editable by the user.
35
36 _DEFAULT_SIZE = 10
37 if sys.platform == 'darwin':
38 _DEFAULT_STYLE = 12
39
40 _DEFAULT_STYLE = {
41 'stdout' : 'fore:#0000FF',
42 'stderr' : 'fore:#007f00',
43 'trace' : 'fore:#FF0000',
44
45 'default' : 'size:%d' % _DEFAULT_SIZE,
46 'bracegood' : 'fore:#00AA00,back:#000000,bold',
47 'bracebad' : 'fore:#FF0000,back:#000000,bold',
48
49 # properties for the various Python lexer styles
50 'comment' : 'fore:#007F00',
51 'number' : 'fore:#007F7F',
52 'string' : 'fore:#7F007F,italic',
53 'char' : 'fore:#7F007F,italic',
54 'keyword' : 'fore:#00007F,bold',
55 'triple' : 'fore:#7F0000',
56 'tripledouble' : 'fore:#7F0000',
57 'class' : 'fore:#0000FF,bold,underline',
58 'def' : 'fore:#007F7F,bold',
59 'operator' : 'bold'
60 }
61
62 # new style numbers
63 _STDOUT_STYLE = 15
64 _STDERR_STYLE = 16
65 _TRACE_STYLE = 17
66
67
68 # system colors
69 #SYS_COLOUR_BACKGROUND = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BACKGROUND)
70
71 #-------------------------------------------------------------------------------
72 # The console widget class
73 #-------------------------------------------------------------------------------
74 class ConsoleWidget(editwindow.EditWindow):
75 """ Specialized styled text control view for console-like workflow.
76
77 This widget is mainly interested in dealing with the prompt and
78 keeping the cursor inside the editing line.
79 """
80
81 # This is where the title captured from the ANSI escape sequences are
82 # stored.
83 title = 'Console'
84
85 # The buffer being edited.
86 def _set_input_buffer(self, string):
87 self.SetSelection(self.current_prompt_pos, self.GetLength())
88 self.ReplaceSelection(string)
89 self.GotoPos(self.GetLength())
90
91 def _get_input_buffer(self):
92 """ Returns the text in current edit buffer.
93 """
94 input_buffer = self.GetTextRange(self.current_prompt_pos,
95 self.GetLength())
96 input_buffer = input_buffer.replace(LINESEP, '\n')
97 return input_buffer
98
99 input_buffer = property(_get_input_buffer, _set_input_buffer)
100
101 style = _DEFAULT_STYLE.copy()
102
103 # Translation table from ANSI escape sequences to color. Override
104 # this to specify your colors.
105 ANSI_STYLES = {'0;30': [0, 'BLACK'], '0;31': [1, 'RED'],
106 '0;32': [2, 'GREEN'], '0;33': [3, 'BROWN'],
107 '0;34': [4, 'BLUE'], '0;35': [5, 'PURPLE'],
108 '0;36': [6, 'CYAN'], '0;37': [7, 'LIGHT GREY'],
109 '1;30': [8, 'DARK GREY'], '1;31': [9, 'RED'],
110 '1;32': [10, 'SEA GREEN'], '1;33': [11, 'YELLOW'],
111 '1;34': [12, 'LIGHT BLUE'], '1;35':
112 [13, 'MEDIUM VIOLET RED'],
113 '1;36': [14, 'LIGHT STEEL BLUE'], '1;37': [15, 'YELLOW']}
114
115 # The color of the carret (call _apply_style() after setting)
116 carret_color = 'BLACK'
117
118 #--------------------------------------------------------------------------
119 # Public API
120 #--------------------------------------------------------------------------
121
122 def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition,
123 size=wx.DefaultSize, style=0, ):
124 editwindow.EditWindow.__init__(self, parent, id, pos, size, style)
125 self._configure_scintilla()
126
127 self.Bind(wx.EVT_KEY_DOWN, self._on_key_down)
128 self.Bind(wx.EVT_KEY_UP, self._on_key_up)
129
130
131 def write(self, text, refresh=True):
132 """ Write given text to buffer, while translating the ansi escape
133 sequences.
134 """
135 # XXX: do not put print statements to sys.stdout/sys.stderr in
136 # this method, the print statements will call this method, as
137 # you will end up with an infinit loop
138 title = self.title_pat.split(text)
139 if len(title)>1:
140 self.title = title[-2]
141
142 text = self.title_pat.sub('', text)
143 segments = self.color_pat.split(text)
144 segment = segments.pop(0)
145 self.GotoPos(self.GetLength())
146 self.StartStyling(self.GetLength(), 0xFF)
147 try:
148 self.AppendText(segment)
149 except UnicodeDecodeError:
150 # XXX: Do I really want to skip the exception?
151 pass
152
153 if segments:
154 for ansi_tag, text in zip(segments[::2], segments[1::2]):
155 self.StartStyling(self.GetLength(), 0xFF)
156 try:
157 self.AppendText(text)
158 except UnicodeDecodeError:
159 # XXX: Do I really want to skip the exception?
160 pass
161
162 if ansi_tag not in self.ANSI_STYLES:
163 style = 0
164 else:
165 style = self.ANSI_STYLES[ansi_tag][0]
166
167 self.SetStyling(len(text), style)
168
169 self.GotoPos(self.GetLength())
170 if refresh:
171 # Maybe this is faster than wx.Yield()
172 self.ProcessEvent(wx.PaintEvent())
173 #wx.Yield()
174
175
176 def new_prompt(self, prompt):
177 """ Prints a prompt at start of line, and move the start of the
178 current block there.
179
180 The prompt can be given with ascii escape sequences.
181 """
182 self.write(prompt, refresh=False)
183 # now we update our cursor giving end of prompt
184 self.current_prompt_pos = self.GetLength()
185 self.current_prompt_line = self.GetCurrentLine()
186 wx.Yield()
187 self.EnsureCaretVisible()
188
189
190 def scroll_to_bottom(self):
191 maxrange = self.GetScrollRange(wx.VERTICAL)
192 self.ScrollLines(maxrange)
193
194
195 def pop_completion(self, possibilities, offset=0):
196 """ Pops up an autocompletion menu. Offset is the offset
197 in characters of the position at which the menu should
198 appear, relativ to the cursor.
199 """
200 self.AutoCompSetIgnoreCase(False)
201 self.AutoCompSetAutoHide(False)
202 self.AutoCompSetMaxHeight(len(possibilities))
203 self.AutoCompShow(offset, " ".join(possibilities))
204
205
206 def get_line_width(self):
207 """ Return the width of the line in characters.
208 """
209 return self.GetSize()[0]/self.GetCharWidth()
210
211 #--------------------------------------------------------------------------
212 # EditWindow API
213 #--------------------------------------------------------------------------
214
215 def OnUpdateUI(self, event):
216 """ Override the OnUpdateUI of the EditWindow class, to prevent
217 syntax highlighting both for faster redraw, and for more
218 consistent look and feel.
219 """
220
221 #--------------------------------------------------------------------------
222 # Private API
223 #--------------------------------------------------------------------------
224
225 def _apply_style(self):
226 """ Applies the colors for the different text elements and the
227 carret.
228 """
229 self.SetCaretForeground(self.carret_color)
230
231 #self.StyleClearAll()
232 self.StyleSetSpec(stc.STC_STYLE_BRACELIGHT,
233 "fore:#FF0000,back:#0000FF,bold")
234 self.StyleSetSpec(stc.STC_STYLE_BRACEBAD,
235 "fore:#000000,back:#FF0000,bold")
236
237 for style in self.ANSI_STYLES.values():
238 self.StyleSetSpec(style[0], "bold,fore:%s" % style[1])
239
240
241 def _configure_scintilla(self):
242 self.SetEOLMode(stc.STC_EOL_LF)
243
244 # Ctrl"+" or Ctrl "-" can be used to zoomin/zoomout the text inside
245 # the widget
246 self.CmdKeyAssign(ord('+'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMIN)
247 self.CmdKeyAssign(ord('-'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMOUT)
248 # Also allow Ctrl Shift "=" for poor non US keyboard users.
249 self.CmdKeyAssign(ord('='), stc.STC_SCMOD_CTRL|stc.STC_SCMOD_SHIFT,
250 stc.STC_CMD_ZOOMIN)
251
252 # Keys: we need to clear some of the keys the that don't play
253 # well with a console.
254 self.CmdKeyClear(ord('D'), stc.STC_SCMOD_CTRL)
255 self.CmdKeyClear(ord('L'), stc.STC_SCMOD_CTRL)
256 self.CmdKeyClear(ord('T'), stc.STC_SCMOD_CTRL)
257 self.CmdKeyClear(ord('A'), stc.STC_SCMOD_CTRL)
258
259 self.SetEOLMode(stc.STC_EOL_CRLF)
260 self.SetWrapMode(stc.STC_WRAP_CHAR)
261 self.SetWrapMode(stc.STC_WRAP_WORD)
262 self.SetBufferedDraw(True)
263 self.SetUseAntiAliasing(True)
264 self.SetLayoutCache(stc.STC_CACHE_PAGE)
265 self.SetUndoCollection(False)
266 self.SetUseTabs(True)
267 self.SetIndent(4)
268 self.SetTabWidth(4)
269
270 # we don't want scintilla's autocompletion to choose
271 # automaticaly out of a single choice list, as we pop it up
272 # automaticaly
273 self.AutoCompSetChooseSingle(False)
274 self.AutoCompSetMaxHeight(10)
275 # XXX: this doesn't seem to have an effect.
276 self.AutoCompSetFillUps('\n')
277
278 self.SetMargins(3, 3) #text is moved away from border with 3px
279 # Suppressing Scintilla margins
280 self.SetMarginWidth(0, 0)
281 self.SetMarginWidth(1, 0)
282 self.SetMarginWidth(2, 0)
283
284 self._apply_style()
285
286 # Xterm escape sequences
287 self.color_pat = re.compile('\x01?\x1b\[(.*?)m\x02?')
288 self.title_pat = re.compile('\x1b]0;(.*?)\x07')
289
290 #self.SetEdgeMode(stc.STC_EDGE_LINE)
291 #self.SetEdgeColumn(80)
292
293 # styles
294 p = self.style
295 self.StyleSetSpec(stc.STC_STYLE_DEFAULT, p['default'])
296 self.StyleClearAll()
297 self.StyleSetSpec(_STDOUT_STYLE, p['stdout'])
298 self.StyleSetSpec(_STDERR_STYLE, p['stderr'])
299 self.StyleSetSpec(_TRACE_STYLE, p['trace'])
300
301 self.StyleSetSpec(stc.STC_STYLE_BRACELIGHT, p['bracegood'])
302 self.StyleSetSpec(stc.STC_STYLE_BRACEBAD, p['bracebad'])
303 self.StyleSetSpec(stc.STC_P_COMMENTLINE, p['comment'])
304 self.StyleSetSpec(stc.STC_P_NUMBER, p['number'])
305 self.StyleSetSpec(stc.STC_P_STRING, p['string'])
306 self.StyleSetSpec(stc.STC_P_CHARACTER, p['char'])
307 self.StyleSetSpec(stc.STC_P_WORD, p['keyword'])
308 self.StyleSetSpec(stc.STC_P_WORD2, p['keyword'])
309 self.StyleSetSpec(stc.STC_P_TRIPLE, p['triple'])
310 self.StyleSetSpec(stc.STC_P_TRIPLEDOUBLE, p['tripledouble'])
311 self.StyleSetSpec(stc.STC_P_CLASSNAME, p['class'])
312 self.StyleSetSpec(stc.STC_P_DEFNAME, p['def'])
313 self.StyleSetSpec(stc.STC_P_OPERATOR, p['operator'])
314 self.StyleSetSpec(stc.STC_P_COMMENTBLOCK, p['comment'])
315
316 def _on_key_down(self, event, skip=True):
317 """ Key press callback used for correcting behavior for
318 console-like interfaces: the cursor is constraint to be after
319 the last prompt.
320
321 Return True if event as been catched.
322 """
323 catched = True
324 # Intercept some specific keys.
325 if event.KeyCode == ord('L') and event.ControlDown() :
326 self.scroll_to_bottom()
327 elif event.KeyCode == ord('K') and event.ControlDown() :
328 self.input_buffer = ''
329 elif event.KeyCode == ord('A') and event.ControlDown() :
330 self.GotoPos(self.GetLength())
331 self.SetSelectionStart(self.current_prompt_pos)
332 self.SetSelectionEnd(self.GetCurrentPos())
333 catched = True
334 elif event.KeyCode == ord('E') and event.ControlDown() :
335 self.GotoPos(self.GetLength())
336 catched = True
337 elif event.KeyCode == wx.WXK_PAGEUP:
338 self.ScrollPages(-1)
339 elif event.KeyCode == wx.WXK_PAGEDOWN:
340 self.ScrollPages(1)
341 elif event.KeyCode == wx.WXK_UP and event.ShiftDown():
342 self.ScrollLines(-1)
343 elif event.KeyCode == wx.WXK_DOWN and event.ShiftDown():
344 self.ScrollLines(1)
345 else:
346 catched = False
347
348 if self.AutoCompActive():
349 event.Skip()
350 else:
351 if event.KeyCode in (13, wx.WXK_NUMPAD_ENTER) and \
352 event.Modifiers in (wx.MOD_NONE, wx.MOD_WIN):
353 catched = True
354 self.CallTipCancel()
355 self.write('\n', refresh=False)
356 # Under windows scintilla seems to be doing funny stuff to the
357 # line returns here, but the getter for input_buffer filters
358 # this out.
359 if sys.platform == 'win32':
360 self.input_buffer = self.input_buffer
361 self._on_enter()
362
363 elif event.KeyCode == wx.WXK_HOME:
364 if event.Modifiers in (wx.MOD_NONE, wx.MOD_WIN):
365 self.GotoPos(self.current_prompt_pos)
366 catched = True
367
368 elif event.Modifiers == wx.MOD_SHIFT:
369 # FIXME: This behavior is not ideal: if the selection
370 # is already started, it will jump.
371 self.SetSelectionStart(self.current_prompt_pos)
372 self.SetSelectionEnd(self.GetCurrentPos())
373 catched = True
374
375 elif event.KeyCode == wx.WXK_UP:
376 if self.GetCurrentLine() > self.current_prompt_line:
377 if self.GetCurrentLine() == self.current_prompt_line + 1 \
378 and self.GetColumn(self.GetCurrentPos()) < \
379 self.GetColumn(self.current_prompt_pos):
380 self.GotoPos(self.current_prompt_pos)
381 else:
382 event.Skip()
383 catched = True
384
385 elif event.KeyCode in (wx.WXK_LEFT, wx.WXK_BACK):
386 if self.GetCurrentPos() > self.current_prompt_pos:
387 event.Skip()
388 catched = True
389
390 if skip and not catched:
391 # Put the cursor back in the edit region
392 if self.GetCurrentPos() < self.current_prompt_pos:
393 self.GotoPos(self.current_prompt_pos)
394 else:
395 event.Skip()
396
397 return catched
398
399
400 def _on_key_up(self, event, skip=True):
401 """ If cursor is outside the editing region, put it back.
402 """
403 event.Skip()
404 if self.GetCurrentPos() < self.current_prompt_pos:
405 self.GotoPos(self.current_prompt_pos)
406
407
408
409 if __name__ == '__main__':
410 # Some simple code to test the console widget.
411 class MainWindow(wx.Frame):
412 def __init__(self, parent, id, title):
413 wx.Frame.__init__(self, parent, id, title, size=(300,250))
414 self._sizer = wx.BoxSizer(wx.VERTICAL)
415 self.console_widget = ConsoleWidget(self)
416 self._sizer.Add(self.console_widget, 1, wx.EXPAND)
417 self.SetSizer(self._sizer)
418 self.SetAutoLayout(1)
419 self.Show(True)
420
421 app = wx.PySimpleApp()
422 w = MainWindow(None, wx.ID_ANY, 'ConsoleWidget')
423 w.SetSize((780, 460))
424 w.Show()
425
426 app.MainLoop()
427
428
@@ -0,0 +1,110 b''
1 """
2 Entry point for a simple application giving a graphical frontend to
3 ipython.
4 """
5
6 try:
7 import wx
8 except ImportError, e:
9 e.message = """%s
10 ________________________________________________________________________________
11 You need wxPython to run this application.
12 """ % e.message
13 e.args = (e.message, ) + e.args[1:]
14 raise e
15
16 from wx_frontend import WxController
17 import __builtin__
18
19
20 class IPythonXController(WxController):
21 """ Sub class of WxController that adds some application-specific
22 bindings.
23 """
24
25 debug = False
26
27 def __init__(self, *args, **kwargs):
28 WxController.__init__(self, *args, **kwargs)
29 self.ipython0.ask_exit = self.do_exit
30 # Scroll to top
31 maxrange = self.GetScrollRange(wx.VERTICAL)
32 self.ScrollLines(-maxrange)
33
34
35 def _on_key_down(self, event, skip=True):
36 # Intercept Ctrl-D to quit
37 if event.KeyCode == ord('D') and event.ControlDown() and \
38 self.input_buffer == '' and \
39 self._input_state == 'readline':
40 wx.CallAfter(self.ask_exit)
41 else:
42 WxController._on_key_down(self, event, skip=skip)
43
44
45 def ask_exit(self):
46 """ Ask the user whether to exit.
47 """
48 self._input_state = 'subprocess'
49 self.write('\n', refresh=False)
50 self.capture_output()
51 self.ipython0.shell.exit()
52 self.release_output()
53 if not self.ipython0.exit_now:
54 wx.CallAfter(self.new_prompt,
55 self.input_prompt_template.substitute(
56 number=self.last_result['number'] + 1))
57 else:
58 wx.CallAfter(wx.GetApp().Exit)
59 self.write('Exiting ...', refresh=False)
60
61
62 def do_exit(self):
63 """ Exits the interpreter, kills the windows.
64 """
65 WxController.do_exit(self)
66 self.release_output()
67 wx.CallAfter(wx.Exit)
68
69
70
71 class IPythonX(wx.Frame):
72 """ Main frame of the IPythonX app.
73 """
74
75 def __init__(self, parent, id, title, debug=False):
76 wx.Frame.__init__(self, parent, id, title, size=(300,250))
77 self._sizer = wx.BoxSizer(wx.VERTICAL)
78 self.shell = IPythonXController(self, debug=debug)
79 self._sizer.Add(self.shell, 1, wx.EXPAND)
80 self.SetSizer(self._sizer)
81 self.SetAutoLayout(1)
82 self.Show(True)
83
84
85 def main():
86 from optparse import OptionParser
87 usage = """usage: %prog [options]
88
89 Simple graphical frontend to IPython, using WxWidgets."""
90 parser = OptionParser(usage=usage)
91 parser.add_option("-d", "--debug",
92 action="store_true", dest="debug", default=False,
93 help="Enable debug message for the wx frontend.")
94
95 options, args = parser.parse_args()
96
97 # Clear the options, to avoid having the ipython0 instance complain
98 import sys
99 sys.argv = sys.argv[:1]
100
101 app = wx.PySimpleApp()
102 frame = IPythonX(None, wx.ID_ANY, 'IPythonX', debug=options.debug)
103 frame.shell.SetFocus()
104 frame.shell.app = app
105 frame.SetSize((680, 460))
106
107 app.MainLoop()
108
109 if __name__ == '__main__':
110 main()
This diff has been collapsed as it changes many lines, (510 lines changed) Show them Hide them
@@ -0,0 +1,510 b''
1 # encoding: utf-8 -*- test-case-name:
2 # FIXME: Need to add tests.
3 # ipython1.frontend.wx.tests.test_wx_frontend -*-
4
5 """Classes to provide a Wx frontend to the
6 IPython.kernel.core.interpreter.
7
8 This class inherits from ConsoleWidget, that provides a console-like
9 widget to provide a text-rendering widget suitable for a terminal.
10 """
11
12 __docformat__ = "restructuredtext en"
13
14 #-------------------------------------------------------------------------------
15 # Copyright (C) 2008 The IPython Development Team
16 #
17 # Distributed under the terms of the BSD License. The full license is in
18 # the file COPYING, distributed as part of this software.
19 #-------------------------------------------------------------------------------
20
21 #-------------------------------------------------------------------------------
22 # Imports
23 #-------------------------------------------------------------------------------
24
25 # Major library imports
26 import re
27 import __builtin__
28 from time import sleep
29 import sys
30 from threading import Lock
31 import string
32
33 import wx
34 from wx import stc
35
36 # Ipython-specific imports.
37 from IPython.frontend._process import PipedProcess
38 from console_widget import ConsoleWidget
39 from IPython.frontend.prefilterfrontend import PrefilterFrontEnd
40
41 #-------------------------------------------------------------------------------
42 # Constants
43 #-------------------------------------------------------------------------------
44
45 _COMPLETE_BUFFER_BG = '#FAFAF1' # Nice green
46 _INPUT_BUFFER_BG = '#FDFFD3' # Nice yellow
47 _ERROR_BG = '#FFF1F1' # Nice red
48
49 _COMPLETE_BUFFER_MARKER = 31
50 _ERROR_MARKER = 30
51 _INPUT_MARKER = 29
52
53 prompt_in1 = \
54 '\n\x01\x1b[0;34m\x02In [\x01\x1b[1;34m\x02$number\x01\x1b[0;34m\x02]: \x01\x1b[0m\x02'
55
56 prompt_out = \
57 '\x01\x1b[0;31m\x02Out[\x01\x1b[1;31m\x02$number\x01\x1b[0;31m\x02]: \x01\x1b[0m\x02'
58
59 #-------------------------------------------------------------------------------
60 # Classes to implement the Wx frontend
61 #-------------------------------------------------------------------------------
62 class WxController(ConsoleWidget, PrefilterFrontEnd):
63 """Classes to provide a Wx frontend to the
64 IPython.kernel.core.interpreter.
65
66 This class inherits from ConsoleWidget, that provides a console-like
67 widget to provide a text-rendering widget suitable for a terminal.
68 """
69
70 output_prompt_template = string.Template(prompt_out)
71
72 input_prompt_template = string.Template(prompt_in1)
73
74 # Print debug info on what is happening to the console.
75 debug = False
76
77 # The title of the terminal, as captured through the ANSI escape
78 # sequences.
79 def _set_title(self, title):
80 return self.Parent.SetTitle(title)
81
82 def _get_title(self):
83 return self.Parent.GetTitle()
84
85 title = property(_get_title, _set_title)
86
87
88 # The buffer being edited.
89 # We are duplicating the definition here because of multiple
90 # inheritence
91 def _set_input_buffer(self, string):
92 ConsoleWidget._set_input_buffer(self, string)
93 self._colorize_input_buffer()
94
95 def _get_input_buffer(self):
96 """ Returns the text in current edit buffer.
97 """
98 return ConsoleWidget._get_input_buffer(self)
99
100 input_buffer = property(_get_input_buffer, _set_input_buffer)
101
102
103 #--------------------------------------------------------------------------
104 # Private Attributes
105 #--------------------------------------------------------------------------
106
107 # A flag governing the behavior of the input. Can be:
108 #
109 # 'readline' for readline-like behavior with a prompt
110 # and an edit buffer.
111 # 'raw_input' similar to readline, but triggered by a raw-input
112 # call. Can be used by subclasses to act differently.
113 # 'subprocess' for sending the raw input directly to a
114 # subprocess.
115 # 'buffering' for buffering of the input, that will be used
116 # when the input state switches back to another state.
117 _input_state = 'readline'
118
119 # Attribute to store reference to the pipes of a subprocess, if we
120 # are running any.
121 _running_process = False
122
123 # A queue for writing fast streams to the screen without flooding the
124 # event loop
125 _out_buffer = []
126
127 # A lock to lock the _out_buffer to make sure we don't empty it
128 # while it is being swapped
129 _out_buffer_lock = Lock()
130
131 _markers = dict()
132
133 #--------------------------------------------------------------------------
134 # Public API
135 #--------------------------------------------------------------------------
136
137 def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition,
138 size=wx.DefaultSize, style=wx.CLIP_CHILDREN,
139 *args, **kwds):
140 """ Create Shell instance.
141 """
142 ConsoleWidget.__init__(self, parent, id, pos, size, style)
143 PrefilterFrontEnd.__init__(self, **kwds)
144
145 # Marker for complete buffer.
146 self.MarkerDefine(_COMPLETE_BUFFER_MARKER, stc.STC_MARK_BACKGROUND,
147 background=_COMPLETE_BUFFER_BG)
148 # Marker for current input buffer.
149 self.MarkerDefine(_INPUT_MARKER, stc.STC_MARK_BACKGROUND,
150 background=_INPUT_BUFFER_BG)
151 # Marker for tracebacks.
152 self.MarkerDefine(_ERROR_MARKER, stc.STC_MARK_BACKGROUND,
153 background=_ERROR_BG)
154
155 # A time for flushing the write buffer
156 BUFFER_FLUSH_TIMER_ID = 100
157 self._buffer_flush_timer = wx.Timer(self, BUFFER_FLUSH_TIMER_ID)
158 wx.EVT_TIMER(self, BUFFER_FLUSH_TIMER_ID, self._buffer_flush)
159
160 if 'debug' in kwds:
161 self.debug = kwds['debug']
162 kwds.pop('debug')
163
164 # Inject self in namespace, for debug
165 if self.debug:
166 self.shell.user_ns['self'] = self
167
168
169 def raw_input(self, prompt):
170 """ A replacement from python's raw_input.
171 """
172 self.new_prompt(prompt)
173 self._input_state = 'raw_input'
174 if hasattr(self, '_cursor'):
175 del self._cursor
176 self.SetCursor(wx.StockCursor(wx.CURSOR_CROSS))
177 self.waiting = True
178 self.__old_on_enter = self._on_enter
179 def my_on_enter():
180 self.waiting = False
181 self._on_enter = my_on_enter
182 # XXX: Busy waiting, ugly.
183 while self.waiting:
184 wx.Yield()
185 sleep(0.1)
186 self._on_enter = self.__old_on_enter
187 self._input_state = 'buffering'
188 self._cursor = wx.BusyCursor()
189 return self.input_buffer.rstrip('\n')
190
191
192 def system_call(self, command_string):
193 self._input_state = 'subprocess'
194 self._running_process = PipedProcess(command_string,
195 out_callback=self.buffered_write,
196 end_callback = self._end_system_call)
197 self._running_process.start()
198 # XXX: another one of these polling loops to have a blocking
199 # call
200 wx.Yield()
201 while self._running_process:
202 wx.Yield()
203 sleep(0.1)
204 # Be sure to flush the buffer.
205 self._buffer_flush(event=None)
206
207
208 def do_calltip(self):
209 """ Analyse current and displays useful calltip for it.
210 """
211 if self.debug:
212 print >>sys.__stdout__, "do_calltip"
213 separators = re.compile('[\s\{\}\[\]\(\)\= ,:]')
214 symbol = self.input_buffer
215 symbol_string = separators.split(symbol)[-1]
216 base_symbol_string = symbol_string.split('.')[0]
217 if base_symbol_string in self.shell.user_ns:
218 symbol = self.shell.user_ns[base_symbol_string]
219 elif base_symbol_string in self.shell.user_global_ns:
220 symbol = self.shell.user_global_ns[base_symbol_string]
221 elif base_symbol_string in __builtin__.__dict__:
222 symbol = __builtin__.__dict__[base_symbol_string]
223 else:
224 return False
225 try:
226 for name in symbol_string.split('.')[1:] + ['__doc__']:
227 symbol = getattr(symbol, name)
228 self.AutoCompCancel()
229 wx.Yield()
230 self.CallTipShow(self.GetCurrentPos(), symbol)
231 except:
232 # The retrieve symbol couldn't be converted to a string
233 pass
234
235
236 def _popup_completion(self, create=False):
237 """ Updates the popup completion menu if it exists. If create is
238 true, open the menu.
239 """
240 if self.debug:
241 print >>sys.__stdout__, "_popup_completion",
242 line = self.input_buffer
243 if (self.AutoCompActive() and not line[-1] == '.') \
244 or create==True:
245 suggestion, completions = self.complete(line)
246 offset=0
247 if completions:
248 complete_sep = re.compile('[\s\{\}\[\]\(\)\= ,:]')
249 residual = complete_sep.split(line)[-1]
250 offset = len(residual)
251 self.pop_completion(completions, offset=offset)
252 if self.debug:
253 print >>sys.__stdout__, completions
254
255
256 def buffered_write(self, text):
257 """ A write method for streams, that caches the stream in order
258 to avoid flooding the event loop.
259
260 This can be called outside of the main loop, in separate
261 threads.
262 """
263 self._out_buffer_lock.acquire()
264 self._out_buffer.append(text)
265 self._out_buffer_lock.release()
266 if not self._buffer_flush_timer.IsRunning():
267 wx.CallAfter(self._buffer_flush_timer.Start,
268 milliseconds=100, oneShot=True)
269
270
271 #--------------------------------------------------------------------------
272 # LineFrontEnd interface
273 #--------------------------------------------------------------------------
274
275 def execute(self, python_string, raw_string=None):
276 self._input_state = 'buffering'
277 self.CallTipCancel()
278 self._cursor = wx.BusyCursor()
279 if raw_string is None:
280 raw_string = python_string
281 end_line = self.current_prompt_line \
282 + max(1, len(raw_string.split('\n'))-1)
283 for i in range(self.current_prompt_line, end_line):
284 if i in self._markers:
285 self.MarkerDeleteHandle(self._markers[i])
286 self._markers[i] = self.MarkerAdd(i, _COMPLETE_BUFFER_MARKER)
287 # Update the display:
288 wx.Yield()
289 self.GotoPos(self.GetLength())
290 PrefilterFrontEnd.execute(self, python_string, raw_string=raw_string)
291
292 def save_output_hooks(self):
293 self.__old_raw_input = __builtin__.raw_input
294 PrefilterFrontEnd.save_output_hooks(self)
295
296 def capture_output(self):
297 __builtin__.raw_input = self.raw_input
298 self.SetLexer(stc.STC_LEX_NULL)
299 PrefilterFrontEnd.capture_output(self)
300
301
302 def release_output(self):
303 __builtin__.raw_input = self.__old_raw_input
304 PrefilterFrontEnd.release_output(self)
305 self.SetLexer(stc.STC_LEX_PYTHON)
306
307
308 def after_execute(self):
309 PrefilterFrontEnd.after_execute(self)
310 # Clear the wait cursor
311 if hasattr(self, '_cursor'):
312 del self._cursor
313 self.SetCursor(wx.StockCursor(wx.CURSOR_CHAR))
314
315
316 def show_traceback(self):
317 start_line = self.GetCurrentLine()
318 PrefilterFrontEnd.show_traceback(self)
319 wx.Yield()
320 for i in range(start_line, self.GetCurrentLine()):
321 self._markers[i] = self.MarkerAdd(i, _ERROR_MARKER)
322
323
324 #--------------------------------------------------------------------------
325 # ConsoleWidget interface
326 #--------------------------------------------------------------------------
327
328 def new_prompt(self, prompt):
329 """ Display a new prompt, and start a new input buffer.
330 """
331 self._input_state = 'readline'
332 ConsoleWidget.new_prompt(self, prompt)
333 i = self.current_prompt_line
334 self._markers[i] = self.MarkerAdd(i, _INPUT_MARKER)
335
336
337 def write(self, *args, **kwargs):
338 # Avoid multiple inheritence, be explicit about which
339 # parent method class gets called
340 ConsoleWidget.write(self, *args, **kwargs)
341
342
343 def _on_key_down(self, event, skip=True):
344 """ Capture the character events, let the parent
345 widget handle them, and put our logic afterward.
346 """
347 # FIXME: This method needs to be broken down in smaller ones.
348 current_line_number = self.GetCurrentLine()
349 if event.KeyCode in (ord('c'), ord('C')) and event.ControlDown():
350 # Capture Control-C
351 if self._input_state == 'subprocess':
352 if self.debug:
353 print >>sys.__stderr__, 'Killing running process'
354 self._running_process.process.kill()
355 elif self._input_state == 'buffering':
356 if self.debug:
357 print >>sys.__stderr__, 'Raising KeyboardInterrupt'
358 raise KeyboardInterrupt
359 # XXX: We need to make really sure we
360 # get back to a prompt.
361 elif self._input_state == 'subprocess' and (
362 ( event.KeyCode<256 and
363 not event.ControlDown() )
364 or
365 ( event.KeyCode in (ord('d'), ord('D')) and
366 event.ControlDown())):
367 # We are running a process, we redirect keys.
368 ConsoleWidget._on_key_down(self, event, skip=skip)
369 char = chr(event.KeyCode)
370 # Deal with some inconsistency in wx keycodes:
371 if char == '\r':
372 char = '\n'
373 elif not event.ShiftDown():
374 char = char.lower()
375 if event.ControlDown() and event.KeyCode in (ord('d'), ord('D')):
376 char = '\04'
377 self._running_process.process.stdin.write(char)
378 self._running_process.process.stdin.flush()
379 elif event.KeyCode in (ord('('), 57):
380 # Calltips
381 event.Skip()
382 self.do_calltip()
383 elif self.AutoCompActive() and not event.KeyCode == ord('\t'):
384 event.Skip()
385 if event.KeyCode in (wx.WXK_BACK, wx.WXK_DELETE):
386 wx.CallAfter(self._popup_completion, create=True)
387 elif not event.KeyCode in (wx.WXK_UP, wx.WXK_DOWN, wx.WXK_LEFT,
388 wx.WXK_RIGHT, wx.WXK_ESCAPE):
389 wx.CallAfter(self._popup_completion)
390 else:
391 # Up history
392 if event.KeyCode == wx.WXK_UP and (
393 ( current_line_number == self.current_prompt_line and
394 event.Modifiers in (wx.MOD_NONE, wx.MOD_WIN) )
395 or event.ControlDown() ):
396 new_buffer = self.get_history_previous(
397 self.input_buffer)
398 if new_buffer is not None:
399 self.input_buffer = new_buffer
400 if self.GetCurrentLine() > self.current_prompt_line:
401 # Go to first line, for seemless history up.
402 self.GotoPos(self.current_prompt_pos)
403 # Down history
404 elif event.KeyCode == wx.WXK_DOWN and (
405 ( current_line_number == self.LineCount -1 and
406 event.Modifiers in (wx.MOD_NONE, wx.MOD_WIN) )
407 or event.ControlDown() ):
408 new_buffer = self.get_history_next()
409 if new_buffer is not None:
410 self.input_buffer = new_buffer
411 # Tab-completion
412 elif event.KeyCode == ord('\t'):
413 last_line = self.input_buffer.split('\n')[-1]
414 if not re.match(r'^\s*$', last_line):
415 self.complete_current_input()
416 if self.AutoCompActive():
417 wx.CallAfter(self._popup_completion, create=True)
418 else:
419 event.Skip()
420 else:
421 ConsoleWidget._on_key_down(self, event, skip=skip)
422
423
424 def _on_key_up(self, event, skip=True):
425 """ Called when any key is released.
426 """
427 if event.KeyCode in (59, ord('.')):
428 # Intercepting '.'
429 event.Skip()
430 self._popup_completion(create=True)
431 else:
432 ConsoleWidget._on_key_up(self, event, skip=skip)
433
434
435 def _on_enter(self):
436 """ Called on return key down, in readline input_state.
437 """
438 if self.debug:
439 print >>sys.__stdout__, repr(self.input_buffer)
440 PrefilterFrontEnd._on_enter(self)
441
442
443 #--------------------------------------------------------------------------
444 # EditWindow API
445 #--------------------------------------------------------------------------
446
447 def OnUpdateUI(self, event):
448 """ Override the OnUpdateUI of the EditWindow class, to prevent
449 syntax highlighting both for faster redraw, and for more
450 consistent look and feel.
451 """
452 if not self._input_state == 'readline':
453 ConsoleWidget.OnUpdateUI(self, event)
454
455 #--------------------------------------------------------------------------
456 # Private API
457 #--------------------------------------------------------------------------
458
459 def _end_system_call(self):
460 """ Called at the end of a system call.
461 """
462 self._input_state = 'buffering'
463 self._running_process = False
464
465
466 def _buffer_flush(self, event):
467 """ Called by the timer to flush the write buffer.
468
469 This is always called in the mainloop, by the wx timer.
470 """
471 self._out_buffer_lock.acquire()
472 _out_buffer = self._out_buffer
473 self._out_buffer = []
474 self._out_buffer_lock.release()
475 self.write(''.join(_out_buffer), refresh=False)
476
477
478 def _colorize_input_buffer(self):
479 """ Keep the input buffer lines at a bright color.
480 """
481 if not self._input_state in ('readline', 'raw_input'):
482 return
483 end_line = self.GetCurrentLine()
484 if not sys.platform == 'win32':
485 end_line += 1
486 for i in range(self.current_prompt_line, end_line):
487 if i in self._markers:
488 self.MarkerDeleteHandle(self._markers[i])
489 self._markers[i] = self.MarkerAdd(i, _INPUT_MARKER)
490
491
492 if __name__ == '__main__':
493 class MainWindow(wx.Frame):
494 def __init__(self, parent, id, title):
495 wx.Frame.__init__(self, parent, id, title, size=(300,250))
496 self._sizer = wx.BoxSizer(wx.VERTICAL)
497 self.shell = WxController(self)
498 self._sizer.Add(self.shell, 1, wx.EXPAND)
499 self.SetSizer(self._sizer)
500 self.SetAutoLayout(1)
501 self.Show(True)
502
503 app = wx.PySimpleApp()
504 frame = MainWindow(None, wx.ID_ANY, 'Ipython')
505 frame.shell.SetFocus()
506 frame.SetSize((680, 460))
507 self = frame.shell
508
509 app.MainLoop()
510
@@ -0,0 +1,34 b''
1 # encoding: utf-8
2 # -*- test-case-name: IPython.frontend.tests.test_frontendbase -*-
3 """
4 zope.interface mock. If zope is installed, this module provides a zope
5 interface classes, if not it provides mocks for them.
6
7 Classes provided:
8 Interface, Attribute, implements, classProvides
9 """
10 __docformat__ = "restructuredtext en"
11
12 #-------------------------------------------------------------------------------
13 # Copyright (C) 2008 The IPython Development Team
14 #
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
17 #-------------------------------------------------------------------------------
18
19 #-------------------------------------------------------------------------------
20 # Imports
21 #-------------------------------------------------------------------------------
22 import string
23 import uuid
24 import _ast
25
26 try:
27 from zope.interface import Interface, Attribute, implements, classProvides
28 except ImportError:
29 #zope.interface is not available
30 Interface = object
31 def Attribute(name, doc): pass
32 def implements(interface): pass
33 def classProvides(interface): pass
34
@@ -0,0 +1,81 b''
1 # encoding: utf-8
2
3 """
4 Stdout/stderr redirector, at the OS level, using file descriptors.
5
6 This also works under windows.
7 """
8
9 __docformat__ = "restructuredtext en"
10
11 #-------------------------------------------------------------------------------
12 # Copyright (C) 2008 The IPython Development Team
13 #
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
16 #-------------------------------------------------------------------------------
17
18
19 import os
20 import sys
21
22 STDOUT = 1
23 STDERR = 2
24
25 class FDRedirector(object):
26 """ Class to redirect output (stdout or stderr) at the OS level using
27 file descriptors.
28 """
29
30 def __init__(self, fd=STDOUT):
31 """ fd is the file descriptor of the outpout you want to capture.
32 It can be STDOUT or STERR.
33 """
34 self.fd = fd
35 self.started = False
36 self.piper = None
37 self.pipew = None
38
39 def start(self):
40 """ Setup the redirection.
41 """
42 if not self.started:
43 self.oldhandle = os.dup(self.fd)
44 self.piper, self.pipew = os.pipe()
45 os.dup2(self.pipew, self.fd)
46 os.close(self.pipew)
47
48 self.started = True
49
50 def flush(self):
51 """ Flush the captured output, similar to the flush method of any
52 stream.
53 """
54 if self.fd == STDOUT:
55 sys.stdout.flush()
56 elif self.fd == STDERR:
57 sys.stderr.flush()
58
59 def stop(self):
60 """ Unset the redirection and return the captured output.
61 """
62 if self.started:
63 self.flush()
64 os.dup2(self.oldhandle, self.fd)
65 os.close(self.oldhandle)
66 f = os.fdopen(self.piper, 'r')
67 output = f.read()
68 f.close()
69
70 self.started = False
71 return output
72 else:
73 return ''
74
75 def getvalue(self):
76 """ Return the output captured since the last getvalue, or the
77 start of the redirection.
78 """
79 output = self.stop()
80 self.start()
81 return output
@@ -0,0 +1,66 b''
1 # encoding: utf-8
2
3 """ File like object that redirects its write calls to a given callback."""
4
5 __docformat__ = "restructuredtext en"
6
7 #-------------------------------------------------------------------------------
8 # Copyright (C) 2008 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 import sys
15
16 class FileLike(object):
17 """ FileLike object that redirects all write to a callback.
18
19 Only the write-related methods are implemented, as well as those
20 required to read a StringIO.
21 """
22 closed = False
23
24 def __init__(self, write_callback):
25 self.write = write_callback
26
27 def flush(self):
28 """ This method is there for compatibility with other file-like
29 objects.
30 """
31 pass
32
33 def close(self):
34 """ This method is there for compatibility with other file-like
35 objects.
36 """
37 pass
38
39 def writelines(self, lines):
40 map(self.write, lines)
41
42 def isatty(self):
43 """ This method is there for compatibility with other file-like
44 objects.
45 """
46 return False
47
48 def getvalue(self):
49 """ This method is there for compatibility with other file-like
50 objects.
51 """
52 return ''
53
54 def reset(self):
55 """ This method is there for compatibility with other file-like
56 objects.
57 """
58 pass
59
60 def truncate(self):
61 """ This method is there for compatibility with other file-like
62 objects.
63 """
64 pass
65
66
@@ -0,0 +1,97 b''
1 # encoding: utf-8
2
3 """
4 Trap stdout/stderr, including at the OS level. Calls a callback with
5 the output each time Python tries to write to the stdout or stderr.
6 """
7
8 __docformat__ = "restructuredtext en"
9
10 #-------------------------------------------------------------------------------
11 # Copyright (C) 2008 The IPython Development Team
12 #
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
15 #-------------------------------------------------------------------------------
16
17 #-------------------------------------------------------------------------------
18 # Imports
19 #-------------------------------------------------------------------------------
20
21 from fd_redirector import FDRedirector, STDOUT, STDERR
22
23 from IPython.kernel.core.file_like import FileLike
24 from IPython.kernel.core.output_trap import OutputTrap
25
26 class RedirectorOutputTrap(OutputTrap):
27 """ Object which can trap text sent to stdout and stderr.
28 """
29
30 #------------------------------------------------------------------------
31 # OutputTrap interface.
32 #------------------------------------------------------------------------
33 def __init__(self, out_callback, err_callback):
34 """
35 out_callback : callable called when there is output in the stdout
36 err_callback : callable called when there is output in the stderr
37 """
38 # Callback invoked on write to stdout and stderr
39 self.out_callback = out_callback
40 self.err_callback = err_callback
41
42 # File descriptor redirectors, to capture non-Python
43 # output.
44 self.out_redirector = FDRedirector(STDOUT)
45 self.err_redirector = FDRedirector(STDERR)
46
47 # Call the base class with file like objects that will trigger
48 # our callbacks
49 OutputTrap.__init__(self, out=FileLike(self.on_out_write),
50 err=FileLike(self.on_err_write), )
51
52
53 def set(self):
54 """ Set the hooks: set the redirectors and call the base class.
55 """
56 self.out_redirector.start()
57 self.err_redirector.start()
58 OutputTrap.set(self)
59
60
61 def unset(self):
62 """ Remove the hooks: call the base class and stop the
63 redirectors.
64 """
65 OutputTrap.unset(self)
66 # Flush the redirectors before stopping them
67 self.on_err_write('')
68 self.err_redirector.stop()
69 self.on_out_write('')
70 self.out_redirector.stop()
71
72
73 #------------------------------------------------------------------------
74 # Callbacks for synchronous output
75 #------------------------------------------------------------------------
76 def on_out_write(self, string):
77 """ Callback called when there is some Python output on stdout.
78 """
79 try:
80 self.out_callback(self.out_redirector.getvalue() + string)
81 except:
82 # If tracebacks are happening and we can't see them, it is
83 # quasy impossible to debug
84 self.unset()
85 raise
86
87 def on_err_write(self, string):
88 """ Callback called when there is some Python output on stderr.
89 """
90 try:
91 self.err_callback(self.err_redirector.getvalue() + string)
92 except:
93 # If tracebacks are happening and we can't see them, it is
94 # quasy impossible to debug
95 self.unset()
96 raise
97
@@ -0,0 +1,53 b''
1 # encoding: utf-8
2
3 """Object to manage sys.excepthook().
4
5 Synchronous version: prints errors when called.
6 """
7
8 __docformat__ = "restructuredtext en"
9
10 #-------------------------------------------------------------------------------
11 # Copyright (C) 2008 The IPython Development Team
12 #
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
15 #-------------------------------------------------------------------------------
16
17 #-------------------------------------------------------------------------------
18 # Imports
19 #-------------------------------------------------------------------------------
20 from traceback_trap import TracebackTrap
21 from IPython.ultraTB import ColorTB
22
23 class SyncTracebackTrap(TracebackTrap):
24 """ TracebackTrap that displays immediatly the traceback in addition
25 to capturing it. Useful in frontends, as without this traceback trap,
26 some tracebacks never get displayed.
27 """
28
29 def __init__(self, sync_formatter=None, formatters=None,
30 raiseException=True):
31 """
32 sync_formatter: Callable to display the traceback.
33 formatters: A list of formatters to apply.
34 """
35 TracebackTrap.__init__(self, formatters=formatters)
36 if sync_formatter is None:
37 sync_formatter = ColorTB(color_scheme='LightBG')
38 self.sync_formatter = sync_formatter
39 self.raiseException = raiseException
40
41
42 def hook(self, *args):
43 """ This method actually implements the hook.
44 """
45 self.args = args
46 if not self.raiseException:
47 print self.sync_formatter(*self.args)
48 else:
49 raise
50
51
52
53
@@ -0,0 +1,61 b''
1 # encoding: utf-8
2 """
3 Test the output capture at the OS level, using file descriptors.
4 """
5
6 __docformat__ = "restructuredtext en"
7
8 #-------------------------------------------------------------------------------
9 # Copyright (C) 2008 The IPython Development Team
10 #
11 # Distributed under the terms of the BSD License. The full license is
12 # in the file COPYING, distributed as part of this software.
13 #-------------------------------------------------------------------------------
14
15
16 import os
17 from cStringIO import StringIO
18
19
20 def test_redirector():
21 """ Checks that the redirector can be used to do synchronous capture.
22 """
23 from IPython.kernel.core.fd_redirector import FDRedirector
24 r = FDRedirector()
25 out = StringIO()
26 try:
27 r.start()
28 for i in range(10):
29 os.system('echo %ic' % i)
30 print >>out, r.getvalue(),
31 print >>out, i
32 except:
33 r.stop()
34 raise
35 r.stop()
36 assert out.getvalue() == "".join("%ic\n%i\n" %(i, i) for i in range(10))
37
38
39 def test_redirector_output_trap():
40 """ This test check not only that the redirector_output_trap does
41 trap the output, but also that it does it in a gready way, that
42 is by calling the callback ASAP.
43 """
44 from IPython.kernel.core.redirector_output_trap import RedirectorOutputTrap
45 out = StringIO()
46 trap = RedirectorOutputTrap(out.write, out.write)
47 try:
48 trap.set()
49 for i in range(10):
50 os.system('echo %ic' % i)
51 print "%ip" % i
52 print >>out, i
53 except:
54 trap.unset()
55 raise
56 trap.unset()
57 assert out.getvalue() == "".join("%ic\n%ip\n%i\n" %(i, i, i)
58 for i in range(10))
59
60
61
@@ -0,0 +1,11 b''
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 """IPythonX -- An enhanced Interactive Python
4
5 This script starts the Wx graphical frontend. This is experimental so
6 far.
7 """
8
9 from IPython.frontend.wx import ipythonx
10
11 ipythonx.main()
@@ -1,62 +1,62 b''
1 """ Legacy stuff
1 """ Legacy stuff
2
2
3 Various stuff that are there for historical / familiarity reasons.
3 Various stuff that are there for historical / familiarity reasons.
4
4
5 This is automatically imported by default profile, though not other profiles
5 This is automatically imported by default profile, though not other profiles
6 (e.g. 'sh' profile).
6 (e.g. 'sh' profile).
7
7
8 Stuff that is considered obsolete / redundant is gradually moved here.
8 Stuff that is considered obsolete / redundant is gradually moved here.
9
9
10 """
10 """
11
11
12 import IPython.ipapi
12 import IPython.ipapi
13 ip = IPython.ipapi.get()
13 ip = IPython.ipapi.get()
14
14
15 import os,sys
15 import os,sys
16
16
17 from IPython.genutils import *
17 from IPython.genutils import *
18
18
19 # use rehashx
19 # use rehashx
20
20
21 def magic_rehash(self, parameter_s = ''):
21 def magic_rehash(self, parameter_s = ''):
22 """Update the alias table with all entries in $PATH.
22 """Update the alias table with all entries in $PATH.
23
23
24 This version does no checks on execute permissions or whether the
24 This version does no checks on execute permissions or whether the
25 contents of $PATH are truly files (instead of directories or something
25 contents of $PATH are truly files (instead of directories or something
26 else). For such a safer (but slower) version, use %rehashx."""
26 else). For such a safer (but slower) version, use %rehashx."""
27
27
28 # This function (and rehashx) manipulate the alias_table directly
28 # This function (and rehashx) manipulate the alias_table directly
29 # rather than calling magic_alias, for speed reasons. A rehash on a
29 # rather than calling magic_alias, for speed reasons. A rehash on a
30 # typical Linux box involves several thousand entries, so efficiency
30 # typical Linux box involves several thousand entries, so efficiency
31 # here is a top concern.
31 # here is a top concern.
32
32
33 path = filter(os.path.isdir,os.environ.get('PATH','').split(os.pathsep))
33 path = filter(os.path.isdir,os.environ.get('PATH','').split(os.pathsep))
34 alias_table = self.shell.alias_table
34 alias_table = self.shell.alias_table
35 for pdir in path:
35 for pdir in path:
36 for ff in os.listdir(pdir):
36 for ff in os.listdir(pdir):
37 # each entry in the alias table must be (N,name), where
37 # each entry in the alias table must be (N,name), where
38 # N is the number of positional arguments of the alias.
38 # N is the number of positional arguments of the alias.
39 alias_table[ff] = (0,ff)
39 alias_table[ff] = (0,ff)
40 # Make sure the alias table doesn't contain keywords or builtins
40 # Make sure the alias table doesn't contain keywords or builtins
41 self.shell.alias_table_validate()
41 self.shell.alias_table_validate()
42 # Call again init_auto_alias() so we get 'rm -i' and other modified
42 # Call again init_auto_alias() so we get 'rm -i' and other modified
43 # aliases since %rehash will probably clobber them
43 # aliases since %rehash will probably clobber them
44 self.shell.init_auto_alias()
44 self.shell.init_auto_alias()
45
45
46 ip.expose_magic("rehash", magic_rehash)
46 ip.expose_magic("rehash", magic_rehash)
47
47
48 # Exit
48 # Exit
49 def magic_Quit(self, parameter_s=''):
49 def magic_Quit(self, parameter_s=''):
50 """Exit IPython without confirmation (like %Exit)."""
50 """Exit IPython without confirmation (like %Exit)."""
51
51
52 self.shell.exit_now = True
52 self.shell.ask_exit()
53
53
54 ip.expose_magic("Quit", magic_Quit)
54 ip.expose_magic("Quit", magic_Quit)
55
55
56
56
57 # make it autocallable fn if you really need it
57 # make it autocallable fn if you really need it
58 def magic_p(self, parameter_s=''):
58 def magic_p(self, parameter_s=''):
59 """Just a short alias for Python's 'print'."""
59 """Just a short alias for Python's 'print'."""
60 exec 'print ' + parameter_s in self.shell.user_ns
60 exec 'print ' + parameter_s in self.shell.user_ns
61
61
62 ip.expose_magic("p", magic_p)
62 ip.expose_magic("p", magic_p)
@@ -1,3350 +1,3350 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3
3
4 $Id: Magic.py 2996 2008-01-30 06:31:39Z fperez $"""
4 $Id: Magic.py 2996 2008-01-30 06:31:39Z fperez $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
12 #*****************************************************************************
13
13
14 #****************************************************************************
14 #****************************************************************************
15 # Modules and globals
15 # Modules and globals
16
16
17 from IPython import Release
17 from IPython import Release
18 __author__ = '%s <%s>\n%s <%s>' % \
18 __author__ = '%s <%s>\n%s <%s>' % \
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 __license__ = Release.license
20 __license__ = Release.license
21
21
22 # Python standard modules
22 # Python standard modules
23 import __builtin__
23 import __builtin__
24 import bdb
24 import bdb
25 import inspect
25 import inspect
26 import os
26 import os
27 import pdb
27 import pdb
28 import pydoc
28 import pydoc
29 import sys
29 import sys
30 import re
30 import re
31 import tempfile
31 import tempfile
32 import time
32 import time
33 import cPickle as pickle
33 import cPickle as pickle
34 import textwrap
34 import textwrap
35 from cStringIO import StringIO
35 from cStringIO import StringIO
36 from getopt import getopt,GetoptError
36 from getopt import getopt,GetoptError
37 from pprint import pprint, pformat
37 from pprint import pprint, pformat
38 from sets import Set
38 from sets import Set
39
39
40 # cProfile was added in Python2.5
40 # cProfile was added in Python2.5
41 try:
41 try:
42 import cProfile as profile
42 import cProfile as profile
43 import pstats
43 import pstats
44 except ImportError:
44 except ImportError:
45 # profile isn't bundled by default in Debian for license reasons
45 # profile isn't bundled by default in Debian for license reasons
46 try:
46 try:
47 import profile,pstats
47 import profile,pstats
48 except ImportError:
48 except ImportError:
49 profile = pstats = None
49 profile = pstats = None
50
50
51 # Homebrewed
51 # Homebrewed
52 import IPython
52 import IPython
53 from IPython import Debugger, OInspect, wildcard
53 from IPython import Debugger, OInspect, wildcard
54 from IPython.FakeModule import FakeModule
54 from IPython.FakeModule import FakeModule
55 from IPython.Itpl import Itpl, itpl, printpl,itplns
55 from IPython.Itpl import Itpl, itpl, printpl,itplns
56 from IPython.PyColorize import Parser
56 from IPython.PyColorize import Parser
57 from IPython.ipstruct import Struct
57 from IPython.ipstruct import Struct
58 from IPython.macro import Macro
58 from IPython.macro import Macro
59 from IPython.genutils import *
59 from IPython.genutils import *
60 from IPython import platutils
60 from IPython import platutils
61 import IPython.generics
61 import IPython.generics
62 import IPython.ipapi
62 import IPython.ipapi
63 from IPython.ipapi import UsageError
63 from IPython.ipapi import UsageError
64 from IPython.testing import decorators as testdec
64 from IPython.testing import decorators as testdec
65
65
66 #***************************************************************************
66 #***************************************************************************
67 # Utility functions
67 # Utility functions
68 def on_off(tag):
68 def on_off(tag):
69 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
69 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
70 return ['OFF','ON'][tag]
70 return ['OFF','ON'][tag]
71
71
72 class Bunch: pass
72 class Bunch: pass
73
73
74 def compress_dhist(dh):
74 def compress_dhist(dh):
75 head, tail = dh[:-10], dh[-10:]
75 head, tail = dh[:-10], dh[-10:]
76
76
77 newhead = []
77 newhead = []
78 done = Set()
78 done = Set()
79 for h in head:
79 for h in head:
80 if h in done:
80 if h in done:
81 continue
81 continue
82 newhead.append(h)
82 newhead.append(h)
83 done.add(h)
83 done.add(h)
84
84
85 return newhead + tail
85 return newhead + tail
86
86
87
87
88 #***************************************************************************
88 #***************************************************************************
89 # Main class implementing Magic functionality
89 # Main class implementing Magic functionality
90 class Magic:
90 class Magic:
91 """Magic functions for InteractiveShell.
91 """Magic functions for InteractiveShell.
92
92
93 Shell functions which can be reached as %function_name. All magic
93 Shell functions which can be reached as %function_name. All magic
94 functions should accept a string, which they can parse for their own
94 functions should accept a string, which they can parse for their own
95 needs. This can make some functions easier to type, eg `%cd ../`
95 needs. This can make some functions easier to type, eg `%cd ../`
96 vs. `%cd("../")`
96 vs. `%cd("../")`
97
97
98 ALL definitions MUST begin with the prefix magic_. The user won't need it
98 ALL definitions MUST begin with the prefix magic_. The user won't need it
99 at the command line, but it is is needed in the definition. """
99 at the command line, but it is is needed in the definition. """
100
100
101 # class globals
101 # class globals
102 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
102 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
103 'Automagic is ON, % prefix NOT needed for magic functions.']
103 'Automagic is ON, % prefix NOT needed for magic functions.']
104
104
105 #......................................................................
105 #......................................................................
106 # some utility functions
106 # some utility functions
107
107
108 def __init__(self,shell):
108 def __init__(self,shell):
109
109
110 self.options_table = {}
110 self.options_table = {}
111 if profile is None:
111 if profile is None:
112 self.magic_prun = self.profile_missing_notice
112 self.magic_prun = self.profile_missing_notice
113 self.shell = shell
113 self.shell = shell
114
114
115 # namespace for holding state we may need
115 # namespace for holding state we may need
116 self._magic_state = Bunch()
116 self._magic_state = Bunch()
117
117
118 def profile_missing_notice(self, *args, **kwargs):
118 def profile_missing_notice(self, *args, **kwargs):
119 error("""\
119 error("""\
120 The profile module could not be found. It has been removed from the standard
120 The profile module could not be found. It has been removed from the standard
121 python packages because of its non-free license. To use profiling, install the
121 python packages because of its non-free license. To use profiling, install the
122 python-profiler package from non-free.""")
122 python-profiler package from non-free.""")
123
123
124 def default_option(self,fn,optstr):
124 def default_option(self,fn,optstr):
125 """Make an entry in the options_table for fn, with value optstr"""
125 """Make an entry in the options_table for fn, with value optstr"""
126
126
127 if fn not in self.lsmagic():
127 if fn not in self.lsmagic():
128 error("%s is not a magic function" % fn)
128 error("%s is not a magic function" % fn)
129 self.options_table[fn] = optstr
129 self.options_table[fn] = optstr
130
130
131 def lsmagic(self):
131 def lsmagic(self):
132 """Return a list of currently available magic functions.
132 """Return a list of currently available magic functions.
133
133
134 Gives a list of the bare names after mangling (['ls','cd', ...], not
134 Gives a list of the bare names after mangling (['ls','cd', ...], not
135 ['magic_ls','magic_cd',...]"""
135 ['magic_ls','magic_cd',...]"""
136
136
137 # FIXME. This needs a cleanup, in the way the magics list is built.
137 # FIXME. This needs a cleanup, in the way the magics list is built.
138
138
139 # magics in class definition
139 # magics in class definition
140 class_magic = lambda fn: fn.startswith('magic_') and \
140 class_magic = lambda fn: fn.startswith('magic_') and \
141 callable(Magic.__dict__[fn])
141 callable(Magic.__dict__[fn])
142 # in instance namespace (run-time user additions)
142 # in instance namespace (run-time user additions)
143 inst_magic = lambda fn: fn.startswith('magic_') and \
143 inst_magic = lambda fn: fn.startswith('magic_') and \
144 callable(self.__dict__[fn])
144 callable(self.__dict__[fn])
145 # and bound magics by user (so they can access self):
145 # and bound magics by user (so they can access self):
146 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
146 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
147 callable(self.__class__.__dict__[fn])
147 callable(self.__class__.__dict__[fn])
148 magics = filter(class_magic,Magic.__dict__.keys()) + \
148 magics = filter(class_magic,Magic.__dict__.keys()) + \
149 filter(inst_magic,self.__dict__.keys()) + \
149 filter(inst_magic,self.__dict__.keys()) + \
150 filter(inst_bound_magic,self.__class__.__dict__.keys())
150 filter(inst_bound_magic,self.__class__.__dict__.keys())
151 out = []
151 out = []
152 for fn in Set(magics):
152 for fn in Set(magics):
153 out.append(fn.replace('magic_','',1))
153 out.append(fn.replace('magic_','',1))
154 out.sort()
154 out.sort()
155 return out
155 return out
156
156
157 def extract_input_slices(self,slices,raw=False):
157 def extract_input_slices(self,slices,raw=False):
158 """Return as a string a set of input history slices.
158 """Return as a string a set of input history slices.
159
159
160 Inputs:
160 Inputs:
161
161
162 - slices: the set of slices is given as a list of strings (like
162 - slices: the set of slices is given as a list of strings (like
163 ['1','4:8','9'], since this function is for use by magic functions
163 ['1','4:8','9'], since this function is for use by magic functions
164 which get their arguments as strings.
164 which get their arguments as strings.
165
165
166 Optional inputs:
166 Optional inputs:
167
167
168 - raw(False): by default, the processed input is used. If this is
168 - raw(False): by default, the processed input is used. If this is
169 true, the raw input history is used instead.
169 true, the raw input history is used instead.
170
170
171 Note that slices can be called with two notations:
171 Note that slices can be called with two notations:
172
172
173 N:M -> standard python form, means including items N...(M-1).
173 N:M -> standard python form, means including items N...(M-1).
174
174
175 N-M -> include items N..M (closed endpoint)."""
175 N-M -> include items N..M (closed endpoint)."""
176
176
177 if raw:
177 if raw:
178 hist = self.shell.input_hist_raw
178 hist = self.shell.input_hist_raw
179 else:
179 else:
180 hist = self.shell.input_hist
180 hist = self.shell.input_hist
181
181
182 cmds = []
182 cmds = []
183 for chunk in slices:
183 for chunk in slices:
184 if ':' in chunk:
184 if ':' in chunk:
185 ini,fin = map(int,chunk.split(':'))
185 ini,fin = map(int,chunk.split(':'))
186 elif '-' in chunk:
186 elif '-' in chunk:
187 ini,fin = map(int,chunk.split('-'))
187 ini,fin = map(int,chunk.split('-'))
188 fin += 1
188 fin += 1
189 else:
189 else:
190 ini = int(chunk)
190 ini = int(chunk)
191 fin = ini+1
191 fin = ini+1
192 cmds.append(hist[ini:fin])
192 cmds.append(hist[ini:fin])
193 return cmds
193 return cmds
194
194
195 def _ofind(self, oname, namespaces=None):
195 def _ofind(self, oname, namespaces=None):
196 """Find an object in the available namespaces.
196 """Find an object in the available namespaces.
197
197
198 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
198 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
199
199
200 Has special code to detect magic functions.
200 Has special code to detect magic functions.
201 """
201 """
202
202
203 oname = oname.strip()
203 oname = oname.strip()
204
204
205 alias_ns = None
205 alias_ns = None
206 if namespaces is None:
206 if namespaces is None:
207 # Namespaces to search in:
207 # Namespaces to search in:
208 # Put them in a list. The order is important so that we
208 # Put them in a list. The order is important so that we
209 # find things in the same order that Python finds them.
209 # find things in the same order that Python finds them.
210 namespaces = [ ('Interactive', self.shell.user_ns),
210 namespaces = [ ('Interactive', self.shell.user_ns),
211 ('IPython internal', self.shell.internal_ns),
211 ('IPython internal', self.shell.internal_ns),
212 ('Python builtin', __builtin__.__dict__),
212 ('Python builtin', __builtin__.__dict__),
213 ('Alias', self.shell.alias_table),
213 ('Alias', self.shell.alias_table),
214 ]
214 ]
215 alias_ns = self.shell.alias_table
215 alias_ns = self.shell.alias_table
216
216
217 # initialize results to 'null'
217 # initialize results to 'null'
218 found = 0; obj = None; ospace = None; ds = None;
218 found = 0; obj = None; ospace = None; ds = None;
219 ismagic = 0; isalias = 0; parent = None
219 ismagic = 0; isalias = 0; parent = None
220
220
221 # Look for the given name by splitting it in parts. If the head is
221 # Look for the given name by splitting it in parts. If the head is
222 # found, then we look for all the remaining parts as members, and only
222 # found, then we look for all the remaining parts as members, and only
223 # declare success if we can find them all.
223 # declare success if we can find them all.
224 oname_parts = oname.split('.')
224 oname_parts = oname.split('.')
225 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
225 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
226 for nsname,ns in namespaces:
226 for nsname,ns in namespaces:
227 try:
227 try:
228 obj = ns[oname_head]
228 obj = ns[oname_head]
229 except KeyError:
229 except KeyError:
230 continue
230 continue
231 else:
231 else:
232 #print 'oname_rest:', oname_rest # dbg
232 #print 'oname_rest:', oname_rest # dbg
233 for part in oname_rest:
233 for part in oname_rest:
234 try:
234 try:
235 parent = obj
235 parent = obj
236 obj = getattr(obj,part)
236 obj = getattr(obj,part)
237 except:
237 except:
238 # Blanket except b/c some badly implemented objects
238 # Blanket except b/c some badly implemented objects
239 # allow __getattr__ to raise exceptions other than
239 # allow __getattr__ to raise exceptions other than
240 # AttributeError, which then crashes IPython.
240 # AttributeError, which then crashes IPython.
241 break
241 break
242 else:
242 else:
243 # If we finish the for loop (no break), we got all members
243 # If we finish the for loop (no break), we got all members
244 found = 1
244 found = 1
245 ospace = nsname
245 ospace = nsname
246 if ns == alias_ns:
246 if ns == alias_ns:
247 isalias = 1
247 isalias = 1
248 break # namespace loop
248 break # namespace loop
249
249
250 # Try to see if it's magic
250 # Try to see if it's magic
251 if not found:
251 if not found:
252 if oname.startswith(self.shell.ESC_MAGIC):
252 if oname.startswith(self.shell.ESC_MAGIC):
253 oname = oname[1:]
253 oname = oname[1:]
254 obj = getattr(self,'magic_'+oname,None)
254 obj = getattr(self,'magic_'+oname,None)
255 if obj is not None:
255 if obj is not None:
256 found = 1
256 found = 1
257 ospace = 'IPython internal'
257 ospace = 'IPython internal'
258 ismagic = 1
258 ismagic = 1
259
259
260 # Last try: special-case some literals like '', [], {}, etc:
260 # Last try: special-case some literals like '', [], {}, etc:
261 if not found and oname_head in ["''",'""','[]','{}','()']:
261 if not found and oname_head in ["''",'""','[]','{}','()']:
262 obj = eval(oname_head)
262 obj = eval(oname_head)
263 found = 1
263 found = 1
264 ospace = 'Interactive'
264 ospace = 'Interactive'
265
265
266 return {'found':found, 'obj':obj, 'namespace':ospace,
266 return {'found':found, 'obj':obj, 'namespace':ospace,
267 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
267 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
268
268
269 def arg_err(self,func):
269 def arg_err(self,func):
270 """Print docstring if incorrect arguments were passed"""
270 """Print docstring if incorrect arguments were passed"""
271 print 'Error in arguments:'
271 print 'Error in arguments:'
272 print OInspect.getdoc(func)
272 print OInspect.getdoc(func)
273
273
274 def format_latex(self,strng):
274 def format_latex(self,strng):
275 """Format a string for latex inclusion."""
275 """Format a string for latex inclusion."""
276
276
277 # Characters that need to be escaped for latex:
277 # Characters that need to be escaped for latex:
278 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
278 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
279 # Magic command names as headers:
279 # Magic command names as headers:
280 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
280 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
281 re.MULTILINE)
281 re.MULTILINE)
282 # Magic commands
282 # Magic commands
283 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
283 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
284 re.MULTILINE)
284 re.MULTILINE)
285 # Paragraph continue
285 # Paragraph continue
286 par_re = re.compile(r'\\$',re.MULTILINE)
286 par_re = re.compile(r'\\$',re.MULTILINE)
287
287
288 # The "\n" symbol
288 # The "\n" symbol
289 newline_re = re.compile(r'\\n')
289 newline_re = re.compile(r'\\n')
290
290
291 # Now build the string for output:
291 # Now build the string for output:
292 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
292 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
293 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
293 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
294 strng)
294 strng)
295 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
295 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
296 strng = par_re.sub(r'\\\\',strng)
296 strng = par_re.sub(r'\\\\',strng)
297 strng = escape_re.sub(r'\\\1',strng)
297 strng = escape_re.sub(r'\\\1',strng)
298 strng = newline_re.sub(r'\\textbackslash{}n',strng)
298 strng = newline_re.sub(r'\\textbackslash{}n',strng)
299 return strng
299 return strng
300
300
301 def format_screen(self,strng):
301 def format_screen(self,strng):
302 """Format a string for screen printing.
302 """Format a string for screen printing.
303
303
304 This removes some latex-type format codes."""
304 This removes some latex-type format codes."""
305 # Paragraph continue
305 # Paragraph continue
306 par_re = re.compile(r'\\$',re.MULTILINE)
306 par_re = re.compile(r'\\$',re.MULTILINE)
307 strng = par_re.sub('',strng)
307 strng = par_re.sub('',strng)
308 return strng
308 return strng
309
309
310 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
310 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
311 """Parse options passed to an argument string.
311 """Parse options passed to an argument string.
312
312
313 The interface is similar to that of getopt(), but it returns back a
313 The interface is similar to that of getopt(), but it returns back a
314 Struct with the options as keys and the stripped argument string still
314 Struct with the options as keys and the stripped argument string still
315 as a string.
315 as a string.
316
316
317 arg_str is quoted as a true sys.argv vector by using shlex.split.
317 arg_str is quoted as a true sys.argv vector by using shlex.split.
318 This allows us to easily expand variables, glob files, quote
318 This allows us to easily expand variables, glob files, quote
319 arguments, etc.
319 arguments, etc.
320
320
321 Options:
321 Options:
322 -mode: default 'string'. If given as 'list', the argument string is
322 -mode: default 'string'. If given as 'list', the argument string is
323 returned as a list (split on whitespace) instead of a string.
323 returned as a list (split on whitespace) instead of a string.
324
324
325 -list_all: put all option values in lists. Normally only options
325 -list_all: put all option values in lists. Normally only options
326 appearing more than once are put in a list.
326 appearing more than once are put in a list.
327
327
328 -posix (True): whether to split the input line in POSIX mode or not,
328 -posix (True): whether to split the input line in POSIX mode or not,
329 as per the conventions outlined in the shlex module from the
329 as per the conventions outlined in the shlex module from the
330 standard library."""
330 standard library."""
331
331
332 # inject default options at the beginning of the input line
332 # inject default options at the beginning of the input line
333 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
333 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
334 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
334 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
335
335
336 mode = kw.get('mode','string')
336 mode = kw.get('mode','string')
337 if mode not in ['string','list']:
337 if mode not in ['string','list']:
338 raise ValueError,'incorrect mode given: %s' % mode
338 raise ValueError,'incorrect mode given: %s' % mode
339 # Get options
339 # Get options
340 list_all = kw.get('list_all',0)
340 list_all = kw.get('list_all',0)
341 posix = kw.get('posix',True)
341 posix = kw.get('posix',True)
342
342
343 # Check if we have more than one argument to warrant extra processing:
343 # Check if we have more than one argument to warrant extra processing:
344 odict = {} # Dictionary with options
344 odict = {} # Dictionary with options
345 args = arg_str.split()
345 args = arg_str.split()
346 if len(args) >= 1:
346 if len(args) >= 1:
347 # If the list of inputs only has 0 or 1 thing in it, there's no
347 # If the list of inputs only has 0 or 1 thing in it, there's no
348 # need to look for options
348 # need to look for options
349 argv = arg_split(arg_str,posix)
349 argv = arg_split(arg_str,posix)
350 # Do regular option processing
350 # Do regular option processing
351 try:
351 try:
352 opts,args = getopt(argv,opt_str,*long_opts)
352 opts,args = getopt(argv,opt_str,*long_opts)
353 except GetoptError,e:
353 except GetoptError,e:
354 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
354 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
355 " ".join(long_opts)))
355 " ".join(long_opts)))
356 for o,a in opts:
356 for o,a in opts:
357 if o.startswith('--'):
357 if o.startswith('--'):
358 o = o[2:]
358 o = o[2:]
359 else:
359 else:
360 o = o[1:]
360 o = o[1:]
361 try:
361 try:
362 odict[o].append(a)
362 odict[o].append(a)
363 except AttributeError:
363 except AttributeError:
364 odict[o] = [odict[o],a]
364 odict[o] = [odict[o],a]
365 except KeyError:
365 except KeyError:
366 if list_all:
366 if list_all:
367 odict[o] = [a]
367 odict[o] = [a]
368 else:
368 else:
369 odict[o] = a
369 odict[o] = a
370
370
371 # Prepare opts,args for return
371 # Prepare opts,args for return
372 opts = Struct(odict)
372 opts = Struct(odict)
373 if mode == 'string':
373 if mode == 'string':
374 args = ' '.join(args)
374 args = ' '.join(args)
375
375
376 return opts,args
376 return opts,args
377
377
378 #......................................................................
378 #......................................................................
379 # And now the actual magic functions
379 # And now the actual magic functions
380
380
381 # Functions for IPython shell work (vars,funcs, config, etc)
381 # Functions for IPython shell work (vars,funcs, config, etc)
382 def magic_lsmagic(self, parameter_s = ''):
382 def magic_lsmagic(self, parameter_s = ''):
383 """List currently available magic functions."""
383 """List currently available magic functions."""
384 mesc = self.shell.ESC_MAGIC
384 mesc = self.shell.ESC_MAGIC
385 print 'Available magic functions:\n'+mesc+\
385 print 'Available magic functions:\n'+mesc+\
386 (' '+mesc).join(self.lsmagic())
386 (' '+mesc).join(self.lsmagic())
387 print '\n' + Magic.auto_status[self.shell.rc.automagic]
387 print '\n' + Magic.auto_status[self.shell.rc.automagic]
388 return None
388 return None
389
389
390 def magic_magic(self, parameter_s = ''):
390 def magic_magic(self, parameter_s = ''):
391 """Print information about the magic function system.
391 """Print information about the magic function system.
392
392
393 Supported formats: -latex, -brief, -rest
393 Supported formats: -latex, -brief, -rest
394 """
394 """
395
395
396 mode = ''
396 mode = ''
397 try:
397 try:
398 if parameter_s.split()[0] == '-latex':
398 if parameter_s.split()[0] == '-latex':
399 mode = 'latex'
399 mode = 'latex'
400 if parameter_s.split()[0] == '-brief':
400 if parameter_s.split()[0] == '-brief':
401 mode = 'brief'
401 mode = 'brief'
402 if parameter_s.split()[0] == '-rest':
402 if parameter_s.split()[0] == '-rest':
403 mode = 'rest'
403 mode = 'rest'
404 rest_docs = []
404 rest_docs = []
405 except:
405 except:
406 pass
406 pass
407
407
408 magic_docs = []
408 magic_docs = []
409 for fname in self.lsmagic():
409 for fname in self.lsmagic():
410 mname = 'magic_' + fname
410 mname = 'magic_' + fname
411 for space in (Magic,self,self.__class__):
411 for space in (Magic,self,self.__class__):
412 try:
412 try:
413 fn = space.__dict__[mname]
413 fn = space.__dict__[mname]
414 except KeyError:
414 except KeyError:
415 pass
415 pass
416 else:
416 else:
417 break
417 break
418 if mode == 'brief':
418 if mode == 'brief':
419 # only first line
419 # only first line
420 if fn.__doc__:
420 if fn.__doc__:
421 fndoc = fn.__doc__.split('\n',1)[0]
421 fndoc = fn.__doc__.split('\n',1)[0]
422 else:
422 else:
423 fndoc = 'No documentation'
423 fndoc = 'No documentation'
424 else:
424 else:
425 fndoc = fn.__doc__.rstrip()
425 fndoc = fn.__doc__.rstrip()
426
426
427 if mode == 'rest':
427 if mode == 'rest':
428 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC,
428 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC,
429 fname,fndoc))
429 fname,fndoc))
430
430
431 else:
431 else:
432 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
432 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
433 fname,fndoc))
433 fname,fndoc))
434
434
435 magic_docs = ''.join(magic_docs)
435 magic_docs = ''.join(magic_docs)
436
436
437 if mode == 'rest':
437 if mode == 'rest':
438 return "".join(rest_docs)
438 return "".join(rest_docs)
439
439
440 if mode == 'latex':
440 if mode == 'latex':
441 print self.format_latex(magic_docs)
441 print self.format_latex(magic_docs)
442 return
442 return
443 else:
443 else:
444 magic_docs = self.format_screen(magic_docs)
444 magic_docs = self.format_screen(magic_docs)
445 if mode == 'brief':
445 if mode == 'brief':
446 return magic_docs
446 return magic_docs
447
447
448 outmsg = """
448 outmsg = """
449 IPython's 'magic' functions
449 IPython's 'magic' functions
450 ===========================
450 ===========================
451
451
452 The magic function system provides a series of functions which allow you to
452 The magic function system provides a series of functions which allow you to
453 control the behavior of IPython itself, plus a lot of system-type
453 control the behavior of IPython itself, plus a lot of system-type
454 features. All these functions are prefixed with a % character, but parameters
454 features. All these functions are prefixed with a % character, but parameters
455 are given without parentheses or quotes.
455 are given without parentheses or quotes.
456
456
457 NOTE: If you have 'automagic' enabled (via the command line option or with the
457 NOTE: If you have 'automagic' enabled (via the command line option or with the
458 %automagic function), you don't need to type in the % explicitly. By default,
458 %automagic function), you don't need to type in the % explicitly. By default,
459 IPython ships with automagic on, so you should only rarely need the % escape.
459 IPython ships with automagic on, so you should only rarely need the % escape.
460
460
461 Example: typing '%cd mydir' (without the quotes) changes you working directory
461 Example: typing '%cd mydir' (without the quotes) changes you working directory
462 to 'mydir', if it exists.
462 to 'mydir', if it exists.
463
463
464 You can define your own magic functions to extend the system. See the supplied
464 You can define your own magic functions to extend the system. See the supplied
465 ipythonrc and example-magic.py files for details (in your ipython
465 ipythonrc and example-magic.py files for details (in your ipython
466 configuration directory, typically $HOME/.ipython/).
466 configuration directory, typically $HOME/.ipython/).
467
467
468 You can also define your own aliased names for magic functions. In your
468 You can also define your own aliased names for magic functions. In your
469 ipythonrc file, placing a line like:
469 ipythonrc file, placing a line like:
470
470
471 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
471 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
472
472
473 will define %pf as a new name for %profile.
473 will define %pf as a new name for %profile.
474
474
475 You can also call magics in code using the ipmagic() function, which IPython
475 You can also call magics in code using the ipmagic() function, which IPython
476 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
476 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
477
477
478 For a list of the available magic functions, use %lsmagic. For a description
478 For a list of the available magic functions, use %lsmagic. For a description
479 of any of them, type %magic_name?, e.g. '%cd?'.
479 of any of them, type %magic_name?, e.g. '%cd?'.
480
480
481 Currently the magic system has the following functions:\n"""
481 Currently the magic system has the following functions:\n"""
482
482
483 mesc = self.shell.ESC_MAGIC
483 mesc = self.shell.ESC_MAGIC
484 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
484 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
485 "\n\n%s%s\n\n%s" % (outmsg,
485 "\n\n%s%s\n\n%s" % (outmsg,
486 magic_docs,mesc,mesc,
486 magic_docs,mesc,mesc,
487 (' '+mesc).join(self.lsmagic()),
487 (' '+mesc).join(self.lsmagic()),
488 Magic.auto_status[self.shell.rc.automagic] ) )
488 Magic.auto_status[self.shell.rc.automagic] ) )
489
489
490 page(outmsg,screen_lines=self.shell.rc.screen_length)
490 page(outmsg,screen_lines=self.shell.rc.screen_length)
491
491
492
492
493 def magic_autoindent(self, parameter_s = ''):
493 def magic_autoindent(self, parameter_s = ''):
494 """Toggle autoindent on/off (if available)."""
494 """Toggle autoindent on/off (if available)."""
495
495
496 self.shell.set_autoindent()
496 self.shell.set_autoindent()
497 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
497 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
498
498
499
499
500 def magic_automagic(self, parameter_s = ''):
500 def magic_automagic(self, parameter_s = ''):
501 """Make magic functions callable without having to type the initial %.
501 """Make magic functions callable without having to type the initial %.
502
502
503 Without argumentsl toggles on/off (when off, you must call it as
503 Without argumentsl toggles on/off (when off, you must call it as
504 %automagic, of course). With arguments it sets the value, and you can
504 %automagic, of course). With arguments it sets the value, and you can
505 use any of (case insensitive):
505 use any of (case insensitive):
506
506
507 - on,1,True: to activate
507 - on,1,True: to activate
508
508
509 - off,0,False: to deactivate.
509 - off,0,False: to deactivate.
510
510
511 Note that magic functions have lowest priority, so if there's a
511 Note that magic functions have lowest priority, so if there's a
512 variable whose name collides with that of a magic fn, automagic won't
512 variable whose name collides with that of a magic fn, automagic won't
513 work for that function (you get the variable instead). However, if you
513 work for that function (you get the variable instead). However, if you
514 delete the variable (del var), the previously shadowed magic function
514 delete the variable (del var), the previously shadowed magic function
515 becomes visible to automagic again."""
515 becomes visible to automagic again."""
516
516
517 rc = self.shell.rc
517 rc = self.shell.rc
518 arg = parameter_s.lower()
518 arg = parameter_s.lower()
519 if parameter_s in ('on','1','true'):
519 if parameter_s in ('on','1','true'):
520 rc.automagic = True
520 rc.automagic = True
521 elif parameter_s in ('off','0','false'):
521 elif parameter_s in ('off','0','false'):
522 rc.automagic = False
522 rc.automagic = False
523 else:
523 else:
524 rc.automagic = not rc.automagic
524 rc.automagic = not rc.automagic
525 print '\n' + Magic.auto_status[rc.automagic]
525 print '\n' + Magic.auto_status[rc.automagic]
526
526
527 @testdec.skip_doctest
527 @testdec.skip_doctest
528 def magic_autocall(self, parameter_s = ''):
528 def magic_autocall(self, parameter_s = ''):
529 """Make functions callable without having to type parentheses.
529 """Make functions callable without having to type parentheses.
530
530
531 Usage:
531 Usage:
532
532
533 %autocall [mode]
533 %autocall [mode]
534
534
535 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
535 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
536 value is toggled on and off (remembering the previous state).
536 value is toggled on and off (remembering the previous state).
537
537
538 In more detail, these values mean:
538 In more detail, these values mean:
539
539
540 0 -> fully disabled
540 0 -> fully disabled
541
541
542 1 -> active, but do not apply if there are no arguments on the line.
542 1 -> active, but do not apply if there are no arguments on the line.
543
543
544 In this mode, you get:
544 In this mode, you get:
545
545
546 In [1]: callable
546 In [1]: callable
547 Out[1]: <built-in function callable>
547 Out[1]: <built-in function callable>
548
548
549 In [2]: callable 'hello'
549 In [2]: callable 'hello'
550 ------> callable('hello')
550 ------> callable('hello')
551 Out[2]: False
551 Out[2]: False
552
552
553 2 -> Active always. Even if no arguments are present, the callable
553 2 -> Active always. Even if no arguments are present, the callable
554 object is called:
554 object is called:
555
555
556 In [2]: float
556 In [2]: float
557 ------> float()
557 ------> float()
558 Out[2]: 0.0
558 Out[2]: 0.0
559
559
560 Note that even with autocall off, you can still use '/' at the start of
560 Note that even with autocall off, you can still use '/' at the start of
561 a line to treat the first argument on the command line as a function
561 a line to treat the first argument on the command line as a function
562 and add parentheses to it:
562 and add parentheses to it:
563
563
564 In [8]: /str 43
564 In [8]: /str 43
565 ------> str(43)
565 ------> str(43)
566 Out[8]: '43'
566 Out[8]: '43'
567
567
568 # all-random (note for auto-testing)
568 # all-random (note for auto-testing)
569 """
569 """
570
570
571 rc = self.shell.rc
571 rc = self.shell.rc
572
572
573 if parameter_s:
573 if parameter_s:
574 arg = int(parameter_s)
574 arg = int(parameter_s)
575 else:
575 else:
576 arg = 'toggle'
576 arg = 'toggle'
577
577
578 if not arg in (0,1,2,'toggle'):
578 if not arg in (0,1,2,'toggle'):
579 error('Valid modes: (0->Off, 1->Smart, 2->Full')
579 error('Valid modes: (0->Off, 1->Smart, 2->Full')
580 return
580 return
581
581
582 if arg in (0,1,2):
582 if arg in (0,1,2):
583 rc.autocall = arg
583 rc.autocall = arg
584 else: # toggle
584 else: # toggle
585 if rc.autocall:
585 if rc.autocall:
586 self._magic_state.autocall_save = rc.autocall
586 self._magic_state.autocall_save = rc.autocall
587 rc.autocall = 0
587 rc.autocall = 0
588 else:
588 else:
589 try:
589 try:
590 rc.autocall = self._magic_state.autocall_save
590 rc.autocall = self._magic_state.autocall_save
591 except AttributeError:
591 except AttributeError:
592 rc.autocall = self._magic_state.autocall_save = 1
592 rc.autocall = self._magic_state.autocall_save = 1
593
593
594 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
594 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
595
595
596 def magic_system_verbose(self, parameter_s = ''):
596 def magic_system_verbose(self, parameter_s = ''):
597 """Set verbose printing of system calls.
597 """Set verbose printing of system calls.
598
598
599 If called without an argument, act as a toggle"""
599 If called without an argument, act as a toggle"""
600
600
601 if parameter_s:
601 if parameter_s:
602 val = bool(eval(parameter_s))
602 val = bool(eval(parameter_s))
603 else:
603 else:
604 val = None
604 val = None
605
605
606 self.shell.rc_set_toggle('system_verbose',val)
606 self.shell.rc_set_toggle('system_verbose',val)
607 print "System verbose printing is:",\
607 print "System verbose printing is:",\
608 ['OFF','ON'][self.shell.rc.system_verbose]
608 ['OFF','ON'][self.shell.rc.system_verbose]
609
609
610
610
611 def magic_page(self, parameter_s=''):
611 def magic_page(self, parameter_s=''):
612 """Pretty print the object and display it through a pager.
612 """Pretty print the object and display it through a pager.
613
613
614 %page [options] OBJECT
614 %page [options] OBJECT
615
615
616 If no object is given, use _ (last output).
616 If no object is given, use _ (last output).
617
617
618 Options:
618 Options:
619
619
620 -r: page str(object), don't pretty-print it."""
620 -r: page str(object), don't pretty-print it."""
621
621
622 # After a function contributed by Olivier Aubert, slightly modified.
622 # After a function contributed by Olivier Aubert, slightly modified.
623
623
624 # Process options/args
624 # Process options/args
625 opts,args = self.parse_options(parameter_s,'r')
625 opts,args = self.parse_options(parameter_s,'r')
626 raw = 'r' in opts
626 raw = 'r' in opts
627
627
628 oname = args and args or '_'
628 oname = args and args or '_'
629 info = self._ofind(oname)
629 info = self._ofind(oname)
630 if info['found']:
630 if info['found']:
631 txt = (raw and str or pformat)( info['obj'] )
631 txt = (raw and str or pformat)( info['obj'] )
632 page(txt)
632 page(txt)
633 else:
633 else:
634 print 'Object `%s` not found' % oname
634 print 'Object `%s` not found' % oname
635
635
636 def magic_profile(self, parameter_s=''):
636 def magic_profile(self, parameter_s=''):
637 """Print your currently active IPyhton profile."""
637 """Print your currently active IPyhton profile."""
638 if self.shell.rc.profile:
638 if self.shell.rc.profile:
639 printpl('Current IPython profile: $self.shell.rc.profile.')
639 printpl('Current IPython profile: $self.shell.rc.profile.')
640 else:
640 else:
641 print 'No profile active.'
641 print 'No profile active.'
642
642
643 def magic_pinfo(self, parameter_s='', namespaces=None):
643 def magic_pinfo(self, parameter_s='', namespaces=None):
644 """Provide detailed information about an object.
644 """Provide detailed information about an object.
645
645
646 '%pinfo object' is just a synonym for object? or ?object."""
646 '%pinfo object' is just a synonym for object? or ?object."""
647
647
648 #print 'pinfo par: <%s>' % parameter_s # dbg
648 #print 'pinfo par: <%s>' % parameter_s # dbg
649
649
650
650
651 # detail_level: 0 -> obj? , 1 -> obj??
651 # detail_level: 0 -> obj? , 1 -> obj??
652 detail_level = 0
652 detail_level = 0
653 # We need to detect if we got called as 'pinfo pinfo foo', which can
653 # We need to detect if we got called as 'pinfo pinfo foo', which can
654 # happen if the user types 'pinfo foo?' at the cmd line.
654 # happen if the user types 'pinfo foo?' at the cmd line.
655 pinfo,qmark1,oname,qmark2 = \
655 pinfo,qmark1,oname,qmark2 = \
656 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
656 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
657 if pinfo or qmark1 or qmark2:
657 if pinfo or qmark1 or qmark2:
658 detail_level = 1
658 detail_level = 1
659 if "*" in oname:
659 if "*" in oname:
660 self.magic_psearch(oname)
660 self.magic_psearch(oname)
661 else:
661 else:
662 self._inspect('pinfo', oname, detail_level=detail_level,
662 self._inspect('pinfo', oname, detail_level=detail_level,
663 namespaces=namespaces)
663 namespaces=namespaces)
664
664
665 def magic_pdef(self, parameter_s='', namespaces=None):
665 def magic_pdef(self, parameter_s='', namespaces=None):
666 """Print the definition header for any callable object.
666 """Print the definition header for any callable object.
667
667
668 If the object is a class, print the constructor information."""
668 If the object is a class, print the constructor information."""
669 self._inspect('pdef',parameter_s, namespaces)
669 self._inspect('pdef',parameter_s, namespaces)
670
670
671 def magic_pdoc(self, parameter_s='', namespaces=None):
671 def magic_pdoc(self, parameter_s='', namespaces=None):
672 """Print the docstring for an object.
672 """Print the docstring for an object.
673
673
674 If the given object is a class, it will print both the class and the
674 If the given object is a class, it will print both the class and the
675 constructor docstrings."""
675 constructor docstrings."""
676 self._inspect('pdoc',parameter_s, namespaces)
676 self._inspect('pdoc',parameter_s, namespaces)
677
677
678 def magic_psource(self, parameter_s='', namespaces=None):
678 def magic_psource(self, parameter_s='', namespaces=None):
679 """Print (or run through pager) the source code for an object."""
679 """Print (or run through pager) the source code for an object."""
680 self._inspect('psource',parameter_s, namespaces)
680 self._inspect('psource',parameter_s, namespaces)
681
681
682 def magic_pfile(self, parameter_s=''):
682 def magic_pfile(self, parameter_s=''):
683 """Print (or run through pager) the file where an object is defined.
683 """Print (or run through pager) the file where an object is defined.
684
684
685 The file opens at the line where the object definition begins. IPython
685 The file opens at the line where the object definition begins. IPython
686 will honor the environment variable PAGER if set, and otherwise will
686 will honor the environment variable PAGER if set, and otherwise will
687 do its best to print the file in a convenient form.
687 do its best to print the file in a convenient form.
688
688
689 If the given argument is not an object currently defined, IPython will
689 If the given argument is not an object currently defined, IPython will
690 try to interpret it as a filename (automatically adding a .py extension
690 try to interpret it as a filename (automatically adding a .py extension
691 if needed). You can thus use %pfile as a syntax highlighting code
691 if needed). You can thus use %pfile as a syntax highlighting code
692 viewer."""
692 viewer."""
693
693
694 # first interpret argument as an object name
694 # first interpret argument as an object name
695 out = self._inspect('pfile',parameter_s)
695 out = self._inspect('pfile',parameter_s)
696 # if not, try the input as a filename
696 # if not, try the input as a filename
697 if out == 'not found':
697 if out == 'not found':
698 try:
698 try:
699 filename = get_py_filename(parameter_s)
699 filename = get_py_filename(parameter_s)
700 except IOError,msg:
700 except IOError,msg:
701 print msg
701 print msg
702 return
702 return
703 page(self.shell.inspector.format(file(filename).read()))
703 page(self.shell.inspector.format(file(filename).read()))
704
704
705 def _inspect(self,meth,oname,namespaces=None,**kw):
705 def _inspect(self,meth,oname,namespaces=None,**kw):
706 """Generic interface to the inspector system.
706 """Generic interface to the inspector system.
707
707
708 This function is meant to be called by pdef, pdoc & friends."""
708 This function is meant to be called by pdef, pdoc & friends."""
709
709
710 #oname = oname.strip()
710 #oname = oname.strip()
711 #print '1- oname: <%r>' % oname # dbg
711 #print '1- oname: <%r>' % oname # dbg
712 try:
712 try:
713 oname = oname.strip().encode('ascii')
713 oname = oname.strip().encode('ascii')
714 #print '2- oname: <%r>' % oname # dbg
714 #print '2- oname: <%r>' % oname # dbg
715 except UnicodeEncodeError:
715 except UnicodeEncodeError:
716 print 'Python identifiers can only contain ascii characters.'
716 print 'Python identifiers can only contain ascii characters.'
717 return 'not found'
717 return 'not found'
718
718
719 info = Struct(self._ofind(oname, namespaces))
719 info = Struct(self._ofind(oname, namespaces))
720
720
721 if info.found:
721 if info.found:
722 try:
722 try:
723 IPython.generics.inspect_object(info.obj)
723 IPython.generics.inspect_object(info.obj)
724 return
724 return
725 except IPython.ipapi.TryNext:
725 except IPython.ipapi.TryNext:
726 pass
726 pass
727 # Get the docstring of the class property if it exists.
727 # Get the docstring of the class property if it exists.
728 path = oname.split('.')
728 path = oname.split('.')
729 root = '.'.join(path[:-1])
729 root = '.'.join(path[:-1])
730 if info.parent is not None:
730 if info.parent is not None:
731 try:
731 try:
732 target = getattr(info.parent, '__class__')
732 target = getattr(info.parent, '__class__')
733 # The object belongs to a class instance.
733 # The object belongs to a class instance.
734 try:
734 try:
735 target = getattr(target, path[-1])
735 target = getattr(target, path[-1])
736 # The class defines the object.
736 # The class defines the object.
737 if isinstance(target, property):
737 if isinstance(target, property):
738 oname = root + '.__class__.' + path[-1]
738 oname = root + '.__class__.' + path[-1]
739 info = Struct(self._ofind(oname))
739 info = Struct(self._ofind(oname))
740 except AttributeError: pass
740 except AttributeError: pass
741 except AttributeError: pass
741 except AttributeError: pass
742
742
743 pmethod = getattr(self.shell.inspector,meth)
743 pmethod = getattr(self.shell.inspector,meth)
744 formatter = info.ismagic and self.format_screen or None
744 formatter = info.ismagic and self.format_screen or None
745 if meth == 'pdoc':
745 if meth == 'pdoc':
746 pmethod(info.obj,oname,formatter)
746 pmethod(info.obj,oname,formatter)
747 elif meth == 'pinfo':
747 elif meth == 'pinfo':
748 pmethod(info.obj,oname,formatter,info,**kw)
748 pmethod(info.obj,oname,formatter,info,**kw)
749 else:
749 else:
750 pmethod(info.obj,oname)
750 pmethod(info.obj,oname)
751 else:
751 else:
752 print 'Object `%s` not found.' % oname
752 print 'Object `%s` not found.' % oname
753 return 'not found' # so callers can take other action
753 return 'not found' # so callers can take other action
754
754
755 def magic_psearch(self, parameter_s=''):
755 def magic_psearch(self, parameter_s=''):
756 """Search for object in namespaces by wildcard.
756 """Search for object in namespaces by wildcard.
757
757
758 %psearch [options] PATTERN [OBJECT TYPE]
758 %psearch [options] PATTERN [OBJECT TYPE]
759
759
760 Note: ? can be used as a synonym for %psearch, at the beginning or at
760 Note: ? can be used as a synonym for %psearch, at the beginning or at
761 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
761 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
762 rest of the command line must be unchanged (options come first), so
762 rest of the command line must be unchanged (options come first), so
763 for example the following forms are equivalent
763 for example the following forms are equivalent
764
764
765 %psearch -i a* function
765 %psearch -i a* function
766 -i a* function?
766 -i a* function?
767 ?-i a* function
767 ?-i a* function
768
768
769 Arguments:
769 Arguments:
770
770
771 PATTERN
771 PATTERN
772
772
773 where PATTERN is a string containing * as a wildcard similar to its
773 where PATTERN is a string containing * as a wildcard similar to its
774 use in a shell. The pattern is matched in all namespaces on the
774 use in a shell. The pattern is matched in all namespaces on the
775 search path. By default objects starting with a single _ are not
775 search path. By default objects starting with a single _ are not
776 matched, many IPython generated objects have a single
776 matched, many IPython generated objects have a single
777 underscore. The default is case insensitive matching. Matching is
777 underscore. The default is case insensitive matching. Matching is
778 also done on the attributes of objects and not only on the objects
778 also done on the attributes of objects and not only on the objects
779 in a module.
779 in a module.
780
780
781 [OBJECT TYPE]
781 [OBJECT TYPE]
782
782
783 Is the name of a python type from the types module. The name is
783 Is the name of a python type from the types module. The name is
784 given in lowercase without the ending type, ex. StringType is
784 given in lowercase without the ending type, ex. StringType is
785 written string. By adding a type here only objects matching the
785 written string. By adding a type here only objects matching the
786 given type are matched. Using all here makes the pattern match all
786 given type are matched. Using all here makes the pattern match all
787 types (this is the default).
787 types (this is the default).
788
788
789 Options:
789 Options:
790
790
791 -a: makes the pattern match even objects whose names start with a
791 -a: makes the pattern match even objects whose names start with a
792 single underscore. These names are normally ommitted from the
792 single underscore. These names are normally ommitted from the
793 search.
793 search.
794
794
795 -i/-c: make the pattern case insensitive/sensitive. If neither of
795 -i/-c: make the pattern case insensitive/sensitive. If neither of
796 these options is given, the default is read from your ipythonrc
796 these options is given, the default is read from your ipythonrc
797 file. The option name which sets this value is
797 file. The option name which sets this value is
798 'wildcards_case_sensitive'. If this option is not specified in your
798 'wildcards_case_sensitive'. If this option is not specified in your
799 ipythonrc file, IPython's internal default is to do a case sensitive
799 ipythonrc file, IPython's internal default is to do a case sensitive
800 search.
800 search.
801
801
802 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
802 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
803 specifiy can be searched in any of the following namespaces:
803 specifiy can be searched in any of the following namespaces:
804 'builtin', 'user', 'user_global','internal', 'alias', where
804 'builtin', 'user', 'user_global','internal', 'alias', where
805 'builtin' and 'user' are the search defaults. Note that you should
805 'builtin' and 'user' are the search defaults. Note that you should
806 not use quotes when specifying namespaces.
806 not use quotes when specifying namespaces.
807
807
808 'Builtin' contains the python module builtin, 'user' contains all
808 'Builtin' contains the python module builtin, 'user' contains all
809 user data, 'alias' only contain the shell aliases and no python
809 user data, 'alias' only contain the shell aliases and no python
810 objects, 'internal' contains objects used by IPython. The
810 objects, 'internal' contains objects used by IPython. The
811 'user_global' namespace is only used by embedded IPython instances,
811 'user_global' namespace is only used by embedded IPython instances,
812 and it contains module-level globals. You can add namespaces to the
812 and it contains module-level globals. You can add namespaces to the
813 search with -s or exclude them with -e (these options can be given
813 search with -s or exclude them with -e (these options can be given
814 more than once).
814 more than once).
815
815
816 Examples:
816 Examples:
817
817
818 %psearch a* -> objects beginning with an a
818 %psearch a* -> objects beginning with an a
819 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
819 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
820 %psearch a* function -> all functions beginning with an a
820 %psearch a* function -> all functions beginning with an a
821 %psearch re.e* -> objects beginning with an e in module re
821 %psearch re.e* -> objects beginning with an e in module re
822 %psearch r*.e* -> objects that start with e in modules starting in r
822 %psearch r*.e* -> objects that start with e in modules starting in r
823 %psearch r*.* string -> all strings in modules beginning with r
823 %psearch r*.* string -> all strings in modules beginning with r
824
824
825 Case sensitve search:
825 Case sensitve search:
826
826
827 %psearch -c a* list all object beginning with lower case a
827 %psearch -c a* list all object beginning with lower case a
828
828
829 Show objects beginning with a single _:
829 Show objects beginning with a single _:
830
830
831 %psearch -a _* list objects beginning with a single underscore"""
831 %psearch -a _* list objects beginning with a single underscore"""
832 try:
832 try:
833 parameter_s = parameter_s.encode('ascii')
833 parameter_s = parameter_s.encode('ascii')
834 except UnicodeEncodeError:
834 except UnicodeEncodeError:
835 print 'Python identifiers can only contain ascii characters.'
835 print 'Python identifiers can only contain ascii characters.'
836 return
836 return
837
837
838 # default namespaces to be searched
838 # default namespaces to be searched
839 def_search = ['user','builtin']
839 def_search = ['user','builtin']
840
840
841 # Process options/args
841 # Process options/args
842 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
842 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
843 opt = opts.get
843 opt = opts.get
844 shell = self.shell
844 shell = self.shell
845 psearch = shell.inspector.psearch
845 psearch = shell.inspector.psearch
846
846
847 # select case options
847 # select case options
848 if opts.has_key('i'):
848 if opts.has_key('i'):
849 ignore_case = True
849 ignore_case = True
850 elif opts.has_key('c'):
850 elif opts.has_key('c'):
851 ignore_case = False
851 ignore_case = False
852 else:
852 else:
853 ignore_case = not shell.rc.wildcards_case_sensitive
853 ignore_case = not shell.rc.wildcards_case_sensitive
854
854
855 # Build list of namespaces to search from user options
855 # Build list of namespaces to search from user options
856 def_search.extend(opt('s',[]))
856 def_search.extend(opt('s',[]))
857 ns_exclude = ns_exclude=opt('e',[])
857 ns_exclude = ns_exclude=opt('e',[])
858 ns_search = [nm for nm in def_search if nm not in ns_exclude]
858 ns_search = [nm for nm in def_search if nm not in ns_exclude]
859
859
860 # Call the actual search
860 # Call the actual search
861 try:
861 try:
862 psearch(args,shell.ns_table,ns_search,
862 psearch(args,shell.ns_table,ns_search,
863 show_all=opt('a'),ignore_case=ignore_case)
863 show_all=opt('a'),ignore_case=ignore_case)
864 except:
864 except:
865 shell.showtraceback()
865 shell.showtraceback()
866
866
867 def magic_who_ls(self, parameter_s=''):
867 def magic_who_ls(self, parameter_s=''):
868 """Return a sorted list of all interactive variables.
868 """Return a sorted list of all interactive variables.
869
869
870 If arguments are given, only variables of types matching these
870 If arguments are given, only variables of types matching these
871 arguments are returned."""
871 arguments are returned."""
872
872
873 user_ns = self.shell.user_ns
873 user_ns = self.shell.user_ns
874 internal_ns = self.shell.internal_ns
874 internal_ns = self.shell.internal_ns
875 user_config_ns = self.shell.user_config_ns
875 user_config_ns = self.shell.user_config_ns
876 out = []
876 out = []
877 typelist = parameter_s.split()
877 typelist = parameter_s.split()
878
878
879 for i in user_ns:
879 for i in user_ns:
880 if not (i.startswith('_') or i.startswith('_i')) \
880 if not (i.startswith('_') or i.startswith('_i')) \
881 and not (i in internal_ns or i in user_config_ns):
881 and not (i in internal_ns or i in user_config_ns):
882 if typelist:
882 if typelist:
883 if type(user_ns[i]).__name__ in typelist:
883 if type(user_ns[i]).__name__ in typelist:
884 out.append(i)
884 out.append(i)
885 else:
885 else:
886 out.append(i)
886 out.append(i)
887 out.sort()
887 out.sort()
888 return out
888 return out
889
889
890 def magic_who(self, parameter_s=''):
890 def magic_who(self, parameter_s=''):
891 """Print all interactive variables, with some minimal formatting.
891 """Print all interactive variables, with some minimal formatting.
892
892
893 If any arguments are given, only variables whose type matches one of
893 If any arguments are given, only variables whose type matches one of
894 these are printed. For example:
894 these are printed. For example:
895
895
896 %who function str
896 %who function str
897
897
898 will only list functions and strings, excluding all other types of
898 will only list functions and strings, excluding all other types of
899 variables. To find the proper type names, simply use type(var) at a
899 variables. To find the proper type names, simply use type(var) at a
900 command line to see how python prints type names. For example:
900 command line to see how python prints type names. For example:
901
901
902 In [1]: type('hello')\\
902 In [1]: type('hello')\\
903 Out[1]: <type 'str'>
903 Out[1]: <type 'str'>
904
904
905 indicates that the type name for strings is 'str'.
905 indicates that the type name for strings is 'str'.
906
906
907 %who always excludes executed names loaded through your configuration
907 %who always excludes executed names loaded through your configuration
908 file and things which are internal to IPython.
908 file and things which are internal to IPython.
909
909
910 This is deliberate, as typically you may load many modules and the
910 This is deliberate, as typically you may load many modules and the
911 purpose of %who is to show you only what you've manually defined."""
911 purpose of %who is to show you only what you've manually defined."""
912
912
913 varlist = self.magic_who_ls(parameter_s)
913 varlist = self.magic_who_ls(parameter_s)
914 if not varlist:
914 if not varlist:
915 if parameter_s:
915 if parameter_s:
916 print 'No variables match your requested type.'
916 print 'No variables match your requested type.'
917 else:
917 else:
918 print 'Interactive namespace is empty.'
918 print 'Interactive namespace is empty.'
919 return
919 return
920
920
921 # if we have variables, move on...
921 # if we have variables, move on...
922 count = 0
922 count = 0
923 for i in varlist:
923 for i in varlist:
924 print i+'\t',
924 print i+'\t',
925 count += 1
925 count += 1
926 if count > 8:
926 if count > 8:
927 count = 0
927 count = 0
928 print
928 print
929 print
929 print
930
930
931 def magic_whos(self, parameter_s=''):
931 def magic_whos(self, parameter_s=''):
932 """Like %who, but gives some extra information about each variable.
932 """Like %who, but gives some extra information about each variable.
933
933
934 The same type filtering of %who can be applied here.
934 The same type filtering of %who can be applied here.
935
935
936 For all variables, the type is printed. Additionally it prints:
936 For all variables, the type is printed. Additionally it prints:
937
937
938 - For {},[],(): their length.
938 - For {},[],(): their length.
939
939
940 - For numpy and Numeric arrays, a summary with shape, number of
940 - For numpy and Numeric arrays, a summary with shape, number of
941 elements, typecode and size in memory.
941 elements, typecode and size in memory.
942
942
943 - Everything else: a string representation, snipping their middle if
943 - Everything else: a string representation, snipping their middle if
944 too long."""
944 too long."""
945
945
946 varnames = self.magic_who_ls(parameter_s)
946 varnames = self.magic_who_ls(parameter_s)
947 if not varnames:
947 if not varnames:
948 if parameter_s:
948 if parameter_s:
949 print 'No variables match your requested type.'
949 print 'No variables match your requested type.'
950 else:
950 else:
951 print 'Interactive namespace is empty.'
951 print 'Interactive namespace is empty.'
952 return
952 return
953
953
954 # if we have variables, move on...
954 # if we have variables, move on...
955
955
956 # for these types, show len() instead of data:
956 # for these types, show len() instead of data:
957 seq_types = [types.DictType,types.ListType,types.TupleType]
957 seq_types = [types.DictType,types.ListType,types.TupleType]
958
958
959 # for numpy/Numeric arrays, display summary info
959 # for numpy/Numeric arrays, display summary info
960 try:
960 try:
961 import numpy
961 import numpy
962 except ImportError:
962 except ImportError:
963 ndarray_type = None
963 ndarray_type = None
964 else:
964 else:
965 ndarray_type = numpy.ndarray.__name__
965 ndarray_type = numpy.ndarray.__name__
966 try:
966 try:
967 import Numeric
967 import Numeric
968 except ImportError:
968 except ImportError:
969 array_type = None
969 array_type = None
970 else:
970 else:
971 array_type = Numeric.ArrayType.__name__
971 array_type = Numeric.ArrayType.__name__
972
972
973 # Find all variable names and types so we can figure out column sizes
973 # Find all variable names and types so we can figure out column sizes
974 def get_vars(i):
974 def get_vars(i):
975 return self.shell.user_ns[i]
975 return self.shell.user_ns[i]
976
976
977 # some types are well known and can be shorter
977 # some types are well known and can be shorter
978 abbrevs = {'IPython.macro.Macro' : 'Macro'}
978 abbrevs = {'IPython.macro.Macro' : 'Macro'}
979 def type_name(v):
979 def type_name(v):
980 tn = type(v).__name__
980 tn = type(v).__name__
981 return abbrevs.get(tn,tn)
981 return abbrevs.get(tn,tn)
982
982
983 varlist = map(get_vars,varnames)
983 varlist = map(get_vars,varnames)
984
984
985 typelist = []
985 typelist = []
986 for vv in varlist:
986 for vv in varlist:
987 tt = type_name(vv)
987 tt = type_name(vv)
988
988
989 if tt=='instance':
989 if tt=='instance':
990 typelist.append( abbrevs.get(str(vv.__class__),
990 typelist.append( abbrevs.get(str(vv.__class__),
991 str(vv.__class__)))
991 str(vv.__class__)))
992 else:
992 else:
993 typelist.append(tt)
993 typelist.append(tt)
994
994
995 # column labels and # of spaces as separator
995 # column labels and # of spaces as separator
996 varlabel = 'Variable'
996 varlabel = 'Variable'
997 typelabel = 'Type'
997 typelabel = 'Type'
998 datalabel = 'Data/Info'
998 datalabel = 'Data/Info'
999 colsep = 3
999 colsep = 3
1000 # variable format strings
1000 # variable format strings
1001 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1001 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1002 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1002 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1003 aformat = "%s: %s elems, type `%s`, %s bytes"
1003 aformat = "%s: %s elems, type `%s`, %s bytes"
1004 # find the size of the columns to format the output nicely
1004 # find the size of the columns to format the output nicely
1005 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1005 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1006 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1006 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1007 # table header
1007 # table header
1008 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1008 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1009 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1009 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1010 # and the table itself
1010 # and the table itself
1011 kb = 1024
1011 kb = 1024
1012 Mb = 1048576 # kb**2
1012 Mb = 1048576 # kb**2
1013 for vname,var,vtype in zip(varnames,varlist,typelist):
1013 for vname,var,vtype in zip(varnames,varlist,typelist):
1014 print itpl(vformat),
1014 print itpl(vformat),
1015 if vtype in seq_types:
1015 if vtype in seq_types:
1016 print len(var)
1016 print len(var)
1017 elif vtype in [array_type,ndarray_type]:
1017 elif vtype in [array_type,ndarray_type]:
1018 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1018 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1019 if vtype==ndarray_type:
1019 if vtype==ndarray_type:
1020 # numpy
1020 # numpy
1021 vsize = var.size
1021 vsize = var.size
1022 vbytes = vsize*var.itemsize
1022 vbytes = vsize*var.itemsize
1023 vdtype = var.dtype
1023 vdtype = var.dtype
1024 else:
1024 else:
1025 # Numeric
1025 # Numeric
1026 vsize = Numeric.size(var)
1026 vsize = Numeric.size(var)
1027 vbytes = vsize*var.itemsize()
1027 vbytes = vsize*var.itemsize()
1028 vdtype = var.typecode()
1028 vdtype = var.typecode()
1029
1029
1030 if vbytes < 100000:
1030 if vbytes < 100000:
1031 print aformat % (vshape,vsize,vdtype,vbytes)
1031 print aformat % (vshape,vsize,vdtype,vbytes)
1032 else:
1032 else:
1033 print aformat % (vshape,vsize,vdtype,vbytes),
1033 print aformat % (vshape,vsize,vdtype,vbytes),
1034 if vbytes < Mb:
1034 if vbytes < Mb:
1035 print '(%s kb)' % (vbytes/kb,)
1035 print '(%s kb)' % (vbytes/kb,)
1036 else:
1036 else:
1037 print '(%s Mb)' % (vbytes/Mb,)
1037 print '(%s Mb)' % (vbytes/Mb,)
1038 else:
1038 else:
1039 try:
1039 try:
1040 vstr = str(var)
1040 vstr = str(var)
1041 except UnicodeEncodeError:
1041 except UnicodeEncodeError:
1042 vstr = unicode(var).encode(sys.getdefaultencoding(),
1042 vstr = unicode(var).encode(sys.getdefaultencoding(),
1043 'backslashreplace')
1043 'backslashreplace')
1044 vstr = vstr.replace('\n','\\n')
1044 vstr = vstr.replace('\n','\\n')
1045 if len(vstr) < 50:
1045 if len(vstr) < 50:
1046 print vstr
1046 print vstr
1047 else:
1047 else:
1048 printpl(vfmt_short)
1048 printpl(vfmt_short)
1049
1049
1050 def magic_reset(self, parameter_s=''):
1050 def magic_reset(self, parameter_s=''):
1051 """Resets the namespace by removing all names defined by the user.
1051 """Resets the namespace by removing all names defined by the user.
1052
1052
1053 Input/Output history are left around in case you need them."""
1053 Input/Output history are left around in case you need them."""
1054
1054
1055 ans = self.shell.ask_yes_no(
1055 ans = self.shell.ask_yes_no(
1056 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1056 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1057 if not ans:
1057 if not ans:
1058 print 'Nothing done.'
1058 print 'Nothing done.'
1059 return
1059 return
1060 user_ns = self.shell.user_ns
1060 user_ns = self.shell.user_ns
1061 for i in self.magic_who_ls():
1061 for i in self.magic_who_ls():
1062 del(user_ns[i])
1062 del(user_ns[i])
1063
1063
1064 # Also flush the private list of module references kept for script
1064 # Also flush the private list of module references kept for script
1065 # execution protection
1065 # execution protection
1066 self.shell._user_main_modules[:] = []
1066 self.shell._user_main_modules[:] = []
1067
1067
1068 def magic_logstart(self,parameter_s=''):
1068 def magic_logstart(self,parameter_s=''):
1069 """Start logging anywhere in a session.
1069 """Start logging anywhere in a session.
1070
1070
1071 %logstart [-o|-r|-t] [log_name [log_mode]]
1071 %logstart [-o|-r|-t] [log_name [log_mode]]
1072
1072
1073 If no name is given, it defaults to a file named 'ipython_log.py' in your
1073 If no name is given, it defaults to a file named 'ipython_log.py' in your
1074 current directory, in 'rotate' mode (see below).
1074 current directory, in 'rotate' mode (see below).
1075
1075
1076 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1076 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1077 history up to that point and then continues logging.
1077 history up to that point and then continues logging.
1078
1078
1079 %logstart takes a second optional parameter: logging mode. This can be one
1079 %logstart takes a second optional parameter: logging mode. This can be one
1080 of (note that the modes are given unquoted):\\
1080 of (note that the modes are given unquoted):\\
1081 append: well, that says it.\\
1081 append: well, that says it.\\
1082 backup: rename (if exists) to name~ and start name.\\
1082 backup: rename (if exists) to name~ and start name.\\
1083 global: single logfile in your home dir, appended to.\\
1083 global: single logfile in your home dir, appended to.\\
1084 over : overwrite existing log.\\
1084 over : overwrite existing log.\\
1085 rotate: create rotating logs name.1~, name.2~, etc.
1085 rotate: create rotating logs name.1~, name.2~, etc.
1086
1086
1087 Options:
1087 Options:
1088
1088
1089 -o: log also IPython's output. In this mode, all commands which
1089 -o: log also IPython's output. In this mode, all commands which
1090 generate an Out[NN] prompt are recorded to the logfile, right after
1090 generate an Out[NN] prompt are recorded to the logfile, right after
1091 their corresponding input line. The output lines are always
1091 their corresponding input line. The output lines are always
1092 prepended with a '#[Out]# ' marker, so that the log remains valid
1092 prepended with a '#[Out]# ' marker, so that the log remains valid
1093 Python code.
1093 Python code.
1094
1094
1095 Since this marker is always the same, filtering only the output from
1095 Since this marker is always the same, filtering only the output from
1096 a log is very easy, using for example a simple awk call:
1096 a log is very easy, using for example a simple awk call:
1097
1097
1098 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1098 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1099
1099
1100 -r: log 'raw' input. Normally, IPython's logs contain the processed
1100 -r: log 'raw' input. Normally, IPython's logs contain the processed
1101 input, so that user lines are logged in their final form, converted
1101 input, so that user lines are logged in their final form, converted
1102 into valid Python. For example, %Exit is logged as
1102 into valid Python. For example, %Exit is logged as
1103 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1103 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1104 exactly as typed, with no transformations applied.
1104 exactly as typed, with no transformations applied.
1105
1105
1106 -t: put timestamps before each input line logged (these are put in
1106 -t: put timestamps before each input line logged (these are put in
1107 comments)."""
1107 comments)."""
1108
1108
1109 opts,par = self.parse_options(parameter_s,'ort')
1109 opts,par = self.parse_options(parameter_s,'ort')
1110 log_output = 'o' in opts
1110 log_output = 'o' in opts
1111 log_raw_input = 'r' in opts
1111 log_raw_input = 'r' in opts
1112 timestamp = 't' in opts
1112 timestamp = 't' in opts
1113
1113
1114 rc = self.shell.rc
1114 rc = self.shell.rc
1115 logger = self.shell.logger
1115 logger = self.shell.logger
1116
1116
1117 # if no args are given, the defaults set in the logger constructor by
1117 # if no args are given, the defaults set in the logger constructor by
1118 # ipytohn remain valid
1118 # ipytohn remain valid
1119 if par:
1119 if par:
1120 try:
1120 try:
1121 logfname,logmode = par.split()
1121 logfname,logmode = par.split()
1122 except:
1122 except:
1123 logfname = par
1123 logfname = par
1124 logmode = 'backup'
1124 logmode = 'backup'
1125 else:
1125 else:
1126 logfname = logger.logfname
1126 logfname = logger.logfname
1127 logmode = logger.logmode
1127 logmode = logger.logmode
1128 # put logfname into rc struct as if it had been called on the command
1128 # put logfname into rc struct as if it had been called on the command
1129 # line, so it ends up saved in the log header Save it in case we need
1129 # line, so it ends up saved in the log header Save it in case we need
1130 # to restore it...
1130 # to restore it...
1131 old_logfile = rc.opts.get('logfile','')
1131 old_logfile = rc.opts.get('logfile','')
1132 if logfname:
1132 if logfname:
1133 logfname = os.path.expanduser(logfname)
1133 logfname = os.path.expanduser(logfname)
1134 rc.opts.logfile = logfname
1134 rc.opts.logfile = logfname
1135 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1135 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1136 try:
1136 try:
1137 started = logger.logstart(logfname,loghead,logmode,
1137 started = logger.logstart(logfname,loghead,logmode,
1138 log_output,timestamp,log_raw_input)
1138 log_output,timestamp,log_raw_input)
1139 except:
1139 except:
1140 rc.opts.logfile = old_logfile
1140 rc.opts.logfile = old_logfile
1141 warn("Couldn't start log: %s" % sys.exc_info()[1])
1141 warn("Couldn't start log: %s" % sys.exc_info()[1])
1142 else:
1142 else:
1143 # log input history up to this point, optionally interleaving
1143 # log input history up to this point, optionally interleaving
1144 # output if requested
1144 # output if requested
1145
1145
1146 if timestamp:
1146 if timestamp:
1147 # disable timestamping for the previous history, since we've
1147 # disable timestamping for the previous history, since we've
1148 # lost those already (no time machine here).
1148 # lost those already (no time machine here).
1149 logger.timestamp = False
1149 logger.timestamp = False
1150
1150
1151 if log_raw_input:
1151 if log_raw_input:
1152 input_hist = self.shell.input_hist_raw
1152 input_hist = self.shell.input_hist_raw
1153 else:
1153 else:
1154 input_hist = self.shell.input_hist
1154 input_hist = self.shell.input_hist
1155
1155
1156 if log_output:
1156 if log_output:
1157 log_write = logger.log_write
1157 log_write = logger.log_write
1158 output_hist = self.shell.output_hist
1158 output_hist = self.shell.output_hist
1159 for n in range(1,len(input_hist)-1):
1159 for n in range(1,len(input_hist)-1):
1160 log_write(input_hist[n].rstrip())
1160 log_write(input_hist[n].rstrip())
1161 if n in output_hist:
1161 if n in output_hist:
1162 log_write(repr(output_hist[n]),'output')
1162 log_write(repr(output_hist[n]),'output')
1163 else:
1163 else:
1164 logger.log_write(input_hist[1:])
1164 logger.log_write(input_hist[1:])
1165 if timestamp:
1165 if timestamp:
1166 # re-enable timestamping
1166 # re-enable timestamping
1167 logger.timestamp = True
1167 logger.timestamp = True
1168
1168
1169 print ('Activating auto-logging. '
1169 print ('Activating auto-logging. '
1170 'Current session state plus future input saved.')
1170 'Current session state plus future input saved.')
1171 logger.logstate()
1171 logger.logstate()
1172
1172
1173 def magic_logstop(self,parameter_s=''):
1173 def magic_logstop(self,parameter_s=''):
1174 """Fully stop logging and close log file.
1174 """Fully stop logging and close log file.
1175
1175
1176 In order to start logging again, a new %logstart call needs to be made,
1176 In order to start logging again, a new %logstart call needs to be made,
1177 possibly (though not necessarily) with a new filename, mode and other
1177 possibly (though not necessarily) with a new filename, mode and other
1178 options."""
1178 options."""
1179 self.logger.logstop()
1179 self.logger.logstop()
1180
1180
1181 def magic_logoff(self,parameter_s=''):
1181 def magic_logoff(self,parameter_s=''):
1182 """Temporarily stop logging.
1182 """Temporarily stop logging.
1183
1183
1184 You must have previously started logging."""
1184 You must have previously started logging."""
1185 self.shell.logger.switch_log(0)
1185 self.shell.logger.switch_log(0)
1186
1186
1187 def magic_logon(self,parameter_s=''):
1187 def magic_logon(self,parameter_s=''):
1188 """Restart logging.
1188 """Restart logging.
1189
1189
1190 This function is for restarting logging which you've temporarily
1190 This function is for restarting logging which you've temporarily
1191 stopped with %logoff. For starting logging for the first time, you
1191 stopped with %logoff. For starting logging for the first time, you
1192 must use the %logstart function, which allows you to specify an
1192 must use the %logstart function, which allows you to specify an
1193 optional log filename."""
1193 optional log filename."""
1194
1194
1195 self.shell.logger.switch_log(1)
1195 self.shell.logger.switch_log(1)
1196
1196
1197 def magic_logstate(self,parameter_s=''):
1197 def magic_logstate(self,parameter_s=''):
1198 """Print the status of the logging system."""
1198 """Print the status of the logging system."""
1199
1199
1200 self.shell.logger.logstate()
1200 self.shell.logger.logstate()
1201
1201
1202 def magic_pdb(self, parameter_s=''):
1202 def magic_pdb(self, parameter_s=''):
1203 """Control the automatic calling of the pdb interactive debugger.
1203 """Control the automatic calling of the pdb interactive debugger.
1204
1204
1205 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1205 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1206 argument it works as a toggle.
1206 argument it works as a toggle.
1207
1207
1208 When an exception is triggered, IPython can optionally call the
1208 When an exception is triggered, IPython can optionally call the
1209 interactive pdb debugger after the traceback printout. %pdb toggles
1209 interactive pdb debugger after the traceback printout. %pdb toggles
1210 this feature on and off.
1210 this feature on and off.
1211
1211
1212 The initial state of this feature is set in your ipythonrc
1212 The initial state of this feature is set in your ipythonrc
1213 configuration file (the variable is called 'pdb').
1213 configuration file (the variable is called 'pdb').
1214
1214
1215 If you want to just activate the debugger AFTER an exception has fired,
1215 If you want to just activate the debugger AFTER an exception has fired,
1216 without having to type '%pdb on' and rerunning your code, you can use
1216 without having to type '%pdb on' and rerunning your code, you can use
1217 the %debug magic."""
1217 the %debug magic."""
1218
1218
1219 par = parameter_s.strip().lower()
1219 par = parameter_s.strip().lower()
1220
1220
1221 if par:
1221 if par:
1222 try:
1222 try:
1223 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1223 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1224 except KeyError:
1224 except KeyError:
1225 print ('Incorrect argument. Use on/1, off/0, '
1225 print ('Incorrect argument. Use on/1, off/0, '
1226 'or nothing for a toggle.')
1226 'or nothing for a toggle.')
1227 return
1227 return
1228 else:
1228 else:
1229 # toggle
1229 # toggle
1230 new_pdb = not self.shell.call_pdb
1230 new_pdb = not self.shell.call_pdb
1231
1231
1232 # set on the shell
1232 # set on the shell
1233 self.shell.call_pdb = new_pdb
1233 self.shell.call_pdb = new_pdb
1234 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1234 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1235
1235
1236 def magic_debug(self, parameter_s=''):
1236 def magic_debug(self, parameter_s=''):
1237 """Activate the interactive debugger in post-mortem mode.
1237 """Activate the interactive debugger in post-mortem mode.
1238
1238
1239 If an exception has just occurred, this lets you inspect its stack
1239 If an exception has just occurred, this lets you inspect its stack
1240 frames interactively. Note that this will always work only on the last
1240 frames interactively. Note that this will always work only on the last
1241 traceback that occurred, so you must call this quickly after an
1241 traceback that occurred, so you must call this quickly after an
1242 exception that you wish to inspect has fired, because if another one
1242 exception that you wish to inspect has fired, because if another one
1243 occurs, it clobbers the previous one.
1243 occurs, it clobbers the previous one.
1244
1244
1245 If you want IPython to automatically do this on every exception, see
1245 If you want IPython to automatically do this on every exception, see
1246 the %pdb magic for more details.
1246 the %pdb magic for more details.
1247 """
1247 """
1248
1248
1249 self.shell.debugger(force=True)
1249 self.shell.debugger(force=True)
1250
1250
1251 @testdec.skip_doctest
1251 @testdec.skip_doctest
1252 def magic_prun(self, parameter_s ='',user_mode=1,
1252 def magic_prun(self, parameter_s ='',user_mode=1,
1253 opts=None,arg_lst=None,prog_ns=None):
1253 opts=None,arg_lst=None,prog_ns=None):
1254
1254
1255 """Run a statement through the python code profiler.
1255 """Run a statement through the python code profiler.
1256
1256
1257 Usage:
1257 Usage:
1258 %prun [options] statement
1258 %prun [options] statement
1259
1259
1260 The given statement (which doesn't require quote marks) is run via the
1260 The given statement (which doesn't require quote marks) is run via the
1261 python profiler in a manner similar to the profile.run() function.
1261 python profiler in a manner similar to the profile.run() function.
1262 Namespaces are internally managed to work correctly; profile.run
1262 Namespaces are internally managed to work correctly; profile.run
1263 cannot be used in IPython because it makes certain assumptions about
1263 cannot be used in IPython because it makes certain assumptions about
1264 namespaces which do not hold under IPython.
1264 namespaces which do not hold under IPython.
1265
1265
1266 Options:
1266 Options:
1267
1267
1268 -l <limit>: you can place restrictions on what or how much of the
1268 -l <limit>: you can place restrictions on what or how much of the
1269 profile gets printed. The limit value can be:
1269 profile gets printed. The limit value can be:
1270
1270
1271 * A string: only information for function names containing this string
1271 * A string: only information for function names containing this string
1272 is printed.
1272 is printed.
1273
1273
1274 * An integer: only these many lines are printed.
1274 * An integer: only these many lines are printed.
1275
1275
1276 * A float (between 0 and 1): this fraction of the report is printed
1276 * A float (between 0 and 1): this fraction of the report is printed
1277 (for example, use a limit of 0.4 to see the topmost 40% only).
1277 (for example, use a limit of 0.4 to see the topmost 40% only).
1278
1278
1279 You can combine several limits with repeated use of the option. For
1279 You can combine several limits with repeated use of the option. For
1280 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1280 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1281 information about class constructors.
1281 information about class constructors.
1282
1282
1283 -r: return the pstats.Stats object generated by the profiling. This
1283 -r: return the pstats.Stats object generated by the profiling. This
1284 object has all the information about the profile in it, and you can
1284 object has all the information about the profile in it, and you can
1285 later use it for further analysis or in other functions.
1285 later use it for further analysis or in other functions.
1286
1286
1287 -s <key>: sort profile by given key. You can provide more than one key
1287 -s <key>: sort profile by given key. You can provide more than one key
1288 by using the option several times: '-s key1 -s key2 -s key3...'. The
1288 by using the option several times: '-s key1 -s key2 -s key3...'. The
1289 default sorting key is 'time'.
1289 default sorting key is 'time'.
1290
1290
1291 The following is copied verbatim from the profile documentation
1291 The following is copied verbatim from the profile documentation
1292 referenced below:
1292 referenced below:
1293
1293
1294 When more than one key is provided, additional keys are used as
1294 When more than one key is provided, additional keys are used as
1295 secondary criteria when the there is equality in all keys selected
1295 secondary criteria when the there is equality in all keys selected
1296 before them.
1296 before them.
1297
1297
1298 Abbreviations can be used for any key names, as long as the
1298 Abbreviations can be used for any key names, as long as the
1299 abbreviation is unambiguous. The following are the keys currently
1299 abbreviation is unambiguous. The following are the keys currently
1300 defined:
1300 defined:
1301
1301
1302 Valid Arg Meaning
1302 Valid Arg Meaning
1303 "calls" call count
1303 "calls" call count
1304 "cumulative" cumulative time
1304 "cumulative" cumulative time
1305 "file" file name
1305 "file" file name
1306 "module" file name
1306 "module" file name
1307 "pcalls" primitive call count
1307 "pcalls" primitive call count
1308 "line" line number
1308 "line" line number
1309 "name" function name
1309 "name" function name
1310 "nfl" name/file/line
1310 "nfl" name/file/line
1311 "stdname" standard name
1311 "stdname" standard name
1312 "time" internal time
1312 "time" internal time
1313
1313
1314 Note that all sorts on statistics are in descending order (placing
1314 Note that all sorts on statistics are in descending order (placing
1315 most time consuming items first), where as name, file, and line number
1315 most time consuming items first), where as name, file, and line number
1316 searches are in ascending order (i.e., alphabetical). The subtle
1316 searches are in ascending order (i.e., alphabetical). The subtle
1317 distinction between "nfl" and "stdname" is that the standard name is a
1317 distinction between "nfl" and "stdname" is that the standard name is a
1318 sort of the name as printed, which means that the embedded line
1318 sort of the name as printed, which means that the embedded line
1319 numbers get compared in an odd way. For example, lines 3, 20, and 40
1319 numbers get compared in an odd way. For example, lines 3, 20, and 40
1320 would (if the file names were the same) appear in the string order
1320 would (if the file names were the same) appear in the string order
1321 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1321 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1322 line numbers. In fact, sort_stats("nfl") is the same as
1322 line numbers. In fact, sort_stats("nfl") is the same as
1323 sort_stats("name", "file", "line").
1323 sort_stats("name", "file", "line").
1324
1324
1325 -T <filename>: save profile results as shown on screen to a text
1325 -T <filename>: save profile results as shown on screen to a text
1326 file. The profile is still shown on screen.
1326 file. The profile is still shown on screen.
1327
1327
1328 -D <filename>: save (via dump_stats) profile statistics to given
1328 -D <filename>: save (via dump_stats) profile statistics to given
1329 filename. This data is in a format understod by the pstats module, and
1329 filename. This data is in a format understod by the pstats module, and
1330 is generated by a call to the dump_stats() method of profile
1330 is generated by a call to the dump_stats() method of profile
1331 objects. The profile is still shown on screen.
1331 objects. The profile is still shown on screen.
1332
1332
1333 If you want to run complete programs under the profiler's control, use
1333 If you want to run complete programs under the profiler's control, use
1334 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1334 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1335 contains profiler specific options as described here.
1335 contains profiler specific options as described here.
1336
1336
1337 You can read the complete documentation for the profile module with::
1337 You can read the complete documentation for the profile module with::
1338
1338
1339 In [1]: import profile; profile.help()
1339 In [1]: import profile; profile.help()
1340 """
1340 """
1341
1341
1342 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1342 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1343 # protect user quote marks
1343 # protect user quote marks
1344 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1344 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1345
1345
1346 if user_mode: # regular user call
1346 if user_mode: # regular user call
1347 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1347 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1348 list_all=1)
1348 list_all=1)
1349 namespace = self.shell.user_ns
1349 namespace = self.shell.user_ns
1350 else: # called to run a program by %run -p
1350 else: # called to run a program by %run -p
1351 try:
1351 try:
1352 filename = get_py_filename(arg_lst[0])
1352 filename = get_py_filename(arg_lst[0])
1353 except IOError,msg:
1353 except IOError,msg:
1354 error(msg)
1354 error(msg)
1355 return
1355 return
1356
1356
1357 arg_str = 'execfile(filename,prog_ns)'
1357 arg_str = 'execfile(filename,prog_ns)'
1358 namespace = locals()
1358 namespace = locals()
1359
1359
1360 opts.merge(opts_def)
1360 opts.merge(opts_def)
1361
1361
1362 prof = profile.Profile()
1362 prof = profile.Profile()
1363 try:
1363 try:
1364 prof = prof.runctx(arg_str,namespace,namespace)
1364 prof = prof.runctx(arg_str,namespace,namespace)
1365 sys_exit = ''
1365 sys_exit = ''
1366 except SystemExit:
1366 except SystemExit:
1367 sys_exit = """*** SystemExit exception caught in code being profiled."""
1367 sys_exit = """*** SystemExit exception caught in code being profiled."""
1368
1368
1369 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1369 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1370
1370
1371 lims = opts.l
1371 lims = opts.l
1372 if lims:
1372 if lims:
1373 lims = [] # rebuild lims with ints/floats/strings
1373 lims = [] # rebuild lims with ints/floats/strings
1374 for lim in opts.l:
1374 for lim in opts.l:
1375 try:
1375 try:
1376 lims.append(int(lim))
1376 lims.append(int(lim))
1377 except ValueError:
1377 except ValueError:
1378 try:
1378 try:
1379 lims.append(float(lim))
1379 lims.append(float(lim))
1380 except ValueError:
1380 except ValueError:
1381 lims.append(lim)
1381 lims.append(lim)
1382
1382
1383 # Trap output.
1383 # Trap output.
1384 stdout_trap = StringIO()
1384 stdout_trap = StringIO()
1385
1385
1386 if hasattr(stats,'stream'):
1386 if hasattr(stats,'stream'):
1387 # In newer versions of python, the stats object has a 'stream'
1387 # In newer versions of python, the stats object has a 'stream'
1388 # attribute to write into.
1388 # attribute to write into.
1389 stats.stream = stdout_trap
1389 stats.stream = stdout_trap
1390 stats.print_stats(*lims)
1390 stats.print_stats(*lims)
1391 else:
1391 else:
1392 # For older versions, we manually redirect stdout during printing
1392 # For older versions, we manually redirect stdout during printing
1393 sys_stdout = sys.stdout
1393 sys_stdout = sys.stdout
1394 try:
1394 try:
1395 sys.stdout = stdout_trap
1395 sys.stdout = stdout_trap
1396 stats.print_stats(*lims)
1396 stats.print_stats(*lims)
1397 finally:
1397 finally:
1398 sys.stdout = sys_stdout
1398 sys.stdout = sys_stdout
1399
1399
1400 output = stdout_trap.getvalue()
1400 output = stdout_trap.getvalue()
1401 output = output.rstrip()
1401 output = output.rstrip()
1402
1402
1403 page(output,screen_lines=self.shell.rc.screen_length)
1403 page(output,screen_lines=self.shell.rc.screen_length)
1404 print sys_exit,
1404 print sys_exit,
1405
1405
1406 dump_file = opts.D[0]
1406 dump_file = opts.D[0]
1407 text_file = opts.T[0]
1407 text_file = opts.T[0]
1408 if dump_file:
1408 if dump_file:
1409 prof.dump_stats(dump_file)
1409 prof.dump_stats(dump_file)
1410 print '\n*** Profile stats marshalled to file',\
1410 print '\n*** Profile stats marshalled to file',\
1411 `dump_file`+'.',sys_exit
1411 `dump_file`+'.',sys_exit
1412 if text_file:
1412 if text_file:
1413 pfile = file(text_file,'w')
1413 pfile = file(text_file,'w')
1414 pfile.write(output)
1414 pfile.write(output)
1415 pfile.close()
1415 pfile.close()
1416 print '\n*** Profile printout saved to text file',\
1416 print '\n*** Profile printout saved to text file',\
1417 `text_file`+'.',sys_exit
1417 `text_file`+'.',sys_exit
1418
1418
1419 if opts.has_key('r'):
1419 if opts.has_key('r'):
1420 return stats
1420 return stats
1421 else:
1421 else:
1422 return None
1422 return None
1423
1423
1424 @testdec.skip_doctest
1424 @testdec.skip_doctest
1425 def magic_run(self, parameter_s ='',runner=None):
1425 def magic_run(self, parameter_s ='',runner=None):
1426 """Run the named file inside IPython as a program.
1426 """Run the named file inside IPython as a program.
1427
1427
1428 Usage:\\
1428 Usage:\\
1429 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1429 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1430
1430
1431 Parameters after the filename are passed as command-line arguments to
1431 Parameters after the filename are passed as command-line arguments to
1432 the program (put in sys.argv). Then, control returns to IPython's
1432 the program (put in sys.argv). Then, control returns to IPython's
1433 prompt.
1433 prompt.
1434
1434
1435 This is similar to running at a system prompt:\\
1435 This is similar to running at a system prompt:\\
1436 $ python file args\\
1436 $ python file args\\
1437 but with the advantage of giving you IPython's tracebacks, and of
1437 but with the advantage of giving you IPython's tracebacks, and of
1438 loading all variables into your interactive namespace for further use
1438 loading all variables into your interactive namespace for further use
1439 (unless -p is used, see below).
1439 (unless -p is used, see below).
1440
1440
1441 The file is executed in a namespace initially consisting only of
1441 The file is executed in a namespace initially consisting only of
1442 __name__=='__main__' and sys.argv constructed as indicated. It thus
1442 __name__=='__main__' and sys.argv constructed as indicated. It thus
1443 sees its environment as if it were being run as a stand-alone program
1443 sees its environment as if it were being run as a stand-alone program
1444 (except for sharing global objects such as previously imported
1444 (except for sharing global objects such as previously imported
1445 modules). But after execution, the IPython interactive namespace gets
1445 modules). But after execution, the IPython interactive namespace gets
1446 updated with all variables defined in the program (except for __name__
1446 updated with all variables defined in the program (except for __name__
1447 and sys.argv). This allows for very convenient loading of code for
1447 and sys.argv). This allows for very convenient loading of code for
1448 interactive work, while giving each program a 'clean sheet' to run in.
1448 interactive work, while giving each program a 'clean sheet' to run in.
1449
1449
1450 Options:
1450 Options:
1451
1451
1452 -n: __name__ is NOT set to '__main__', but to the running file's name
1452 -n: __name__ is NOT set to '__main__', but to the running file's name
1453 without extension (as python does under import). This allows running
1453 without extension (as python does under import). This allows running
1454 scripts and reloading the definitions in them without calling code
1454 scripts and reloading the definitions in them without calling code
1455 protected by an ' if __name__ == "__main__" ' clause.
1455 protected by an ' if __name__ == "__main__" ' clause.
1456
1456
1457 -i: run the file in IPython's namespace instead of an empty one. This
1457 -i: run the file in IPython's namespace instead of an empty one. This
1458 is useful if you are experimenting with code written in a text editor
1458 is useful if you are experimenting with code written in a text editor
1459 which depends on variables defined interactively.
1459 which depends on variables defined interactively.
1460
1460
1461 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1461 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1462 being run. This is particularly useful if IPython is being used to
1462 being run. This is particularly useful if IPython is being used to
1463 run unittests, which always exit with a sys.exit() call. In such
1463 run unittests, which always exit with a sys.exit() call. In such
1464 cases you are interested in the output of the test results, not in
1464 cases you are interested in the output of the test results, not in
1465 seeing a traceback of the unittest module.
1465 seeing a traceback of the unittest module.
1466
1466
1467 -t: print timing information at the end of the run. IPython will give
1467 -t: print timing information at the end of the run. IPython will give
1468 you an estimated CPU time consumption for your script, which under
1468 you an estimated CPU time consumption for your script, which under
1469 Unix uses the resource module to avoid the wraparound problems of
1469 Unix uses the resource module to avoid the wraparound problems of
1470 time.clock(). Under Unix, an estimate of time spent on system tasks
1470 time.clock(). Under Unix, an estimate of time spent on system tasks
1471 is also given (for Windows platforms this is reported as 0.0).
1471 is also given (for Windows platforms this is reported as 0.0).
1472
1472
1473 If -t is given, an additional -N<N> option can be given, where <N>
1473 If -t is given, an additional -N<N> option can be given, where <N>
1474 must be an integer indicating how many times you want the script to
1474 must be an integer indicating how many times you want the script to
1475 run. The final timing report will include total and per run results.
1475 run. The final timing report will include total and per run results.
1476
1476
1477 For example (testing the script uniq_stable.py):
1477 For example (testing the script uniq_stable.py):
1478
1478
1479 In [1]: run -t uniq_stable
1479 In [1]: run -t uniq_stable
1480
1480
1481 IPython CPU timings (estimated):\\
1481 IPython CPU timings (estimated):\\
1482 User : 0.19597 s.\\
1482 User : 0.19597 s.\\
1483 System: 0.0 s.\\
1483 System: 0.0 s.\\
1484
1484
1485 In [2]: run -t -N5 uniq_stable
1485 In [2]: run -t -N5 uniq_stable
1486
1486
1487 IPython CPU timings (estimated):\\
1487 IPython CPU timings (estimated):\\
1488 Total runs performed: 5\\
1488 Total runs performed: 5\\
1489 Times : Total Per run\\
1489 Times : Total Per run\\
1490 User : 0.910862 s, 0.1821724 s.\\
1490 User : 0.910862 s, 0.1821724 s.\\
1491 System: 0.0 s, 0.0 s.
1491 System: 0.0 s, 0.0 s.
1492
1492
1493 -d: run your program under the control of pdb, the Python debugger.
1493 -d: run your program under the control of pdb, the Python debugger.
1494 This allows you to execute your program step by step, watch variables,
1494 This allows you to execute your program step by step, watch variables,
1495 etc. Internally, what IPython does is similar to calling:
1495 etc. Internally, what IPython does is similar to calling:
1496
1496
1497 pdb.run('execfile("YOURFILENAME")')
1497 pdb.run('execfile("YOURFILENAME")')
1498
1498
1499 with a breakpoint set on line 1 of your file. You can change the line
1499 with a breakpoint set on line 1 of your file. You can change the line
1500 number for this automatic breakpoint to be <N> by using the -bN option
1500 number for this automatic breakpoint to be <N> by using the -bN option
1501 (where N must be an integer). For example:
1501 (where N must be an integer). For example:
1502
1502
1503 %run -d -b40 myscript
1503 %run -d -b40 myscript
1504
1504
1505 will set the first breakpoint at line 40 in myscript.py. Note that
1505 will set the first breakpoint at line 40 in myscript.py. Note that
1506 the first breakpoint must be set on a line which actually does
1506 the first breakpoint must be set on a line which actually does
1507 something (not a comment or docstring) for it to stop execution.
1507 something (not a comment or docstring) for it to stop execution.
1508
1508
1509 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1509 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1510 first enter 'c' (without qoutes) to start execution up to the first
1510 first enter 'c' (without qoutes) to start execution up to the first
1511 breakpoint.
1511 breakpoint.
1512
1512
1513 Entering 'help' gives information about the use of the debugger. You
1513 Entering 'help' gives information about the use of the debugger. You
1514 can easily see pdb's full documentation with "import pdb;pdb.help()"
1514 can easily see pdb's full documentation with "import pdb;pdb.help()"
1515 at a prompt.
1515 at a prompt.
1516
1516
1517 -p: run program under the control of the Python profiler module (which
1517 -p: run program under the control of the Python profiler module (which
1518 prints a detailed report of execution times, function calls, etc).
1518 prints a detailed report of execution times, function calls, etc).
1519
1519
1520 You can pass other options after -p which affect the behavior of the
1520 You can pass other options after -p which affect the behavior of the
1521 profiler itself. See the docs for %prun for details.
1521 profiler itself. See the docs for %prun for details.
1522
1522
1523 In this mode, the program's variables do NOT propagate back to the
1523 In this mode, the program's variables do NOT propagate back to the
1524 IPython interactive namespace (because they remain in the namespace
1524 IPython interactive namespace (because they remain in the namespace
1525 where the profiler executes them).
1525 where the profiler executes them).
1526
1526
1527 Internally this triggers a call to %prun, see its documentation for
1527 Internally this triggers a call to %prun, see its documentation for
1528 details on the options available specifically for profiling.
1528 details on the options available specifically for profiling.
1529
1529
1530 There is one special usage for which the text above doesn't apply:
1530 There is one special usage for which the text above doesn't apply:
1531 if the filename ends with .ipy, the file is run as ipython script,
1531 if the filename ends with .ipy, the file is run as ipython script,
1532 just as if the commands were written on IPython prompt.
1532 just as if the commands were written on IPython prompt.
1533 """
1533 """
1534
1534
1535 # get arguments and set sys.argv for program to be run.
1535 # get arguments and set sys.argv for program to be run.
1536 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1536 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1537 mode='list',list_all=1)
1537 mode='list',list_all=1)
1538
1538
1539 try:
1539 try:
1540 filename = get_py_filename(arg_lst[0])
1540 filename = get_py_filename(arg_lst[0])
1541 except IndexError:
1541 except IndexError:
1542 warn('you must provide at least a filename.')
1542 warn('you must provide at least a filename.')
1543 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1543 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1544 return
1544 return
1545 except IOError,msg:
1545 except IOError,msg:
1546 error(msg)
1546 error(msg)
1547 return
1547 return
1548
1548
1549 if filename.lower().endswith('.ipy'):
1549 if filename.lower().endswith('.ipy'):
1550 self.api.runlines(open(filename).read())
1550 self.api.runlines(open(filename).read())
1551 return
1551 return
1552
1552
1553 # Control the response to exit() calls made by the script being run
1553 # Control the response to exit() calls made by the script being run
1554 exit_ignore = opts.has_key('e')
1554 exit_ignore = opts.has_key('e')
1555
1555
1556 # Make sure that the running script gets a proper sys.argv as if it
1556 # Make sure that the running script gets a proper sys.argv as if it
1557 # were run from a system shell.
1557 # were run from a system shell.
1558 save_argv = sys.argv # save it for later restoring
1558 save_argv = sys.argv # save it for later restoring
1559 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1559 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1560
1560
1561 if opts.has_key('i'):
1561 if opts.has_key('i'):
1562 # Run in user's interactive namespace
1562 # Run in user's interactive namespace
1563 prog_ns = self.shell.user_ns
1563 prog_ns = self.shell.user_ns
1564 __name__save = self.shell.user_ns['__name__']
1564 __name__save = self.shell.user_ns['__name__']
1565 prog_ns['__name__'] = '__main__'
1565 prog_ns['__name__'] = '__main__'
1566 main_mod = FakeModule(prog_ns)
1566 main_mod = FakeModule(prog_ns)
1567 else:
1567 else:
1568 # Run in a fresh, empty namespace
1568 # Run in a fresh, empty namespace
1569 if opts.has_key('n'):
1569 if opts.has_key('n'):
1570 name = os.path.splitext(os.path.basename(filename))[0]
1570 name = os.path.splitext(os.path.basename(filename))[0]
1571 else:
1571 else:
1572 name = '__main__'
1572 name = '__main__'
1573 main_mod = FakeModule()
1573 main_mod = FakeModule()
1574 prog_ns = main_mod.__dict__
1574 prog_ns = main_mod.__dict__
1575 prog_ns['__name__'] = name
1575 prog_ns['__name__'] = name
1576 # The shell MUST hold a reference to main_mod so after %run exits,
1576 # The shell MUST hold a reference to main_mod so after %run exits,
1577 # the python deletion mechanism doesn't zero it out (leaving
1577 # the python deletion mechanism doesn't zero it out (leaving
1578 # dangling references)
1578 # dangling references)
1579 self.shell._user_main_modules.append(main_mod)
1579 self.shell._user_main_modules.append(main_mod)
1580
1580
1581 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1581 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1582 # set the __file__ global in the script's namespace
1582 # set the __file__ global in the script's namespace
1583 prog_ns['__file__'] = filename
1583 prog_ns['__file__'] = filename
1584
1584
1585 # pickle fix. See iplib for an explanation. But we need to make sure
1585 # pickle fix. See iplib for an explanation. But we need to make sure
1586 # that, if we overwrite __main__, we replace it at the end
1586 # that, if we overwrite __main__, we replace it at the end
1587 main_mod_name = prog_ns['__name__']
1587 main_mod_name = prog_ns['__name__']
1588
1588
1589 if main_mod_name == '__main__':
1589 if main_mod_name == '__main__':
1590 restore_main = sys.modules['__main__']
1590 restore_main = sys.modules['__main__']
1591 else:
1591 else:
1592 restore_main = False
1592 restore_main = False
1593
1593
1594 # This needs to be undone at the end to prevent holding references to
1594 # This needs to be undone at the end to prevent holding references to
1595 # every single object ever created.
1595 # every single object ever created.
1596 sys.modules[main_mod_name] = main_mod
1596 sys.modules[main_mod_name] = main_mod
1597
1597
1598 stats = None
1598 stats = None
1599 try:
1599 try:
1600 self.shell.savehist()
1600 self.shell.savehist()
1601
1601
1602 if opts.has_key('p'):
1602 if opts.has_key('p'):
1603 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1603 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1604 else:
1604 else:
1605 if opts.has_key('d'):
1605 if opts.has_key('d'):
1606 deb = Debugger.Pdb(self.shell.rc.colors)
1606 deb = Debugger.Pdb(self.shell.rc.colors)
1607 # reset Breakpoint state, which is moronically kept
1607 # reset Breakpoint state, which is moronically kept
1608 # in a class
1608 # in a class
1609 bdb.Breakpoint.next = 1
1609 bdb.Breakpoint.next = 1
1610 bdb.Breakpoint.bplist = {}
1610 bdb.Breakpoint.bplist = {}
1611 bdb.Breakpoint.bpbynumber = [None]
1611 bdb.Breakpoint.bpbynumber = [None]
1612 # Set an initial breakpoint to stop execution
1612 # Set an initial breakpoint to stop execution
1613 maxtries = 10
1613 maxtries = 10
1614 bp = int(opts.get('b',[1])[0])
1614 bp = int(opts.get('b',[1])[0])
1615 checkline = deb.checkline(filename,bp)
1615 checkline = deb.checkline(filename,bp)
1616 if not checkline:
1616 if not checkline:
1617 for bp in range(bp+1,bp+maxtries+1):
1617 for bp in range(bp+1,bp+maxtries+1):
1618 if deb.checkline(filename,bp):
1618 if deb.checkline(filename,bp):
1619 break
1619 break
1620 else:
1620 else:
1621 msg = ("\nI failed to find a valid line to set "
1621 msg = ("\nI failed to find a valid line to set "
1622 "a breakpoint\n"
1622 "a breakpoint\n"
1623 "after trying up to line: %s.\n"
1623 "after trying up to line: %s.\n"
1624 "Please set a valid breakpoint manually "
1624 "Please set a valid breakpoint manually "
1625 "with the -b option." % bp)
1625 "with the -b option." % bp)
1626 error(msg)
1626 error(msg)
1627 return
1627 return
1628 # if we find a good linenumber, set the breakpoint
1628 # if we find a good linenumber, set the breakpoint
1629 deb.do_break('%s:%s' % (filename,bp))
1629 deb.do_break('%s:%s' % (filename,bp))
1630 # Start file run
1630 # Start file run
1631 print "NOTE: Enter 'c' at the",
1631 print "NOTE: Enter 'c' at the",
1632 print "%s prompt to start your script." % deb.prompt
1632 print "%s prompt to start your script." % deb.prompt
1633 try:
1633 try:
1634 deb.run('execfile("%s")' % filename,prog_ns)
1634 deb.run('execfile("%s")' % filename,prog_ns)
1635
1635
1636 except:
1636 except:
1637 etype, value, tb = sys.exc_info()
1637 etype, value, tb = sys.exc_info()
1638 # Skip three frames in the traceback: the %run one,
1638 # Skip three frames in the traceback: the %run one,
1639 # one inside bdb.py, and the command-line typed by the
1639 # one inside bdb.py, and the command-line typed by the
1640 # user (run by exec in pdb itself).
1640 # user (run by exec in pdb itself).
1641 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1641 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1642 else:
1642 else:
1643 if runner is None:
1643 if runner is None:
1644 runner = self.shell.safe_execfile
1644 runner = self.shell.safe_execfile
1645 if opts.has_key('t'):
1645 if opts.has_key('t'):
1646 # timed execution
1646 # timed execution
1647 try:
1647 try:
1648 nruns = int(opts['N'][0])
1648 nruns = int(opts['N'][0])
1649 if nruns < 1:
1649 if nruns < 1:
1650 error('Number of runs must be >=1')
1650 error('Number of runs must be >=1')
1651 return
1651 return
1652 except (KeyError):
1652 except (KeyError):
1653 nruns = 1
1653 nruns = 1
1654 if nruns == 1:
1654 if nruns == 1:
1655 t0 = clock2()
1655 t0 = clock2()
1656 runner(filename,prog_ns,prog_ns,
1656 runner(filename,prog_ns,prog_ns,
1657 exit_ignore=exit_ignore)
1657 exit_ignore=exit_ignore)
1658 t1 = clock2()
1658 t1 = clock2()
1659 t_usr = t1[0]-t0[0]
1659 t_usr = t1[0]-t0[0]
1660 t_sys = t1[1]-t1[1]
1660 t_sys = t1[1]-t1[1]
1661 print "\nIPython CPU timings (estimated):"
1661 print "\nIPython CPU timings (estimated):"
1662 print " User : %10s s." % t_usr
1662 print " User : %10s s." % t_usr
1663 print " System: %10s s." % t_sys
1663 print " System: %10s s." % t_sys
1664 else:
1664 else:
1665 runs = range(nruns)
1665 runs = range(nruns)
1666 t0 = clock2()
1666 t0 = clock2()
1667 for nr in runs:
1667 for nr in runs:
1668 runner(filename,prog_ns,prog_ns,
1668 runner(filename,prog_ns,prog_ns,
1669 exit_ignore=exit_ignore)
1669 exit_ignore=exit_ignore)
1670 t1 = clock2()
1670 t1 = clock2()
1671 t_usr = t1[0]-t0[0]
1671 t_usr = t1[0]-t0[0]
1672 t_sys = t1[1]-t1[1]
1672 t_sys = t1[1]-t1[1]
1673 print "\nIPython CPU timings (estimated):"
1673 print "\nIPython CPU timings (estimated):"
1674 print "Total runs performed:",nruns
1674 print "Total runs performed:",nruns
1675 print " Times : %10s %10s" % ('Total','Per run')
1675 print " Times : %10s %10s" % ('Total','Per run')
1676 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1676 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1677 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1677 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1678
1678
1679 else:
1679 else:
1680 # regular execution
1680 # regular execution
1681 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1681 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1682 if opts.has_key('i'):
1682 if opts.has_key('i'):
1683 self.shell.user_ns['__name__'] = __name__save
1683 self.shell.user_ns['__name__'] = __name__save
1684 else:
1684 else:
1685 # update IPython interactive namespace
1685 # update IPython interactive namespace
1686 del prog_ns['__name__']
1686 del prog_ns['__name__']
1687 self.shell.user_ns.update(prog_ns)
1687 self.shell.user_ns.update(prog_ns)
1688 finally:
1688 finally:
1689 # Ensure key global structures are restored
1689 # Ensure key global structures are restored
1690 sys.argv = save_argv
1690 sys.argv = save_argv
1691 if restore_main:
1691 if restore_main:
1692 sys.modules['__main__'] = restore_main
1692 sys.modules['__main__'] = restore_main
1693 else:
1693 else:
1694 # Remove from sys.modules the reference to main_mod we'd
1694 # Remove from sys.modules the reference to main_mod we'd
1695 # added. Otherwise it will trap references to objects
1695 # added. Otherwise it will trap references to objects
1696 # contained therein.
1696 # contained therein.
1697 del sys.modules[main_mod_name]
1697 del sys.modules[main_mod_name]
1698 self.shell.reloadhist()
1698 self.shell.reloadhist()
1699
1699
1700 return stats
1700 return stats
1701
1701
1702 def magic_runlog(self, parameter_s =''):
1702 def magic_runlog(self, parameter_s =''):
1703 """Run files as logs.
1703 """Run files as logs.
1704
1704
1705 Usage:\\
1705 Usage:\\
1706 %runlog file1 file2 ...
1706 %runlog file1 file2 ...
1707
1707
1708 Run the named files (treating them as log files) in sequence inside
1708 Run the named files (treating them as log files) in sequence inside
1709 the interpreter, and return to the prompt. This is much slower than
1709 the interpreter, and return to the prompt. This is much slower than
1710 %run because each line is executed in a try/except block, but it
1710 %run because each line is executed in a try/except block, but it
1711 allows running files with syntax errors in them.
1711 allows running files with syntax errors in them.
1712
1712
1713 Normally IPython will guess when a file is one of its own logfiles, so
1713 Normally IPython will guess when a file is one of its own logfiles, so
1714 you can typically use %run even for logs. This shorthand allows you to
1714 you can typically use %run even for logs. This shorthand allows you to
1715 force any file to be treated as a log file."""
1715 force any file to be treated as a log file."""
1716
1716
1717 for f in parameter_s.split():
1717 for f in parameter_s.split():
1718 self.shell.safe_execfile(f,self.shell.user_ns,
1718 self.shell.safe_execfile(f,self.shell.user_ns,
1719 self.shell.user_ns,islog=1)
1719 self.shell.user_ns,islog=1)
1720
1720
1721 @testdec.skip_doctest
1721 @testdec.skip_doctest
1722 def magic_timeit(self, parameter_s =''):
1722 def magic_timeit(self, parameter_s =''):
1723 """Time execution of a Python statement or expression
1723 """Time execution of a Python statement or expression
1724
1724
1725 Usage:\\
1725 Usage:\\
1726 %timeit [-n<N> -r<R> [-t|-c]] statement
1726 %timeit [-n<N> -r<R> [-t|-c]] statement
1727
1727
1728 Time execution of a Python statement or expression using the timeit
1728 Time execution of a Python statement or expression using the timeit
1729 module.
1729 module.
1730
1730
1731 Options:
1731 Options:
1732 -n<N>: execute the given statement <N> times in a loop. If this value
1732 -n<N>: execute the given statement <N> times in a loop. If this value
1733 is not given, a fitting value is chosen.
1733 is not given, a fitting value is chosen.
1734
1734
1735 -r<R>: repeat the loop iteration <R> times and take the best result.
1735 -r<R>: repeat the loop iteration <R> times and take the best result.
1736 Default: 3
1736 Default: 3
1737
1737
1738 -t: use time.time to measure the time, which is the default on Unix.
1738 -t: use time.time to measure the time, which is the default on Unix.
1739 This function measures wall time.
1739 This function measures wall time.
1740
1740
1741 -c: use time.clock to measure the time, which is the default on
1741 -c: use time.clock to measure the time, which is the default on
1742 Windows and measures wall time. On Unix, resource.getrusage is used
1742 Windows and measures wall time. On Unix, resource.getrusage is used
1743 instead and returns the CPU user time.
1743 instead and returns the CPU user time.
1744
1744
1745 -p<P>: use a precision of <P> digits to display the timing result.
1745 -p<P>: use a precision of <P> digits to display the timing result.
1746 Default: 3
1746 Default: 3
1747
1747
1748
1748
1749 Examples:
1749 Examples:
1750
1750
1751 In [1]: %timeit pass
1751 In [1]: %timeit pass
1752 10000000 loops, best of 3: 53.3 ns per loop
1752 10000000 loops, best of 3: 53.3 ns per loop
1753
1753
1754 In [2]: u = None
1754 In [2]: u = None
1755
1755
1756 In [3]: %timeit u is None
1756 In [3]: %timeit u is None
1757 10000000 loops, best of 3: 184 ns per loop
1757 10000000 loops, best of 3: 184 ns per loop
1758
1758
1759 In [4]: %timeit -r 4 u == None
1759 In [4]: %timeit -r 4 u == None
1760 1000000 loops, best of 4: 242 ns per loop
1760 1000000 loops, best of 4: 242 ns per loop
1761
1761
1762 In [5]: import time
1762 In [5]: import time
1763
1763
1764 In [6]: %timeit -n1 time.sleep(2)
1764 In [6]: %timeit -n1 time.sleep(2)
1765 1 loops, best of 3: 2 s per loop
1765 1 loops, best of 3: 2 s per loop
1766
1766
1767
1767
1768 The times reported by %timeit will be slightly higher than those
1768 The times reported by %timeit will be slightly higher than those
1769 reported by the timeit.py script when variables are accessed. This is
1769 reported by the timeit.py script when variables are accessed. This is
1770 due to the fact that %timeit executes the statement in the namespace
1770 due to the fact that %timeit executes the statement in the namespace
1771 of the shell, compared with timeit.py, which uses a single setup
1771 of the shell, compared with timeit.py, which uses a single setup
1772 statement to import function or create variables. Generally, the bias
1772 statement to import function or create variables. Generally, the bias
1773 does not matter as long as results from timeit.py are not mixed with
1773 does not matter as long as results from timeit.py are not mixed with
1774 those from %timeit."""
1774 those from %timeit."""
1775
1775
1776 import timeit
1776 import timeit
1777 import math
1777 import math
1778
1778
1779 units = [u"s", u"ms", u"\xb5s", u"ns"]
1779 units = [u"s", u"ms", u"\xb5s", u"ns"]
1780 scaling = [1, 1e3, 1e6, 1e9]
1780 scaling = [1, 1e3, 1e6, 1e9]
1781
1781
1782 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1782 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1783 posix=False)
1783 posix=False)
1784 if stmt == "":
1784 if stmt == "":
1785 return
1785 return
1786 timefunc = timeit.default_timer
1786 timefunc = timeit.default_timer
1787 number = int(getattr(opts, "n", 0))
1787 number = int(getattr(opts, "n", 0))
1788 repeat = int(getattr(opts, "r", timeit.default_repeat))
1788 repeat = int(getattr(opts, "r", timeit.default_repeat))
1789 precision = int(getattr(opts, "p", 3))
1789 precision = int(getattr(opts, "p", 3))
1790 if hasattr(opts, "t"):
1790 if hasattr(opts, "t"):
1791 timefunc = time.time
1791 timefunc = time.time
1792 if hasattr(opts, "c"):
1792 if hasattr(opts, "c"):
1793 timefunc = clock
1793 timefunc = clock
1794
1794
1795 timer = timeit.Timer(timer=timefunc)
1795 timer = timeit.Timer(timer=timefunc)
1796 # this code has tight coupling to the inner workings of timeit.Timer,
1796 # this code has tight coupling to the inner workings of timeit.Timer,
1797 # but is there a better way to achieve that the code stmt has access
1797 # but is there a better way to achieve that the code stmt has access
1798 # to the shell namespace?
1798 # to the shell namespace?
1799
1799
1800 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1800 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1801 'setup': "pass"}
1801 'setup': "pass"}
1802 # Track compilation time so it can be reported if too long
1802 # Track compilation time so it can be reported if too long
1803 # Minimum time above which compilation time will be reported
1803 # Minimum time above which compilation time will be reported
1804 tc_min = 0.1
1804 tc_min = 0.1
1805
1805
1806 t0 = clock()
1806 t0 = clock()
1807 code = compile(src, "<magic-timeit>", "exec")
1807 code = compile(src, "<magic-timeit>", "exec")
1808 tc = clock()-t0
1808 tc = clock()-t0
1809
1809
1810 ns = {}
1810 ns = {}
1811 exec code in self.shell.user_ns, ns
1811 exec code in self.shell.user_ns, ns
1812 timer.inner = ns["inner"]
1812 timer.inner = ns["inner"]
1813
1813
1814 if number == 0:
1814 if number == 0:
1815 # determine number so that 0.2 <= total time < 2.0
1815 # determine number so that 0.2 <= total time < 2.0
1816 number = 1
1816 number = 1
1817 for i in range(1, 10):
1817 for i in range(1, 10):
1818 number *= 10
1818 number *= 10
1819 if timer.timeit(number) >= 0.2:
1819 if timer.timeit(number) >= 0.2:
1820 break
1820 break
1821
1821
1822 best = min(timer.repeat(repeat, number)) / number
1822 best = min(timer.repeat(repeat, number)) / number
1823
1823
1824 if best > 0.0:
1824 if best > 0.0:
1825 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1825 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1826 else:
1826 else:
1827 order = 3
1827 order = 3
1828 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1828 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1829 precision,
1829 precision,
1830 best * scaling[order],
1830 best * scaling[order],
1831 units[order])
1831 units[order])
1832 if tc > tc_min:
1832 if tc > tc_min:
1833 print "Compiler time: %.2f s" % tc
1833 print "Compiler time: %.2f s" % tc
1834
1834
1835 @testdec.skip_doctest
1835 @testdec.skip_doctest
1836 def magic_time(self,parameter_s = ''):
1836 def magic_time(self,parameter_s = ''):
1837 """Time execution of a Python statement or expression.
1837 """Time execution of a Python statement or expression.
1838
1838
1839 The CPU and wall clock times are printed, and the value of the
1839 The CPU and wall clock times are printed, and the value of the
1840 expression (if any) is returned. Note that under Win32, system time
1840 expression (if any) is returned. Note that under Win32, system time
1841 is always reported as 0, since it can not be measured.
1841 is always reported as 0, since it can not be measured.
1842
1842
1843 This function provides very basic timing functionality. In Python
1843 This function provides very basic timing functionality. In Python
1844 2.3, the timeit module offers more control and sophistication, so this
1844 2.3, the timeit module offers more control and sophistication, so this
1845 could be rewritten to use it (patches welcome).
1845 could be rewritten to use it (patches welcome).
1846
1846
1847 Some examples:
1847 Some examples:
1848
1848
1849 In [1]: time 2**128
1849 In [1]: time 2**128
1850 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1850 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1851 Wall time: 0.00
1851 Wall time: 0.00
1852 Out[1]: 340282366920938463463374607431768211456L
1852 Out[1]: 340282366920938463463374607431768211456L
1853
1853
1854 In [2]: n = 1000000
1854 In [2]: n = 1000000
1855
1855
1856 In [3]: time sum(range(n))
1856 In [3]: time sum(range(n))
1857 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1857 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1858 Wall time: 1.37
1858 Wall time: 1.37
1859 Out[3]: 499999500000L
1859 Out[3]: 499999500000L
1860
1860
1861 In [4]: time print 'hello world'
1861 In [4]: time print 'hello world'
1862 hello world
1862 hello world
1863 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1863 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1864 Wall time: 0.00
1864 Wall time: 0.00
1865
1865
1866 Note that the time needed by Python to compile the given expression
1866 Note that the time needed by Python to compile the given expression
1867 will be reported if it is more than 0.1s. In this example, the
1867 will be reported if it is more than 0.1s. In this example, the
1868 actual exponentiation is done by Python at compilation time, so while
1868 actual exponentiation is done by Python at compilation time, so while
1869 the expression can take a noticeable amount of time to compute, that
1869 the expression can take a noticeable amount of time to compute, that
1870 time is purely due to the compilation:
1870 time is purely due to the compilation:
1871
1871
1872 In [5]: time 3**9999;
1872 In [5]: time 3**9999;
1873 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1873 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1874 Wall time: 0.00 s
1874 Wall time: 0.00 s
1875
1875
1876 In [6]: time 3**999999;
1876 In [6]: time 3**999999;
1877 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1877 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1878 Wall time: 0.00 s
1878 Wall time: 0.00 s
1879 Compiler : 0.78 s
1879 Compiler : 0.78 s
1880 """
1880 """
1881
1881
1882 # fail immediately if the given expression can't be compiled
1882 # fail immediately if the given expression can't be compiled
1883
1883
1884 expr = self.shell.prefilter(parameter_s,False)
1884 expr = self.shell.prefilter(parameter_s,False)
1885
1885
1886 # Minimum time above which compilation time will be reported
1886 # Minimum time above which compilation time will be reported
1887 tc_min = 0.1
1887 tc_min = 0.1
1888
1888
1889 try:
1889 try:
1890 mode = 'eval'
1890 mode = 'eval'
1891 t0 = clock()
1891 t0 = clock()
1892 code = compile(expr,'<timed eval>',mode)
1892 code = compile(expr,'<timed eval>',mode)
1893 tc = clock()-t0
1893 tc = clock()-t0
1894 except SyntaxError:
1894 except SyntaxError:
1895 mode = 'exec'
1895 mode = 'exec'
1896 t0 = clock()
1896 t0 = clock()
1897 code = compile(expr,'<timed exec>',mode)
1897 code = compile(expr,'<timed exec>',mode)
1898 tc = clock()-t0
1898 tc = clock()-t0
1899 # skew measurement as little as possible
1899 # skew measurement as little as possible
1900 glob = self.shell.user_ns
1900 glob = self.shell.user_ns
1901 clk = clock2
1901 clk = clock2
1902 wtime = time.time
1902 wtime = time.time
1903 # time execution
1903 # time execution
1904 wall_st = wtime()
1904 wall_st = wtime()
1905 if mode=='eval':
1905 if mode=='eval':
1906 st = clk()
1906 st = clk()
1907 out = eval(code,glob)
1907 out = eval(code,glob)
1908 end = clk()
1908 end = clk()
1909 else:
1909 else:
1910 st = clk()
1910 st = clk()
1911 exec code in glob
1911 exec code in glob
1912 end = clk()
1912 end = clk()
1913 out = None
1913 out = None
1914 wall_end = wtime()
1914 wall_end = wtime()
1915 # Compute actual times and report
1915 # Compute actual times and report
1916 wall_time = wall_end-wall_st
1916 wall_time = wall_end-wall_st
1917 cpu_user = end[0]-st[0]
1917 cpu_user = end[0]-st[0]
1918 cpu_sys = end[1]-st[1]
1918 cpu_sys = end[1]-st[1]
1919 cpu_tot = cpu_user+cpu_sys
1919 cpu_tot = cpu_user+cpu_sys
1920 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1920 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1921 (cpu_user,cpu_sys,cpu_tot)
1921 (cpu_user,cpu_sys,cpu_tot)
1922 print "Wall time: %.2f s" % wall_time
1922 print "Wall time: %.2f s" % wall_time
1923 if tc > tc_min:
1923 if tc > tc_min:
1924 print "Compiler : %.2f s" % tc
1924 print "Compiler : %.2f s" % tc
1925 return out
1925 return out
1926
1926
1927 @testdec.skip_doctest
1927 @testdec.skip_doctest
1928 def magic_macro(self,parameter_s = ''):
1928 def magic_macro(self,parameter_s = ''):
1929 """Define a set of input lines as a macro for future re-execution.
1929 """Define a set of input lines as a macro for future re-execution.
1930
1930
1931 Usage:\\
1931 Usage:\\
1932 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1932 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1933
1933
1934 Options:
1934 Options:
1935
1935
1936 -r: use 'raw' input. By default, the 'processed' history is used,
1936 -r: use 'raw' input. By default, the 'processed' history is used,
1937 so that magics are loaded in their transformed version to valid
1937 so that magics are loaded in their transformed version to valid
1938 Python. If this option is given, the raw input as typed as the
1938 Python. If this option is given, the raw input as typed as the
1939 command line is used instead.
1939 command line is used instead.
1940
1940
1941 This will define a global variable called `name` which is a string
1941 This will define a global variable called `name` which is a string
1942 made of joining the slices and lines you specify (n1,n2,... numbers
1942 made of joining the slices and lines you specify (n1,n2,... numbers
1943 above) from your input history into a single string. This variable
1943 above) from your input history into a single string. This variable
1944 acts like an automatic function which re-executes those lines as if
1944 acts like an automatic function which re-executes those lines as if
1945 you had typed them. You just type 'name' at the prompt and the code
1945 you had typed them. You just type 'name' at the prompt and the code
1946 executes.
1946 executes.
1947
1947
1948 The notation for indicating number ranges is: n1-n2 means 'use line
1948 The notation for indicating number ranges is: n1-n2 means 'use line
1949 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1949 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1950 using the lines numbered 5,6 and 7.
1950 using the lines numbered 5,6 and 7.
1951
1951
1952 Note: as a 'hidden' feature, you can also use traditional python slice
1952 Note: as a 'hidden' feature, you can also use traditional python slice
1953 notation, where N:M means numbers N through M-1.
1953 notation, where N:M means numbers N through M-1.
1954
1954
1955 For example, if your history contains (%hist prints it):
1955 For example, if your history contains (%hist prints it):
1956
1956
1957 44: x=1
1957 44: x=1
1958 45: y=3
1958 45: y=3
1959 46: z=x+y
1959 46: z=x+y
1960 47: print x
1960 47: print x
1961 48: a=5
1961 48: a=5
1962 49: print 'x',x,'y',y
1962 49: print 'x',x,'y',y
1963
1963
1964 you can create a macro with lines 44 through 47 (included) and line 49
1964 you can create a macro with lines 44 through 47 (included) and line 49
1965 called my_macro with:
1965 called my_macro with:
1966
1966
1967 In [55]: %macro my_macro 44-47 49
1967 In [55]: %macro my_macro 44-47 49
1968
1968
1969 Now, typing `my_macro` (without quotes) will re-execute all this code
1969 Now, typing `my_macro` (without quotes) will re-execute all this code
1970 in one pass.
1970 in one pass.
1971
1971
1972 You don't need to give the line-numbers in order, and any given line
1972 You don't need to give the line-numbers in order, and any given line
1973 number can appear multiple times. You can assemble macros with any
1973 number can appear multiple times. You can assemble macros with any
1974 lines from your input history in any order.
1974 lines from your input history in any order.
1975
1975
1976 The macro is a simple object which holds its value in an attribute,
1976 The macro is a simple object which holds its value in an attribute,
1977 but IPython's display system checks for macros and executes them as
1977 but IPython's display system checks for macros and executes them as
1978 code instead of printing them when you type their name.
1978 code instead of printing them when you type their name.
1979
1979
1980 You can view a macro's contents by explicitly printing it with:
1980 You can view a macro's contents by explicitly printing it with:
1981
1981
1982 'print macro_name'.
1982 'print macro_name'.
1983
1983
1984 For one-off cases which DON'T contain magic function calls in them you
1984 For one-off cases which DON'T contain magic function calls in them you
1985 can obtain similar results by explicitly executing slices from your
1985 can obtain similar results by explicitly executing slices from your
1986 input history with:
1986 input history with:
1987
1987
1988 In [60]: exec In[44:48]+In[49]"""
1988 In [60]: exec In[44:48]+In[49]"""
1989
1989
1990 opts,args = self.parse_options(parameter_s,'r',mode='list')
1990 opts,args = self.parse_options(parameter_s,'r',mode='list')
1991 if not args:
1991 if not args:
1992 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
1992 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
1993 macs.sort()
1993 macs.sort()
1994 return macs
1994 return macs
1995 if len(args) == 1:
1995 if len(args) == 1:
1996 raise UsageError(
1996 raise UsageError(
1997 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1997 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1998 name,ranges = args[0], args[1:]
1998 name,ranges = args[0], args[1:]
1999
1999
2000 #print 'rng',ranges # dbg
2000 #print 'rng',ranges # dbg
2001 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2001 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2002 macro = Macro(lines)
2002 macro = Macro(lines)
2003 self.shell.user_ns.update({name:macro})
2003 self.shell.user_ns.update({name:macro})
2004 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2004 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2005 print 'Macro contents:'
2005 print 'Macro contents:'
2006 print macro,
2006 print macro,
2007
2007
2008 def magic_save(self,parameter_s = ''):
2008 def magic_save(self,parameter_s = ''):
2009 """Save a set of lines to a given filename.
2009 """Save a set of lines to a given filename.
2010
2010
2011 Usage:\\
2011 Usage:\\
2012 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2012 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2013
2013
2014 Options:
2014 Options:
2015
2015
2016 -r: use 'raw' input. By default, the 'processed' history is used,
2016 -r: use 'raw' input. By default, the 'processed' history is used,
2017 so that magics are loaded in their transformed version to valid
2017 so that magics are loaded in their transformed version to valid
2018 Python. If this option is given, the raw input as typed as the
2018 Python. If this option is given, the raw input as typed as the
2019 command line is used instead.
2019 command line is used instead.
2020
2020
2021 This function uses the same syntax as %macro for line extraction, but
2021 This function uses the same syntax as %macro for line extraction, but
2022 instead of creating a macro it saves the resulting string to the
2022 instead of creating a macro it saves the resulting string to the
2023 filename you specify.
2023 filename you specify.
2024
2024
2025 It adds a '.py' extension to the file if you don't do so yourself, and
2025 It adds a '.py' extension to the file if you don't do so yourself, and
2026 it asks for confirmation before overwriting existing files."""
2026 it asks for confirmation before overwriting existing files."""
2027
2027
2028 opts,args = self.parse_options(parameter_s,'r',mode='list')
2028 opts,args = self.parse_options(parameter_s,'r',mode='list')
2029 fname,ranges = args[0], args[1:]
2029 fname,ranges = args[0], args[1:]
2030 if not fname.endswith('.py'):
2030 if not fname.endswith('.py'):
2031 fname += '.py'
2031 fname += '.py'
2032 if os.path.isfile(fname):
2032 if os.path.isfile(fname):
2033 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2033 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2034 if ans.lower() not in ['y','yes']:
2034 if ans.lower() not in ['y','yes']:
2035 print 'Operation cancelled.'
2035 print 'Operation cancelled.'
2036 return
2036 return
2037 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2037 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2038 f = file(fname,'w')
2038 f = file(fname,'w')
2039 f.write(cmds)
2039 f.write(cmds)
2040 f.close()
2040 f.close()
2041 print 'The following commands were written to file `%s`:' % fname
2041 print 'The following commands were written to file `%s`:' % fname
2042 print cmds
2042 print cmds
2043
2043
2044 def _edit_macro(self,mname,macro):
2044 def _edit_macro(self,mname,macro):
2045 """open an editor with the macro data in a file"""
2045 """open an editor with the macro data in a file"""
2046 filename = self.shell.mktempfile(macro.value)
2046 filename = self.shell.mktempfile(macro.value)
2047 self.shell.hooks.editor(filename)
2047 self.shell.hooks.editor(filename)
2048
2048
2049 # and make a new macro object, to replace the old one
2049 # and make a new macro object, to replace the old one
2050 mfile = open(filename)
2050 mfile = open(filename)
2051 mvalue = mfile.read()
2051 mvalue = mfile.read()
2052 mfile.close()
2052 mfile.close()
2053 self.shell.user_ns[mname] = Macro(mvalue)
2053 self.shell.user_ns[mname] = Macro(mvalue)
2054
2054
2055 def magic_ed(self,parameter_s=''):
2055 def magic_ed(self,parameter_s=''):
2056 """Alias to %edit."""
2056 """Alias to %edit."""
2057 return self.magic_edit(parameter_s)
2057 return self.magic_edit(parameter_s)
2058
2058
2059 @testdec.skip_doctest
2059 @testdec.skip_doctest
2060 def magic_edit(self,parameter_s='',last_call=['','']):
2060 def magic_edit(self,parameter_s='',last_call=['','']):
2061 """Bring up an editor and execute the resulting code.
2061 """Bring up an editor and execute the resulting code.
2062
2062
2063 Usage:
2063 Usage:
2064 %edit [options] [args]
2064 %edit [options] [args]
2065
2065
2066 %edit runs IPython's editor hook. The default version of this hook is
2066 %edit runs IPython's editor hook. The default version of this hook is
2067 set to call the __IPYTHON__.rc.editor command. This is read from your
2067 set to call the __IPYTHON__.rc.editor command. This is read from your
2068 environment variable $EDITOR. If this isn't found, it will default to
2068 environment variable $EDITOR. If this isn't found, it will default to
2069 vi under Linux/Unix and to notepad under Windows. See the end of this
2069 vi under Linux/Unix and to notepad under Windows. See the end of this
2070 docstring for how to change the editor hook.
2070 docstring for how to change the editor hook.
2071
2071
2072 You can also set the value of this editor via the command line option
2072 You can also set the value of this editor via the command line option
2073 '-editor' or in your ipythonrc file. This is useful if you wish to use
2073 '-editor' or in your ipythonrc file. This is useful if you wish to use
2074 specifically for IPython an editor different from your typical default
2074 specifically for IPython an editor different from your typical default
2075 (and for Windows users who typically don't set environment variables).
2075 (and for Windows users who typically don't set environment variables).
2076
2076
2077 This command allows you to conveniently edit multi-line code right in
2077 This command allows you to conveniently edit multi-line code right in
2078 your IPython session.
2078 your IPython session.
2079
2079
2080 If called without arguments, %edit opens up an empty editor with a
2080 If called without arguments, %edit opens up an empty editor with a
2081 temporary file and will execute the contents of this file when you
2081 temporary file and will execute the contents of this file when you
2082 close it (don't forget to save it!).
2082 close it (don't forget to save it!).
2083
2083
2084
2084
2085 Options:
2085 Options:
2086
2086
2087 -n <number>: open the editor at a specified line number. By default,
2087 -n <number>: open the editor at a specified line number. By default,
2088 the IPython editor hook uses the unix syntax 'editor +N filename', but
2088 the IPython editor hook uses the unix syntax 'editor +N filename', but
2089 you can configure this by providing your own modified hook if your
2089 you can configure this by providing your own modified hook if your
2090 favorite editor supports line-number specifications with a different
2090 favorite editor supports line-number specifications with a different
2091 syntax.
2091 syntax.
2092
2092
2093 -p: this will call the editor with the same data as the previous time
2093 -p: this will call the editor with the same data as the previous time
2094 it was used, regardless of how long ago (in your current session) it
2094 it was used, regardless of how long ago (in your current session) it
2095 was.
2095 was.
2096
2096
2097 -r: use 'raw' input. This option only applies to input taken from the
2097 -r: use 'raw' input. This option only applies to input taken from the
2098 user's history. By default, the 'processed' history is used, so that
2098 user's history. By default, the 'processed' history is used, so that
2099 magics are loaded in their transformed version to valid Python. If
2099 magics are loaded in their transformed version to valid Python. If
2100 this option is given, the raw input as typed as the command line is
2100 this option is given, the raw input as typed as the command line is
2101 used instead. When you exit the editor, it will be executed by
2101 used instead. When you exit the editor, it will be executed by
2102 IPython's own processor.
2102 IPython's own processor.
2103
2103
2104 -x: do not execute the edited code immediately upon exit. This is
2104 -x: do not execute the edited code immediately upon exit. This is
2105 mainly useful if you are editing programs which need to be called with
2105 mainly useful if you are editing programs which need to be called with
2106 command line arguments, which you can then do using %run.
2106 command line arguments, which you can then do using %run.
2107
2107
2108
2108
2109 Arguments:
2109 Arguments:
2110
2110
2111 If arguments are given, the following possibilites exist:
2111 If arguments are given, the following possibilites exist:
2112
2112
2113 - The arguments are numbers or pairs of colon-separated numbers (like
2113 - The arguments are numbers or pairs of colon-separated numbers (like
2114 1 4:8 9). These are interpreted as lines of previous input to be
2114 1 4:8 9). These are interpreted as lines of previous input to be
2115 loaded into the editor. The syntax is the same of the %macro command.
2115 loaded into the editor. The syntax is the same of the %macro command.
2116
2116
2117 - If the argument doesn't start with a number, it is evaluated as a
2117 - If the argument doesn't start with a number, it is evaluated as a
2118 variable and its contents loaded into the editor. You can thus edit
2118 variable and its contents loaded into the editor. You can thus edit
2119 any string which contains python code (including the result of
2119 any string which contains python code (including the result of
2120 previous edits).
2120 previous edits).
2121
2121
2122 - If the argument is the name of an object (other than a string),
2122 - If the argument is the name of an object (other than a string),
2123 IPython will try to locate the file where it was defined and open the
2123 IPython will try to locate the file where it was defined and open the
2124 editor at the point where it is defined. You can use `%edit function`
2124 editor at the point where it is defined. You can use `%edit function`
2125 to load an editor exactly at the point where 'function' is defined,
2125 to load an editor exactly at the point where 'function' is defined,
2126 edit it and have the file be executed automatically.
2126 edit it and have the file be executed automatically.
2127
2127
2128 If the object is a macro (see %macro for details), this opens up your
2128 If the object is a macro (see %macro for details), this opens up your
2129 specified editor with a temporary file containing the macro's data.
2129 specified editor with a temporary file containing the macro's data.
2130 Upon exit, the macro is reloaded with the contents of the file.
2130 Upon exit, the macro is reloaded with the contents of the file.
2131
2131
2132 Note: opening at an exact line is only supported under Unix, and some
2132 Note: opening at an exact line is only supported under Unix, and some
2133 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2133 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2134 '+NUMBER' parameter necessary for this feature. Good editors like
2134 '+NUMBER' parameter necessary for this feature. Good editors like
2135 (X)Emacs, vi, jed, pico and joe all do.
2135 (X)Emacs, vi, jed, pico and joe all do.
2136
2136
2137 - If the argument is not found as a variable, IPython will look for a
2137 - If the argument is not found as a variable, IPython will look for a
2138 file with that name (adding .py if necessary) and load it into the
2138 file with that name (adding .py if necessary) and load it into the
2139 editor. It will execute its contents with execfile() when you exit,
2139 editor. It will execute its contents with execfile() when you exit,
2140 loading any code in the file into your interactive namespace.
2140 loading any code in the file into your interactive namespace.
2141
2141
2142 After executing your code, %edit will return as output the code you
2142 After executing your code, %edit will return as output the code you
2143 typed in the editor (except when it was an existing file). This way
2143 typed in the editor (except when it was an existing file). This way
2144 you can reload the code in further invocations of %edit as a variable,
2144 you can reload the code in further invocations of %edit as a variable,
2145 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2145 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2146 the output.
2146 the output.
2147
2147
2148 Note that %edit is also available through the alias %ed.
2148 Note that %edit is also available through the alias %ed.
2149
2149
2150 This is an example of creating a simple function inside the editor and
2150 This is an example of creating a simple function inside the editor and
2151 then modifying it. First, start up the editor:
2151 then modifying it. First, start up the editor:
2152
2152
2153 In [1]: ed
2153 In [1]: ed
2154 Editing... done. Executing edited code...
2154 Editing... done. Executing edited code...
2155 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2155 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2156
2156
2157 We can then call the function foo():
2157 We can then call the function foo():
2158
2158
2159 In [2]: foo()
2159 In [2]: foo()
2160 foo() was defined in an editing session
2160 foo() was defined in an editing session
2161
2161
2162 Now we edit foo. IPython automatically loads the editor with the
2162 Now we edit foo. IPython automatically loads the editor with the
2163 (temporary) file where foo() was previously defined:
2163 (temporary) file where foo() was previously defined:
2164
2164
2165 In [3]: ed foo
2165 In [3]: ed foo
2166 Editing... done. Executing edited code...
2166 Editing... done. Executing edited code...
2167
2167
2168 And if we call foo() again we get the modified version:
2168 And if we call foo() again we get the modified version:
2169
2169
2170 In [4]: foo()
2170 In [4]: foo()
2171 foo() has now been changed!
2171 foo() has now been changed!
2172
2172
2173 Here is an example of how to edit a code snippet successive
2173 Here is an example of how to edit a code snippet successive
2174 times. First we call the editor:
2174 times. First we call the editor:
2175
2175
2176 In [5]: ed
2176 In [5]: ed
2177 Editing... done. Executing edited code...
2177 Editing... done. Executing edited code...
2178 hello
2178 hello
2179 Out[5]: "print 'hello'n"
2179 Out[5]: "print 'hello'n"
2180
2180
2181 Now we call it again with the previous output (stored in _):
2181 Now we call it again with the previous output (stored in _):
2182
2182
2183 In [6]: ed _
2183 In [6]: ed _
2184 Editing... done. Executing edited code...
2184 Editing... done. Executing edited code...
2185 hello world
2185 hello world
2186 Out[6]: "print 'hello world'n"
2186 Out[6]: "print 'hello world'n"
2187
2187
2188 Now we call it with the output #8 (stored in _8, also as Out[8]):
2188 Now we call it with the output #8 (stored in _8, also as Out[8]):
2189
2189
2190 In [7]: ed _8
2190 In [7]: ed _8
2191 Editing... done. Executing edited code...
2191 Editing... done. Executing edited code...
2192 hello again
2192 hello again
2193 Out[7]: "print 'hello again'n"
2193 Out[7]: "print 'hello again'n"
2194
2194
2195
2195
2196 Changing the default editor hook:
2196 Changing the default editor hook:
2197
2197
2198 If you wish to write your own editor hook, you can put it in a
2198 If you wish to write your own editor hook, you can put it in a
2199 configuration file which you load at startup time. The default hook
2199 configuration file which you load at startup time. The default hook
2200 is defined in the IPython.hooks module, and you can use that as a
2200 is defined in the IPython.hooks module, and you can use that as a
2201 starting example for further modifications. That file also has
2201 starting example for further modifications. That file also has
2202 general instructions on how to set a new hook for use once you've
2202 general instructions on how to set a new hook for use once you've
2203 defined it."""
2203 defined it."""
2204
2204
2205 # FIXME: This function has become a convoluted mess. It needs a
2205 # FIXME: This function has become a convoluted mess. It needs a
2206 # ground-up rewrite with clean, simple logic.
2206 # ground-up rewrite with clean, simple logic.
2207
2207
2208 def make_filename(arg):
2208 def make_filename(arg):
2209 "Make a filename from the given args"
2209 "Make a filename from the given args"
2210 try:
2210 try:
2211 filename = get_py_filename(arg)
2211 filename = get_py_filename(arg)
2212 except IOError:
2212 except IOError:
2213 if args.endswith('.py'):
2213 if args.endswith('.py'):
2214 filename = arg
2214 filename = arg
2215 else:
2215 else:
2216 filename = None
2216 filename = None
2217 return filename
2217 return filename
2218
2218
2219 # custom exceptions
2219 # custom exceptions
2220 class DataIsObject(Exception): pass
2220 class DataIsObject(Exception): pass
2221
2221
2222 opts,args = self.parse_options(parameter_s,'prxn:')
2222 opts,args = self.parse_options(parameter_s,'prxn:')
2223 # Set a few locals from the options for convenience:
2223 # Set a few locals from the options for convenience:
2224 opts_p = opts.has_key('p')
2224 opts_p = opts.has_key('p')
2225 opts_r = opts.has_key('r')
2225 opts_r = opts.has_key('r')
2226
2226
2227 # Default line number value
2227 # Default line number value
2228 lineno = opts.get('n',None)
2228 lineno = opts.get('n',None)
2229
2229
2230 if opts_p:
2230 if opts_p:
2231 args = '_%s' % last_call[0]
2231 args = '_%s' % last_call[0]
2232 if not self.shell.user_ns.has_key(args):
2232 if not self.shell.user_ns.has_key(args):
2233 args = last_call[1]
2233 args = last_call[1]
2234
2234
2235 # use last_call to remember the state of the previous call, but don't
2235 # use last_call to remember the state of the previous call, but don't
2236 # let it be clobbered by successive '-p' calls.
2236 # let it be clobbered by successive '-p' calls.
2237 try:
2237 try:
2238 last_call[0] = self.shell.outputcache.prompt_count
2238 last_call[0] = self.shell.outputcache.prompt_count
2239 if not opts_p:
2239 if not opts_p:
2240 last_call[1] = parameter_s
2240 last_call[1] = parameter_s
2241 except:
2241 except:
2242 pass
2242 pass
2243
2243
2244 # by default this is done with temp files, except when the given
2244 # by default this is done with temp files, except when the given
2245 # arg is a filename
2245 # arg is a filename
2246 use_temp = 1
2246 use_temp = 1
2247
2247
2248 if re.match(r'\d',args):
2248 if re.match(r'\d',args):
2249 # Mode where user specifies ranges of lines, like in %macro.
2249 # Mode where user specifies ranges of lines, like in %macro.
2250 # This means that you can't edit files whose names begin with
2250 # This means that you can't edit files whose names begin with
2251 # numbers this way. Tough.
2251 # numbers this way. Tough.
2252 ranges = args.split()
2252 ranges = args.split()
2253 data = ''.join(self.extract_input_slices(ranges,opts_r))
2253 data = ''.join(self.extract_input_slices(ranges,opts_r))
2254 elif args.endswith('.py'):
2254 elif args.endswith('.py'):
2255 filename = make_filename(args)
2255 filename = make_filename(args)
2256 data = ''
2256 data = ''
2257 use_temp = 0
2257 use_temp = 0
2258 elif args:
2258 elif args:
2259 try:
2259 try:
2260 # Load the parameter given as a variable. If not a string,
2260 # Load the parameter given as a variable. If not a string,
2261 # process it as an object instead (below)
2261 # process it as an object instead (below)
2262
2262
2263 #print '*** args',args,'type',type(args) # dbg
2263 #print '*** args',args,'type',type(args) # dbg
2264 data = eval(args,self.shell.user_ns)
2264 data = eval(args,self.shell.user_ns)
2265 if not type(data) in StringTypes:
2265 if not type(data) in StringTypes:
2266 raise DataIsObject
2266 raise DataIsObject
2267
2267
2268 except (NameError,SyntaxError):
2268 except (NameError,SyntaxError):
2269 # given argument is not a variable, try as a filename
2269 # given argument is not a variable, try as a filename
2270 filename = make_filename(args)
2270 filename = make_filename(args)
2271 if filename is None:
2271 if filename is None:
2272 warn("Argument given (%s) can't be found as a variable "
2272 warn("Argument given (%s) can't be found as a variable "
2273 "or as a filename." % args)
2273 "or as a filename." % args)
2274 return
2274 return
2275
2275
2276 data = ''
2276 data = ''
2277 use_temp = 0
2277 use_temp = 0
2278 except DataIsObject:
2278 except DataIsObject:
2279
2279
2280 # macros have a special edit function
2280 # macros have a special edit function
2281 if isinstance(data,Macro):
2281 if isinstance(data,Macro):
2282 self._edit_macro(args,data)
2282 self._edit_macro(args,data)
2283 return
2283 return
2284
2284
2285 # For objects, try to edit the file where they are defined
2285 # For objects, try to edit the file where they are defined
2286 try:
2286 try:
2287 filename = inspect.getabsfile(data)
2287 filename = inspect.getabsfile(data)
2288 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2288 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2289 # class created by %edit? Try to find source
2289 # class created by %edit? Try to find source
2290 # by looking for method definitions instead, the
2290 # by looking for method definitions instead, the
2291 # __module__ in those classes is FakeModule.
2291 # __module__ in those classes is FakeModule.
2292 attrs = [getattr(data, aname) for aname in dir(data)]
2292 attrs = [getattr(data, aname) for aname in dir(data)]
2293 for attr in attrs:
2293 for attr in attrs:
2294 if not inspect.ismethod(attr):
2294 if not inspect.ismethod(attr):
2295 continue
2295 continue
2296 filename = inspect.getabsfile(attr)
2296 filename = inspect.getabsfile(attr)
2297 if filename and 'fakemodule' not in filename.lower():
2297 if filename and 'fakemodule' not in filename.lower():
2298 # change the attribute to be the edit target instead
2298 # change the attribute to be the edit target instead
2299 data = attr
2299 data = attr
2300 break
2300 break
2301
2301
2302 datafile = 1
2302 datafile = 1
2303 except TypeError:
2303 except TypeError:
2304 filename = make_filename(args)
2304 filename = make_filename(args)
2305 datafile = 1
2305 datafile = 1
2306 warn('Could not find file where `%s` is defined.\n'
2306 warn('Could not find file where `%s` is defined.\n'
2307 'Opening a file named `%s`' % (args,filename))
2307 'Opening a file named `%s`' % (args,filename))
2308 # Now, make sure we can actually read the source (if it was in
2308 # Now, make sure we can actually read the source (if it was in
2309 # a temp file it's gone by now).
2309 # a temp file it's gone by now).
2310 if datafile:
2310 if datafile:
2311 try:
2311 try:
2312 if lineno is None:
2312 if lineno is None:
2313 lineno = inspect.getsourcelines(data)[1]
2313 lineno = inspect.getsourcelines(data)[1]
2314 except IOError:
2314 except IOError:
2315 filename = make_filename(args)
2315 filename = make_filename(args)
2316 if filename is None:
2316 if filename is None:
2317 warn('The file `%s` where `%s` was defined cannot '
2317 warn('The file `%s` where `%s` was defined cannot '
2318 'be read.' % (filename,data))
2318 'be read.' % (filename,data))
2319 return
2319 return
2320 use_temp = 0
2320 use_temp = 0
2321 else:
2321 else:
2322 data = ''
2322 data = ''
2323
2323
2324 if use_temp:
2324 if use_temp:
2325 filename = self.shell.mktempfile(data)
2325 filename = self.shell.mktempfile(data)
2326 print 'IPython will make a temporary file named:',filename
2326 print 'IPython will make a temporary file named:',filename
2327
2327
2328 # do actual editing here
2328 # do actual editing here
2329 print 'Editing...',
2329 print 'Editing...',
2330 sys.stdout.flush()
2330 sys.stdout.flush()
2331 self.shell.hooks.editor(filename,lineno)
2331 self.shell.hooks.editor(filename,lineno)
2332 if opts.has_key('x'): # -x prevents actual execution
2332 if opts.has_key('x'): # -x prevents actual execution
2333 print
2333 print
2334 else:
2334 else:
2335 print 'done. Executing edited code...'
2335 print 'done. Executing edited code...'
2336 if opts_r:
2336 if opts_r:
2337 self.shell.runlines(file_read(filename))
2337 self.shell.runlines(file_read(filename))
2338 else:
2338 else:
2339 self.shell.safe_execfile(filename,self.shell.user_ns,
2339 self.shell.safe_execfile(filename,self.shell.user_ns,
2340 self.shell.user_ns)
2340 self.shell.user_ns)
2341 if use_temp:
2341 if use_temp:
2342 try:
2342 try:
2343 return open(filename).read()
2343 return open(filename).read()
2344 except IOError,msg:
2344 except IOError,msg:
2345 if msg.filename == filename:
2345 if msg.filename == filename:
2346 warn('File not found. Did you forget to save?')
2346 warn('File not found. Did you forget to save?')
2347 return
2347 return
2348 else:
2348 else:
2349 self.shell.showtraceback()
2349 self.shell.showtraceback()
2350
2350
2351 def magic_xmode(self,parameter_s = ''):
2351 def magic_xmode(self,parameter_s = ''):
2352 """Switch modes for the exception handlers.
2352 """Switch modes for the exception handlers.
2353
2353
2354 Valid modes: Plain, Context and Verbose.
2354 Valid modes: Plain, Context and Verbose.
2355
2355
2356 If called without arguments, acts as a toggle."""
2356 If called without arguments, acts as a toggle."""
2357
2357
2358 def xmode_switch_err(name):
2358 def xmode_switch_err(name):
2359 warn('Error changing %s exception modes.\n%s' %
2359 warn('Error changing %s exception modes.\n%s' %
2360 (name,sys.exc_info()[1]))
2360 (name,sys.exc_info()[1]))
2361
2361
2362 shell = self.shell
2362 shell = self.shell
2363 new_mode = parameter_s.strip().capitalize()
2363 new_mode = parameter_s.strip().capitalize()
2364 try:
2364 try:
2365 shell.InteractiveTB.set_mode(mode=new_mode)
2365 shell.InteractiveTB.set_mode(mode=new_mode)
2366 print 'Exception reporting mode:',shell.InteractiveTB.mode
2366 print 'Exception reporting mode:',shell.InteractiveTB.mode
2367 except:
2367 except:
2368 xmode_switch_err('user')
2368 xmode_switch_err('user')
2369
2369
2370 # threaded shells use a special handler in sys.excepthook
2370 # threaded shells use a special handler in sys.excepthook
2371 if shell.isthreaded:
2371 if shell.isthreaded:
2372 try:
2372 try:
2373 shell.sys_excepthook.set_mode(mode=new_mode)
2373 shell.sys_excepthook.set_mode(mode=new_mode)
2374 except:
2374 except:
2375 xmode_switch_err('threaded')
2375 xmode_switch_err('threaded')
2376
2376
2377 def magic_colors(self,parameter_s = ''):
2377 def magic_colors(self,parameter_s = ''):
2378 """Switch color scheme for prompts, info system and exception handlers.
2378 """Switch color scheme for prompts, info system and exception handlers.
2379
2379
2380 Currently implemented schemes: NoColor, Linux, LightBG.
2380 Currently implemented schemes: NoColor, Linux, LightBG.
2381
2381
2382 Color scheme names are not case-sensitive."""
2382 Color scheme names are not case-sensitive."""
2383
2383
2384 def color_switch_err(name):
2384 def color_switch_err(name):
2385 warn('Error changing %s color schemes.\n%s' %
2385 warn('Error changing %s color schemes.\n%s' %
2386 (name,sys.exc_info()[1]))
2386 (name,sys.exc_info()[1]))
2387
2387
2388
2388
2389 new_scheme = parameter_s.strip()
2389 new_scheme = parameter_s.strip()
2390 if not new_scheme:
2390 if not new_scheme:
2391 raise UsageError(
2391 raise UsageError(
2392 "%colors: you must specify a color scheme. See '%colors?'")
2392 "%colors: you must specify a color scheme. See '%colors?'")
2393 return
2393 return
2394 # local shortcut
2394 # local shortcut
2395 shell = self.shell
2395 shell = self.shell
2396
2396
2397 import IPython.rlineimpl as readline
2397 import IPython.rlineimpl as readline
2398
2398
2399 if not readline.have_readline and sys.platform == "win32":
2399 if not readline.have_readline and sys.platform == "win32":
2400 msg = """\
2400 msg = """\
2401 Proper color support under MS Windows requires the pyreadline library.
2401 Proper color support under MS Windows requires the pyreadline library.
2402 You can find it at:
2402 You can find it at:
2403 http://ipython.scipy.org/moin/PyReadline/Intro
2403 http://ipython.scipy.org/moin/PyReadline/Intro
2404 Gary's readline needs the ctypes module, from:
2404 Gary's readline needs the ctypes module, from:
2405 http://starship.python.net/crew/theller/ctypes
2405 http://starship.python.net/crew/theller/ctypes
2406 (Note that ctypes is already part of Python versions 2.5 and newer).
2406 (Note that ctypes is already part of Python versions 2.5 and newer).
2407
2407
2408 Defaulting color scheme to 'NoColor'"""
2408 Defaulting color scheme to 'NoColor'"""
2409 new_scheme = 'NoColor'
2409 new_scheme = 'NoColor'
2410 warn(msg)
2410 warn(msg)
2411
2411
2412 # readline option is 0
2412 # readline option is 0
2413 if not shell.has_readline:
2413 if not shell.has_readline:
2414 new_scheme = 'NoColor'
2414 new_scheme = 'NoColor'
2415
2415
2416 # Set prompt colors
2416 # Set prompt colors
2417 try:
2417 try:
2418 shell.outputcache.set_colors(new_scheme)
2418 shell.outputcache.set_colors(new_scheme)
2419 except:
2419 except:
2420 color_switch_err('prompt')
2420 color_switch_err('prompt')
2421 else:
2421 else:
2422 shell.rc.colors = \
2422 shell.rc.colors = \
2423 shell.outputcache.color_table.active_scheme_name
2423 shell.outputcache.color_table.active_scheme_name
2424 # Set exception colors
2424 # Set exception colors
2425 try:
2425 try:
2426 shell.InteractiveTB.set_colors(scheme = new_scheme)
2426 shell.InteractiveTB.set_colors(scheme = new_scheme)
2427 shell.SyntaxTB.set_colors(scheme = new_scheme)
2427 shell.SyntaxTB.set_colors(scheme = new_scheme)
2428 except:
2428 except:
2429 color_switch_err('exception')
2429 color_switch_err('exception')
2430
2430
2431 # threaded shells use a verbose traceback in sys.excepthook
2431 # threaded shells use a verbose traceback in sys.excepthook
2432 if shell.isthreaded:
2432 if shell.isthreaded:
2433 try:
2433 try:
2434 shell.sys_excepthook.set_colors(scheme=new_scheme)
2434 shell.sys_excepthook.set_colors(scheme=new_scheme)
2435 except:
2435 except:
2436 color_switch_err('system exception handler')
2436 color_switch_err('system exception handler')
2437
2437
2438 # Set info (for 'object?') colors
2438 # Set info (for 'object?') colors
2439 if shell.rc.color_info:
2439 if shell.rc.color_info:
2440 try:
2440 try:
2441 shell.inspector.set_active_scheme(new_scheme)
2441 shell.inspector.set_active_scheme(new_scheme)
2442 except:
2442 except:
2443 color_switch_err('object inspector')
2443 color_switch_err('object inspector')
2444 else:
2444 else:
2445 shell.inspector.set_active_scheme('NoColor')
2445 shell.inspector.set_active_scheme('NoColor')
2446
2446
2447 def magic_color_info(self,parameter_s = ''):
2447 def magic_color_info(self,parameter_s = ''):
2448 """Toggle color_info.
2448 """Toggle color_info.
2449
2449
2450 The color_info configuration parameter controls whether colors are
2450 The color_info configuration parameter controls whether colors are
2451 used for displaying object details (by things like %psource, %pfile or
2451 used for displaying object details (by things like %psource, %pfile or
2452 the '?' system). This function toggles this value with each call.
2452 the '?' system). This function toggles this value with each call.
2453
2453
2454 Note that unless you have a fairly recent pager (less works better
2454 Note that unless you have a fairly recent pager (less works better
2455 than more) in your system, using colored object information displays
2455 than more) in your system, using colored object information displays
2456 will not work properly. Test it and see."""
2456 will not work properly. Test it and see."""
2457
2457
2458 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2458 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2459 self.magic_colors(self.shell.rc.colors)
2459 self.magic_colors(self.shell.rc.colors)
2460 print 'Object introspection functions have now coloring:',
2460 print 'Object introspection functions have now coloring:',
2461 print ['OFF','ON'][self.shell.rc.color_info]
2461 print ['OFF','ON'][self.shell.rc.color_info]
2462
2462
2463 def magic_Pprint(self, parameter_s=''):
2463 def magic_Pprint(self, parameter_s=''):
2464 """Toggle pretty printing on/off."""
2464 """Toggle pretty printing on/off."""
2465
2465
2466 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2466 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2467 print 'Pretty printing has been turned', \
2467 print 'Pretty printing has been turned', \
2468 ['OFF','ON'][self.shell.rc.pprint]
2468 ['OFF','ON'][self.shell.rc.pprint]
2469
2469
2470 def magic_exit(self, parameter_s=''):
2470 def magic_exit(self, parameter_s=''):
2471 """Exit IPython, confirming if configured to do so.
2471 """Exit IPython, confirming if configured to do so.
2472
2472
2473 You can configure whether IPython asks for confirmation upon exit by
2473 You can configure whether IPython asks for confirmation upon exit by
2474 setting the confirm_exit flag in the ipythonrc file."""
2474 setting the confirm_exit flag in the ipythonrc file."""
2475
2475
2476 self.shell.exit()
2476 self.shell.exit()
2477
2477
2478 def magic_quit(self, parameter_s=''):
2478 def magic_quit(self, parameter_s=''):
2479 """Exit IPython, confirming if configured to do so (like %exit)"""
2479 """Exit IPython, confirming if configured to do so (like %exit)"""
2480
2480
2481 self.shell.exit()
2481 self.shell.exit()
2482
2482
2483 def magic_Exit(self, parameter_s=''):
2483 def magic_Exit(self, parameter_s=''):
2484 """Exit IPython without confirmation."""
2484 """Exit IPython without confirmation."""
2485
2485
2486 self.shell.exit_now = True
2486 self.shell.ask_exit()
2487
2487
2488 #......................................................................
2488 #......................................................................
2489 # Functions to implement unix shell-type things
2489 # Functions to implement unix shell-type things
2490
2490
2491 @testdec.skip_doctest
2491 @testdec.skip_doctest
2492 def magic_alias(self, parameter_s = ''):
2492 def magic_alias(self, parameter_s = ''):
2493 """Define an alias for a system command.
2493 """Define an alias for a system command.
2494
2494
2495 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2495 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2496
2496
2497 Then, typing 'alias_name params' will execute the system command 'cmd
2497 Then, typing 'alias_name params' will execute the system command 'cmd
2498 params' (from your underlying operating system).
2498 params' (from your underlying operating system).
2499
2499
2500 Aliases have lower precedence than magic functions and Python normal
2500 Aliases have lower precedence than magic functions and Python normal
2501 variables, so if 'foo' is both a Python variable and an alias, the
2501 variables, so if 'foo' is both a Python variable and an alias, the
2502 alias can not be executed until 'del foo' removes the Python variable.
2502 alias can not be executed until 'del foo' removes the Python variable.
2503
2503
2504 You can use the %l specifier in an alias definition to represent the
2504 You can use the %l specifier in an alias definition to represent the
2505 whole line when the alias is called. For example:
2505 whole line when the alias is called. For example:
2506
2506
2507 In [2]: alias all echo "Input in brackets: <%l>"
2507 In [2]: alias all echo "Input in brackets: <%l>"
2508 In [3]: all hello world
2508 In [3]: all hello world
2509 Input in brackets: <hello world>
2509 Input in brackets: <hello world>
2510
2510
2511 You can also define aliases with parameters using %s specifiers (one
2511 You can also define aliases with parameters using %s specifiers (one
2512 per parameter):
2512 per parameter):
2513
2513
2514 In [1]: alias parts echo first %s second %s
2514 In [1]: alias parts echo first %s second %s
2515 In [2]: %parts A B
2515 In [2]: %parts A B
2516 first A second B
2516 first A second B
2517 In [3]: %parts A
2517 In [3]: %parts A
2518 Incorrect number of arguments: 2 expected.
2518 Incorrect number of arguments: 2 expected.
2519 parts is an alias to: 'echo first %s second %s'
2519 parts is an alias to: 'echo first %s second %s'
2520
2520
2521 Note that %l and %s are mutually exclusive. You can only use one or
2521 Note that %l and %s are mutually exclusive. You can only use one or
2522 the other in your aliases.
2522 the other in your aliases.
2523
2523
2524 Aliases expand Python variables just like system calls using ! or !!
2524 Aliases expand Python variables just like system calls using ! or !!
2525 do: all expressions prefixed with '$' get expanded. For details of
2525 do: all expressions prefixed with '$' get expanded. For details of
2526 the semantic rules, see PEP-215:
2526 the semantic rules, see PEP-215:
2527 http://www.python.org/peps/pep-0215.html. This is the library used by
2527 http://www.python.org/peps/pep-0215.html. This is the library used by
2528 IPython for variable expansion. If you want to access a true shell
2528 IPython for variable expansion. If you want to access a true shell
2529 variable, an extra $ is necessary to prevent its expansion by IPython:
2529 variable, an extra $ is necessary to prevent its expansion by IPython:
2530
2530
2531 In [6]: alias show echo
2531 In [6]: alias show echo
2532 In [7]: PATH='A Python string'
2532 In [7]: PATH='A Python string'
2533 In [8]: show $PATH
2533 In [8]: show $PATH
2534 A Python string
2534 A Python string
2535 In [9]: show $$PATH
2535 In [9]: show $$PATH
2536 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2536 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2537
2537
2538 You can use the alias facility to acess all of $PATH. See the %rehash
2538 You can use the alias facility to acess all of $PATH. See the %rehash
2539 and %rehashx functions, which automatically create aliases for the
2539 and %rehashx functions, which automatically create aliases for the
2540 contents of your $PATH.
2540 contents of your $PATH.
2541
2541
2542 If called with no parameters, %alias prints the current alias table."""
2542 If called with no parameters, %alias prints the current alias table."""
2543
2543
2544 par = parameter_s.strip()
2544 par = parameter_s.strip()
2545 if not par:
2545 if not par:
2546 stored = self.db.get('stored_aliases', {} )
2546 stored = self.db.get('stored_aliases', {} )
2547 atab = self.shell.alias_table
2547 atab = self.shell.alias_table
2548 aliases = atab.keys()
2548 aliases = atab.keys()
2549 aliases.sort()
2549 aliases.sort()
2550 res = []
2550 res = []
2551 showlast = []
2551 showlast = []
2552 for alias in aliases:
2552 for alias in aliases:
2553 special = False
2553 special = False
2554 try:
2554 try:
2555 tgt = atab[alias][1]
2555 tgt = atab[alias][1]
2556 except (TypeError, AttributeError):
2556 except (TypeError, AttributeError):
2557 # unsubscriptable? probably a callable
2557 # unsubscriptable? probably a callable
2558 tgt = atab[alias]
2558 tgt = atab[alias]
2559 special = True
2559 special = True
2560 # 'interesting' aliases
2560 # 'interesting' aliases
2561 if (alias in stored or
2561 if (alias in stored or
2562 special or
2562 special or
2563 alias.lower() != os.path.splitext(tgt)[0].lower() or
2563 alias.lower() != os.path.splitext(tgt)[0].lower() or
2564 ' ' in tgt):
2564 ' ' in tgt):
2565 showlast.append((alias, tgt))
2565 showlast.append((alias, tgt))
2566 else:
2566 else:
2567 res.append((alias, tgt ))
2567 res.append((alias, tgt ))
2568
2568
2569 # show most interesting aliases last
2569 # show most interesting aliases last
2570 res.extend(showlast)
2570 res.extend(showlast)
2571 print "Total number of aliases:",len(aliases)
2571 print "Total number of aliases:",len(aliases)
2572 return res
2572 return res
2573 try:
2573 try:
2574 alias,cmd = par.split(None,1)
2574 alias,cmd = par.split(None,1)
2575 except:
2575 except:
2576 print OInspect.getdoc(self.magic_alias)
2576 print OInspect.getdoc(self.magic_alias)
2577 else:
2577 else:
2578 nargs = cmd.count('%s')
2578 nargs = cmd.count('%s')
2579 if nargs>0 and cmd.find('%l')>=0:
2579 if nargs>0 and cmd.find('%l')>=0:
2580 error('The %s and %l specifiers are mutually exclusive '
2580 error('The %s and %l specifiers are mutually exclusive '
2581 'in alias definitions.')
2581 'in alias definitions.')
2582 else: # all looks OK
2582 else: # all looks OK
2583 self.shell.alias_table[alias] = (nargs,cmd)
2583 self.shell.alias_table[alias] = (nargs,cmd)
2584 self.shell.alias_table_validate(verbose=0)
2584 self.shell.alias_table_validate(verbose=0)
2585 # end magic_alias
2585 # end magic_alias
2586
2586
2587 def magic_unalias(self, parameter_s = ''):
2587 def magic_unalias(self, parameter_s = ''):
2588 """Remove an alias"""
2588 """Remove an alias"""
2589
2589
2590 aname = parameter_s.strip()
2590 aname = parameter_s.strip()
2591 if aname in self.shell.alias_table:
2591 if aname in self.shell.alias_table:
2592 del self.shell.alias_table[aname]
2592 del self.shell.alias_table[aname]
2593 stored = self.db.get('stored_aliases', {} )
2593 stored = self.db.get('stored_aliases', {} )
2594 if aname in stored:
2594 if aname in stored:
2595 print "Removing %stored alias",aname
2595 print "Removing %stored alias",aname
2596 del stored[aname]
2596 del stored[aname]
2597 self.db['stored_aliases'] = stored
2597 self.db['stored_aliases'] = stored
2598
2598
2599
2599
2600 def magic_rehashx(self, parameter_s = ''):
2600 def magic_rehashx(self, parameter_s = ''):
2601 """Update the alias table with all executable files in $PATH.
2601 """Update the alias table with all executable files in $PATH.
2602
2602
2603 This version explicitly checks that every entry in $PATH is a file
2603 This version explicitly checks that every entry in $PATH is a file
2604 with execute access (os.X_OK), so it is much slower than %rehash.
2604 with execute access (os.X_OK), so it is much slower than %rehash.
2605
2605
2606 Under Windows, it checks executability as a match agains a
2606 Under Windows, it checks executability as a match agains a
2607 '|'-separated string of extensions, stored in the IPython config
2607 '|'-separated string of extensions, stored in the IPython config
2608 variable win_exec_ext. This defaults to 'exe|com|bat'.
2608 variable win_exec_ext. This defaults to 'exe|com|bat'.
2609
2609
2610 This function also resets the root module cache of module completer,
2610 This function also resets the root module cache of module completer,
2611 used on slow filesystems.
2611 used on slow filesystems.
2612 """
2612 """
2613
2613
2614
2614
2615 ip = self.api
2615 ip = self.api
2616
2616
2617 # for the benefit of module completer in ipy_completers.py
2617 # for the benefit of module completer in ipy_completers.py
2618 del ip.db['rootmodules']
2618 del ip.db['rootmodules']
2619
2619
2620 path = [os.path.abspath(os.path.expanduser(p)) for p in
2620 path = [os.path.abspath(os.path.expanduser(p)) for p in
2621 os.environ.get('PATH','').split(os.pathsep)]
2621 os.environ.get('PATH','').split(os.pathsep)]
2622 path = filter(os.path.isdir,path)
2622 path = filter(os.path.isdir,path)
2623
2623
2624 alias_table = self.shell.alias_table
2624 alias_table = self.shell.alias_table
2625 syscmdlist = []
2625 syscmdlist = []
2626 if os.name == 'posix':
2626 if os.name == 'posix':
2627 isexec = lambda fname:os.path.isfile(fname) and \
2627 isexec = lambda fname:os.path.isfile(fname) and \
2628 os.access(fname,os.X_OK)
2628 os.access(fname,os.X_OK)
2629 else:
2629 else:
2630
2630
2631 try:
2631 try:
2632 winext = os.environ['pathext'].replace(';','|').replace('.','')
2632 winext = os.environ['pathext'].replace(';','|').replace('.','')
2633 except KeyError:
2633 except KeyError:
2634 winext = 'exe|com|bat|py'
2634 winext = 'exe|com|bat|py'
2635 if 'py' not in winext:
2635 if 'py' not in winext:
2636 winext += '|py'
2636 winext += '|py'
2637 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2637 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2638 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2638 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2639 savedir = os.getcwd()
2639 savedir = os.getcwd()
2640 try:
2640 try:
2641 # write the whole loop for posix/Windows so we don't have an if in
2641 # write the whole loop for posix/Windows so we don't have an if in
2642 # the innermost part
2642 # the innermost part
2643 if os.name == 'posix':
2643 if os.name == 'posix':
2644 for pdir in path:
2644 for pdir in path:
2645 os.chdir(pdir)
2645 os.chdir(pdir)
2646 for ff in os.listdir(pdir):
2646 for ff in os.listdir(pdir):
2647 if isexec(ff) and ff not in self.shell.no_alias:
2647 if isexec(ff) and ff not in self.shell.no_alias:
2648 # each entry in the alias table must be (N,name),
2648 # each entry in the alias table must be (N,name),
2649 # where N is the number of positional arguments of the
2649 # where N is the number of positional arguments of the
2650 # alias.
2650 # alias.
2651 alias_table[ff] = (0,ff)
2651 alias_table[ff] = (0,ff)
2652 syscmdlist.append(ff)
2652 syscmdlist.append(ff)
2653 else:
2653 else:
2654 for pdir in path:
2654 for pdir in path:
2655 os.chdir(pdir)
2655 os.chdir(pdir)
2656 for ff in os.listdir(pdir):
2656 for ff in os.listdir(pdir):
2657 base, ext = os.path.splitext(ff)
2657 base, ext = os.path.splitext(ff)
2658 if isexec(ff) and base.lower() not in self.shell.no_alias:
2658 if isexec(ff) and base.lower() not in self.shell.no_alias:
2659 if ext.lower() == '.exe':
2659 if ext.lower() == '.exe':
2660 ff = base
2660 ff = base
2661 alias_table[base.lower()] = (0,ff)
2661 alias_table[base.lower()] = (0,ff)
2662 syscmdlist.append(ff)
2662 syscmdlist.append(ff)
2663 # Make sure the alias table doesn't contain keywords or builtins
2663 # Make sure the alias table doesn't contain keywords or builtins
2664 self.shell.alias_table_validate()
2664 self.shell.alias_table_validate()
2665 # Call again init_auto_alias() so we get 'rm -i' and other
2665 # Call again init_auto_alias() so we get 'rm -i' and other
2666 # modified aliases since %rehashx will probably clobber them
2666 # modified aliases since %rehashx will probably clobber them
2667
2667
2668 # no, we don't want them. if %rehashx clobbers them, good,
2668 # no, we don't want them. if %rehashx clobbers them, good,
2669 # we'll probably get better versions
2669 # we'll probably get better versions
2670 # self.shell.init_auto_alias()
2670 # self.shell.init_auto_alias()
2671 db = ip.db
2671 db = ip.db
2672 db['syscmdlist'] = syscmdlist
2672 db['syscmdlist'] = syscmdlist
2673 finally:
2673 finally:
2674 os.chdir(savedir)
2674 os.chdir(savedir)
2675
2675
2676 def magic_pwd(self, parameter_s = ''):
2676 def magic_pwd(self, parameter_s = ''):
2677 """Return the current working directory path."""
2677 """Return the current working directory path."""
2678 return os.getcwd()
2678 return os.getcwd()
2679
2679
2680 def magic_cd(self, parameter_s=''):
2680 def magic_cd(self, parameter_s=''):
2681 """Change the current working directory.
2681 """Change the current working directory.
2682
2682
2683 This command automatically maintains an internal list of directories
2683 This command automatically maintains an internal list of directories
2684 you visit during your IPython session, in the variable _dh. The
2684 you visit during your IPython session, in the variable _dh. The
2685 command %dhist shows this history nicely formatted. You can also
2685 command %dhist shows this history nicely formatted. You can also
2686 do 'cd -<tab>' to see directory history conveniently.
2686 do 'cd -<tab>' to see directory history conveniently.
2687
2687
2688 Usage:
2688 Usage:
2689
2689
2690 cd 'dir': changes to directory 'dir'.
2690 cd 'dir': changes to directory 'dir'.
2691
2691
2692 cd -: changes to the last visited directory.
2692 cd -: changes to the last visited directory.
2693
2693
2694 cd -<n>: changes to the n-th directory in the directory history.
2694 cd -<n>: changes to the n-th directory in the directory history.
2695
2695
2696 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2696 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2697 (note: cd <bookmark_name> is enough if there is no
2697 (note: cd <bookmark_name> is enough if there is no
2698 directory <bookmark_name>, but a bookmark with the name exists.)
2698 directory <bookmark_name>, but a bookmark with the name exists.)
2699 'cd -b <tab>' allows you to tab-complete bookmark names.
2699 'cd -b <tab>' allows you to tab-complete bookmark names.
2700
2700
2701 Options:
2701 Options:
2702
2702
2703 -q: quiet. Do not print the working directory after the cd command is
2703 -q: quiet. Do not print the working directory after the cd command is
2704 executed. By default IPython's cd command does print this directory,
2704 executed. By default IPython's cd command does print this directory,
2705 since the default prompts do not display path information.
2705 since the default prompts do not display path information.
2706
2706
2707 Note that !cd doesn't work for this purpose because the shell where
2707 Note that !cd doesn't work for this purpose because the shell where
2708 !command runs is immediately discarded after executing 'command'."""
2708 !command runs is immediately discarded after executing 'command'."""
2709
2709
2710 parameter_s = parameter_s.strip()
2710 parameter_s = parameter_s.strip()
2711 #bkms = self.shell.persist.get("bookmarks",{})
2711 #bkms = self.shell.persist.get("bookmarks",{})
2712
2712
2713 oldcwd = os.getcwd()
2713 oldcwd = os.getcwd()
2714 numcd = re.match(r'(-)(\d+)$',parameter_s)
2714 numcd = re.match(r'(-)(\d+)$',parameter_s)
2715 # jump in directory history by number
2715 # jump in directory history by number
2716 if numcd:
2716 if numcd:
2717 nn = int(numcd.group(2))
2717 nn = int(numcd.group(2))
2718 try:
2718 try:
2719 ps = self.shell.user_ns['_dh'][nn]
2719 ps = self.shell.user_ns['_dh'][nn]
2720 except IndexError:
2720 except IndexError:
2721 print 'The requested directory does not exist in history.'
2721 print 'The requested directory does not exist in history.'
2722 return
2722 return
2723 else:
2723 else:
2724 opts = {}
2724 opts = {}
2725 else:
2725 else:
2726 #turn all non-space-escaping backslashes to slashes,
2726 #turn all non-space-escaping backslashes to slashes,
2727 # for c:\windows\directory\names\
2727 # for c:\windows\directory\names\
2728 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2728 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2729 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2729 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2730 # jump to previous
2730 # jump to previous
2731 if ps == '-':
2731 if ps == '-':
2732 try:
2732 try:
2733 ps = self.shell.user_ns['_dh'][-2]
2733 ps = self.shell.user_ns['_dh'][-2]
2734 except IndexError:
2734 except IndexError:
2735 raise UsageError('%cd -: No previous directory to change to.')
2735 raise UsageError('%cd -: No previous directory to change to.')
2736 # jump to bookmark if needed
2736 # jump to bookmark if needed
2737 else:
2737 else:
2738 if not os.path.isdir(ps) or opts.has_key('b'):
2738 if not os.path.isdir(ps) or opts.has_key('b'):
2739 bkms = self.db.get('bookmarks', {})
2739 bkms = self.db.get('bookmarks', {})
2740
2740
2741 if bkms.has_key(ps):
2741 if bkms.has_key(ps):
2742 target = bkms[ps]
2742 target = bkms[ps]
2743 print '(bookmark:%s) -> %s' % (ps,target)
2743 print '(bookmark:%s) -> %s' % (ps,target)
2744 ps = target
2744 ps = target
2745 else:
2745 else:
2746 if opts.has_key('b'):
2746 if opts.has_key('b'):
2747 raise UsageError("Bookmark '%s' not found. "
2747 raise UsageError("Bookmark '%s' not found. "
2748 "Use '%%bookmark -l' to see your bookmarks." % ps)
2748 "Use '%%bookmark -l' to see your bookmarks." % ps)
2749
2749
2750 # at this point ps should point to the target dir
2750 # at this point ps should point to the target dir
2751 if ps:
2751 if ps:
2752 try:
2752 try:
2753 os.chdir(os.path.expanduser(ps))
2753 os.chdir(os.path.expanduser(ps))
2754 if self.shell.rc.term_title:
2754 if self.shell.rc.term_title:
2755 #print 'set term title:',self.shell.rc.term_title # dbg
2755 #print 'set term title:',self.shell.rc.term_title # dbg
2756 platutils.set_term_title('IPy ' + abbrev_cwd())
2756 platutils.set_term_title('IPy ' + abbrev_cwd())
2757 except OSError:
2757 except OSError:
2758 print sys.exc_info()[1]
2758 print sys.exc_info()[1]
2759 else:
2759 else:
2760 cwd = os.getcwd()
2760 cwd = os.getcwd()
2761 dhist = self.shell.user_ns['_dh']
2761 dhist = self.shell.user_ns['_dh']
2762 if oldcwd != cwd:
2762 if oldcwd != cwd:
2763 dhist.append(cwd)
2763 dhist.append(cwd)
2764 self.db['dhist'] = compress_dhist(dhist)[-100:]
2764 self.db['dhist'] = compress_dhist(dhist)[-100:]
2765
2765
2766 else:
2766 else:
2767 os.chdir(self.shell.home_dir)
2767 os.chdir(self.shell.home_dir)
2768 if self.shell.rc.term_title:
2768 if self.shell.rc.term_title:
2769 platutils.set_term_title("IPy ~")
2769 platutils.set_term_title("IPy ~")
2770 cwd = os.getcwd()
2770 cwd = os.getcwd()
2771 dhist = self.shell.user_ns['_dh']
2771 dhist = self.shell.user_ns['_dh']
2772
2772
2773 if oldcwd != cwd:
2773 if oldcwd != cwd:
2774 dhist.append(cwd)
2774 dhist.append(cwd)
2775 self.db['dhist'] = compress_dhist(dhist)[-100:]
2775 self.db['dhist'] = compress_dhist(dhist)[-100:]
2776 if not 'q' in opts and self.shell.user_ns['_dh']:
2776 if not 'q' in opts and self.shell.user_ns['_dh']:
2777 print self.shell.user_ns['_dh'][-1]
2777 print self.shell.user_ns['_dh'][-1]
2778
2778
2779
2779
2780 def magic_env(self, parameter_s=''):
2780 def magic_env(self, parameter_s=''):
2781 """List environment variables."""
2781 """List environment variables."""
2782
2782
2783 return os.environ.data
2783 return os.environ.data
2784
2784
2785 def magic_pushd(self, parameter_s=''):
2785 def magic_pushd(self, parameter_s=''):
2786 """Place the current dir on stack and change directory.
2786 """Place the current dir on stack and change directory.
2787
2787
2788 Usage:\\
2788 Usage:\\
2789 %pushd ['dirname']
2789 %pushd ['dirname']
2790 """
2790 """
2791
2791
2792 dir_s = self.shell.dir_stack
2792 dir_s = self.shell.dir_stack
2793 tgt = os.path.expanduser(parameter_s)
2793 tgt = os.path.expanduser(parameter_s)
2794 cwd = os.getcwd().replace(self.home_dir,'~')
2794 cwd = os.getcwd().replace(self.home_dir,'~')
2795 if tgt:
2795 if tgt:
2796 self.magic_cd(parameter_s)
2796 self.magic_cd(parameter_s)
2797 dir_s.insert(0,cwd)
2797 dir_s.insert(0,cwd)
2798 return self.magic_dirs()
2798 return self.magic_dirs()
2799
2799
2800 def magic_popd(self, parameter_s=''):
2800 def magic_popd(self, parameter_s=''):
2801 """Change to directory popped off the top of the stack.
2801 """Change to directory popped off the top of the stack.
2802 """
2802 """
2803 if not self.shell.dir_stack:
2803 if not self.shell.dir_stack:
2804 raise UsageError("%popd on empty stack")
2804 raise UsageError("%popd on empty stack")
2805 top = self.shell.dir_stack.pop(0)
2805 top = self.shell.dir_stack.pop(0)
2806 self.magic_cd(top)
2806 self.magic_cd(top)
2807 print "popd ->",top
2807 print "popd ->",top
2808
2808
2809 def magic_dirs(self, parameter_s=''):
2809 def magic_dirs(self, parameter_s=''):
2810 """Return the current directory stack."""
2810 """Return the current directory stack."""
2811
2811
2812 return self.shell.dir_stack
2812 return self.shell.dir_stack
2813
2813
2814 def magic_dhist(self, parameter_s=''):
2814 def magic_dhist(self, parameter_s=''):
2815 """Print your history of visited directories.
2815 """Print your history of visited directories.
2816
2816
2817 %dhist -> print full history\\
2817 %dhist -> print full history\\
2818 %dhist n -> print last n entries only\\
2818 %dhist n -> print last n entries only\\
2819 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2819 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2820
2820
2821 This history is automatically maintained by the %cd command, and
2821 This history is automatically maintained by the %cd command, and
2822 always available as the global list variable _dh. You can use %cd -<n>
2822 always available as the global list variable _dh. You can use %cd -<n>
2823 to go to directory number <n>.
2823 to go to directory number <n>.
2824
2824
2825 Note that most of time, you should view directory history by entering
2825 Note that most of time, you should view directory history by entering
2826 cd -<TAB>.
2826 cd -<TAB>.
2827
2827
2828 """
2828 """
2829
2829
2830 dh = self.shell.user_ns['_dh']
2830 dh = self.shell.user_ns['_dh']
2831 if parameter_s:
2831 if parameter_s:
2832 try:
2832 try:
2833 args = map(int,parameter_s.split())
2833 args = map(int,parameter_s.split())
2834 except:
2834 except:
2835 self.arg_err(Magic.magic_dhist)
2835 self.arg_err(Magic.magic_dhist)
2836 return
2836 return
2837 if len(args) == 1:
2837 if len(args) == 1:
2838 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2838 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2839 elif len(args) == 2:
2839 elif len(args) == 2:
2840 ini,fin = args
2840 ini,fin = args
2841 else:
2841 else:
2842 self.arg_err(Magic.magic_dhist)
2842 self.arg_err(Magic.magic_dhist)
2843 return
2843 return
2844 else:
2844 else:
2845 ini,fin = 0,len(dh)
2845 ini,fin = 0,len(dh)
2846 nlprint(dh,
2846 nlprint(dh,
2847 header = 'Directory history (kept in _dh)',
2847 header = 'Directory history (kept in _dh)',
2848 start=ini,stop=fin)
2848 start=ini,stop=fin)
2849
2849
2850 @testdec.skip_doctest
2850 @testdec.skip_doctest
2851 def magic_sc(self, parameter_s=''):
2851 def magic_sc(self, parameter_s=''):
2852 """Shell capture - execute a shell command and capture its output.
2852 """Shell capture - execute a shell command and capture its output.
2853
2853
2854 DEPRECATED. Suboptimal, retained for backwards compatibility.
2854 DEPRECATED. Suboptimal, retained for backwards compatibility.
2855
2855
2856 You should use the form 'var = !command' instead. Example:
2856 You should use the form 'var = !command' instead. Example:
2857
2857
2858 "%sc -l myfiles = ls ~" should now be written as
2858 "%sc -l myfiles = ls ~" should now be written as
2859
2859
2860 "myfiles = !ls ~"
2860 "myfiles = !ls ~"
2861
2861
2862 myfiles.s, myfiles.l and myfiles.n still apply as documented
2862 myfiles.s, myfiles.l and myfiles.n still apply as documented
2863 below.
2863 below.
2864
2864
2865 --
2865 --
2866 %sc [options] varname=command
2866 %sc [options] varname=command
2867
2867
2868 IPython will run the given command using commands.getoutput(), and
2868 IPython will run the given command using commands.getoutput(), and
2869 will then update the user's interactive namespace with a variable
2869 will then update the user's interactive namespace with a variable
2870 called varname, containing the value of the call. Your command can
2870 called varname, containing the value of the call. Your command can
2871 contain shell wildcards, pipes, etc.
2871 contain shell wildcards, pipes, etc.
2872
2872
2873 The '=' sign in the syntax is mandatory, and the variable name you
2873 The '=' sign in the syntax is mandatory, and the variable name you
2874 supply must follow Python's standard conventions for valid names.
2874 supply must follow Python's standard conventions for valid names.
2875
2875
2876 (A special format without variable name exists for internal use)
2876 (A special format without variable name exists for internal use)
2877
2877
2878 Options:
2878 Options:
2879
2879
2880 -l: list output. Split the output on newlines into a list before
2880 -l: list output. Split the output on newlines into a list before
2881 assigning it to the given variable. By default the output is stored
2881 assigning it to the given variable. By default the output is stored
2882 as a single string.
2882 as a single string.
2883
2883
2884 -v: verbose. Print the contents of the variable.
2884 -v: verbose. Print the contents of the variable.
2885
2885
2886 In most cases you should not need to split as a list, because the
2886 In most cases you should not need to split as a list, because the
2887 returned value is a special type of string which can automatically
2887 returned value is a special type of string which can automatically
2888 provide its contents either as a list (split on newlines) or as a
2888 provide its contents either as a list (split on newlines) or as a
2889 space-separated string. These are convenient, respectively, either
2889 space-separated string. These are convenient, respectively, either
2890 for sequential processing or to be passed to a shell command.
2890 for sequential processing or to be passed to a shell command.
2891
2891
2892 For example:
2892 For example:
2893
2893
2894 # all-random
2894 # all-random
2895
2895
2896 # Capture into variable a
2896 # Capture into variable a
2897 In [1]: sc a=ls *py
2897 In [1]: sc a=ls *py
2898
2898
2899 # a is a string with embedded newlines
2899 # a is a string with embedded newlines
2900 In [2]: a
2900 In [2]: a
2901 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2901 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2902
2902
2903 # which can be seen as a list:
2903 # which can be seen as a list:
2904 In [3]: a.l
2904 In [3]: a.l
2905 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2905 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2906
2906
2907 # or as a whitespace-separated string:
2907 # or as a whitespace-separated string:
2908 In [4]: a.s
2908 In [4]: a.s
2909 Out[4]: 'setup.py win32_manual_post_install.py'
2909 Out[4]: 'setup.py win32_manual_post_install.py'
2910
2910
2911 # a.s is useful to pass as a single command line:
2911 # a.s is useful to pass as a single command line:
2912 In [5]: !wc -l $a.s
2912 In [5]: !wc -l $a.s
2913 146 setup.py
2913 146 setup.py
2914 130 win32_manual_post_install.py
2914 130 win32_manual_post_install.py
2915 276 total
2915 276 total
2916
2916
2917 # while the list form is useful to loop over:
2917 # while the list form is useful to loop over:
2918 In [6]: for f in a.l:
2918 In [6]: for f in a.l:
2919 ...: !wc -l $f
2919 ...: !wc -l $f
2920 ...:
2920 ...:
2921 146 setup.py
2921 146 setup.py
2922 130 win32_manual_post_install.py
2922 130 win32_manual_post_install.py
2923
2923
2924 Similiarly, the lists returned by the -l option are also special, in
2924 Similiarly, the lists returned by the -l option are also special, in
2925 the sense that you can equally invoke the .s attribute on them to
2925 the sense that you can equally invoke the .s attribute on them to
2926 automatically get a whitespace-separated string from their contents:
2926 automatically get a whitespace-separated string from their contents:
2927
2927
2928 In [7]: sc -l b=ls *py
2928 In [7]: sc -l b=ls *py
2929
2929
2930 In [8]: b
2930 In [8]: b
2931 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2931 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2932
2932
2933 In [9]: b.s
2933 In [9]: b.s
2934 Out[9]: 'setup.py win32_manual_post_install.py'
2934 Out[9]: 'setup.py win32_manual_post_install.py'
2935
2935
2936 In summary, both the lists and strings used for ouptut capture have
2936 In summary, both the lists and strings used for ouptut capture have
2937 the following special attributes:
2937 the following special attributes:
2938
2938
2939 .l (or .list) : value as list.
2939 .l (or .list) : value as list.
2940 .n (or .nlstr): value as newline-separated string.
2940 .n (or .nlstr): value as newline-separated string.
2941 .s (or .spstr): value as space-separated string.
2941 .s (or .spstr): value as space-separated string.
2942 """
2942 """
2943
2943
2944 opts,args = self.parse_options(parameter_s,'lv')
2944 opts,args = self.parse_options(parameter_s,'lv')
2945 # Try to get a variable name and command to run
2945 # Try to get a variable name and command to run
2946 try:
2946 try:
2947 # the variable name must be obtained from the parse_options
2947 # the variable name must be obtained from the parse_options
2948 # output, which uses shlex.split to strip options out.
2948 # output, which uses shlex.split to strip options out.
2949 var,_ = args.split('=',1)
2949 var,_ = args.split('=',1)
2950 var = var.strip()
2950 var = var.strip()
2951 # But the the command has to be extracted from the original input
2951 # But the the command has to be extracted from the original input
2952 # parameter_s, not on what parse_options returns, to avoid the
2952 # parameter_s, not on what parse_options returns, to avoid the
2953 # quote stripping which shlex.split performs on it.
2953 # quote stripping which shlex.split performs on it.
2954 _,cmd = parameter_s.split('=',1)
2954 _,cmd = parameter_s.split('=',1)
2955 except ValueError:
2955 except ValueError:
2956 var,cmd = '',''
2956 var,cmd = '',''
2957 # If all looks ok, proceed
2957 # If all looks ok, proceed
2958 out,err = self.shell.getoutputerror(cmd)
2958 out,err = self.shell.getoutputerror(cmd)
2959 if err:
2959 if err:
2960 print >> Term.cerr,err
2960 print >> Term.cerr,err
2961 if opts.has_key('l'):
2961 if opts.has_key('l'):
2962 out = SList(out.split('\n'))
2962 out = SList(out.split('\n'))
2963 else:
2963 else:
2964 out = LSString(out)
2964 out = LSString(out)
2965 if opts.has_key('v'):
2965 if opts.has_key('v'):
2966 print '%s ==\n%s' % (var,pformat(out))
2966 print '%s ==\n%s' % (var,pformat(out))
2967 if var:
2967 if var:
2968 self.shell.user_ns.update({var:out})
2968 self.shell.user_ns.update({var:out})
2969 else:
2969 else:
2970 return out
2970 return out
2971
2971
2972 def magic_sx(self, parameter_s=''):
2972 def magic_sx(self, parameter_s=''):
2973 """Shell execute - run a shell command and capture its output.
2973 """Shell execute - run a shell command and capture its output.
2974
2974
2975 %sx command
2975 %sx command
2976
2976
2977 IPython will run the given command using commands.getoutput(), and
2977 IPython will run the given command using commands.getoutput(), and
2978 return the result formatted as a list (split on '\\n'). Since the
2978 return the result formatted as a list (split on '\\n'). Since the
2979 output is _returned_, it will be stored in ipython's regular output
2979 output is _returned_, it will be stored in ipython's regular output
2980 cache Out[N] and in the '_N' automatic variables.
2980 cache Out[N] and in the '_N' automatic variables.
2981
2981
2982 Notes:
2982 Notes:
2983
2983
2984 1) If an input line begins with '!!', then %sx is automatically
2984 1) If an input line begins with '!!', then %sx is automatically
2985 invoked. That is, while:
2985 invoked. That is, while:
2986 !ls
2986 !ls
2987 causes ipython to simply issue system('ls'), typing
2987 causes ipython to simply issue system('ls'), typing
2988 !!ls
2988 !!ls
2989 is a shorthand equivalent to:
2989 is a shorthand equivalent to:
2990 %sx ls
2990 %sx ls
2991
2991
2992 2) %sx differs from %sc in that %sx automatically splits into a list,
2992 2) %sx differs from %sc in that %sx automatically splits into a list,
2993 like '%sc -l'. The reason for this is to make it as easy as possible
2993 like '%sc -l'. The reason for this is to make it as easy as possible
2994 to process line-oriented shell output via further python commands.
2994 to process line-oriented shell output via further python commands.
2995 %sc is meant to provide much finer control, but requires more
2995 %sc is meant to provide much finer control, but requires more
2996 typing.
2996 typing.
2997
2997
2998 3) Just like %sc -l, this is a list with special attributes:
2998 3) Just like %sc -l, this is a list with special attributes:
2999
2999
3000 .l (or .list) : value as list.
3000 .l (or .list) : value as list.
3001 .n (or .nlstr): value as newline-separated string.
3001 .n (or .nlstr): value as newline-separated string.
3002 .s (or .spstr): value as whitespace-separated string.
3002 .s (or .spstr): value as whitespace-separated string.
3003
3003
3004 This is very useful when trying to use such lists as arguments to
3004 This is very useful when trying to use such lists as arguments to
3005 system commands."""
3005 system commands."""
3006
3006
3007 if parameter_s:
3007 if parameter_s:
3008 out,err = self.shell.getoutputerror(parameter_s)
3008 out,err = self.shell.getoutputerror(parameter_s)
3009 if err:
3009 if err:
3010 print >> Term.cerr,err
3010 print >> Term.cerr,err
3011 return SList(out.split('\n'))
3011 return SList(out.split('\n'))
3012
3012
3013 def magic_bg(self, parameter_s=''):
3013 def magic_bg(self, parameter_s=''):
3014 """Run a job in the background, in a separate thread.
3014 """Run a job in the background, in a separate thread.
3015
3015
3016 For example,
3016 For example,
3017
3017
3018 %bg myfunc(x,y,z=1)
3018 %bg myfunc(x,y,z=1)
3019
3019
3020 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3020 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3021 execution starts, a message will be printed indicating the job
3021 execution starts, a message will be printed indicating the job
3022 number. If your job number is 5, you can use
3022 number. If your job number is 5, you can use
3023
3023
3024 myvar = jobs.result(5) or myvar = jobs[5].result
3024 myvar = jobs.result(5) or myvar = jobs[5].result
3025
3025
3026 to assign this result to variable 'myvar'.
3026 to assign this result to variable 'myvar'.
3027
3027
3028 IPython has a job manager, accessible via the 'jobs' object. You can
3028 IPython has a job manager, accessible via the 'jobs' object. You can
3029 type jobs? to get more information about it, and use jobs.<TAB> to see
3029 type jobs? to get more information about it, and use jobs.<TAB> to see
3030 its attributes. All attributes not starting with an underscore are
3030 its attributes. All attributes not starting with an underscore are
3031 meant for public use.
3031 meant for public use.
3032
3032
3033 In particular, look at the jobs.new() method, which is used to create
3033 In particular, look at the jobs.new() method, which is used to create
3034 new jobs. This magic %bg function is just a convenience wrapper
3034 new jobs. This magic %bg function is just a convenience wrapper
3035 around jobs.new(), for expression-based jobs. If you want to create a
3035 around jobs.new(), for expression-based jobs. If you want to create a
3036 new job with an explicit function object and arguments, you must call
3036 new job with an explicit function object and arguments, you must call
3037 jobs.new() directly.
3037 jobs.new() directly.
3038
3038
3039 The jobs.new docstring also describes in detail several important
3039 The jobs.new docstring also describes in detail several important
3040 caveats associated with a thread-based model for background job
3040 caveats associated with a thread-based model for background job
3041 execution. Type jobs.new? for details.
3041 execution. Type jobs.new? for details.
3042
3042
3043 You can check the status of all jobs with jobs.status().
3043 You can check the status of all jobs with jobs.status().
3044
3044
3045 The jobs variable is set by IPython into the Python builtin namespace.
3045 The jobs variable is set by IPython into the Python builtin namespace.
3046 If you ever declare a variable named 'jobs', you will shadow this
3046 If you ever declare a variable named 'jobs', you will shadow this
3047 name. You can either delete your global jobs variable to regain
3047 name. You can either delete your global jobs variable to regain
3048 access to the job manager, or make a new name and assign it manually
3048 access to the job manager, or make a new name and assign it manually
3049 to the manager (stored in IPython's namespace). For example, to
3049 to the manager (stored in IPython's namespace). For example, to
3050 assign the job manager to the Jobs name, use:
3050 assign the job manager to the Jobs name, use:
3051
3051
3052 Jobs = __builtins__.jobs"""
3052 Jobs = __builtins__.jobs"""
3053
3053
3054 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3054 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3055
3055
3056 def magic_r(self, parameter_s=''):
3056 def magic_r(self, parameter_s=''):
3057 """Repeat previous input.
3057 """Repeat previous input.
3058
3058
3059 Note: Consider using the more powerfull %rep instead!
3059 Note: Consider using the more powerfull %rep instead!
3060
3060
3061 If given an argument, repeats the previous command which starts with
3061 If given an argument, repeats the previous command which starts with
3062 the same string, otherwise it just repeats the previous input.
3062 the same string, otherwise it just repeats the previous input.
3063
3063
3064 Shell escaped commands (with ! as first character) are not recognized
3064 Shell escaped commands (with ! as first character) are not recognized
3065 by this system, only pure python code and magic commands.
3065 by this system, only pure python code and magic commands.
3066 """
3066 """
3067
3067
3068 start = parameter_s.strip()
3068 start = parameter_s.strip()
3069 esc_magic = self.shell.ESC_MAGIC
3069 esc_magic = self.shell.ESC_MAGIC
3070 # Identify magic commands even if automagic is on (which means
3070 # Identify magic commands even if automagic is on (which means
3071 # the in-memory version is different from that typed by the user).
3071 # the in-memory version is different from that typed by the user).
3072 if self.shell.rc.automagic:
3072 if self.shell.rc.automagic:
3073 start_magic = esc_magic+start
3073 start_magic = esc_magic+start
3074 else:
3074 else:
3075 start_magic = start
3075 start_magic = start
3076 # Look through the input history in reverse
3076 # Look through the input history in reverse
3077 for n in range(len(self.shell.input_hist)-2,0,-1):
3077 for n in range(len(self.shell.input_hist)-2,0,-1):
3078 input = self.shell.input_hist[n]
3078 input = self.shell.input_hist[n]
3079 # skip plain 'r' lines so we don't recurse to infinity
3079 # skip plain 'r' lines so we don't recurse to infinity
3080 if input != '_ip.magic("r")\n' and \
3080 if input != '_ip.magic("r")\n' and \
3081 (input.startswith(start) or input.startswith(start_magic)):
3081 (input.startswith(start) or input.startswith(start_magic)):
3082 #print 'match',`input` # dbg
3082 #print 'match',`input` # dbg
3083 print 'Executing:',input,
3083 print 'Executing:',input,
3084 self.shell.runlines(input)
3084 self.shell.runlines(input)
3085 return
3085 return
3086 print 'No previous input matching `%s` found.' % start
3086 print 'No previous input matching `%s` found.' % start
3087
3087
3088
3088
3089 def magic_bookmark(self, parameter_s=''):
3089 def magic_bookmark(self, parameter_s=''):
3090 """Manage IPython's bookmark system.
3090 """Manage IPython's bookmark system.
3091
3091
3092 %bookmark <name> - set bookmark to current dir
3092 %bookmark <name> - set bookmark to current dir
3093 %bookmark <name> <dir> - set bookmark to <dir>
3093 %bookmark <name> <dir> - set bookmark to <dir>
3094 %bookmark -l - list all bookmarks
3094 %bookmark -l - list all bookmarks
3095 %bookmark -d <name> - remove bookmark
3095 %bookmark -d <name> - remove bookmark
3096 %bookmark -r - remove all bookmarks
3096 %bookmark -r - remove all bookmarks
3097
3097
3098 You can later on access a bookmarked folder with:
3098 You can later on access a bookmarked folder with:
3099 %cd -b <name>
3099 %cd -b <name>
3100 or simply '%cd <name>' if there is no directory called <name> AND
3100 or simply '%cd <name>' if there is no directory called <name> AND
3101 there is such a bookmark defined.
3101 there is such a bookmark defined.
3102
3102
3103 Your bookmarks persist through IPython sessions, but they are
3103 Your bookmarks persist through IPython sessions, but they are
3104 associated with each profile."""
3104 associated with each profile."""
3105
3105
3106 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3106 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3107 if len(args) > 2:
3107 if len(args) > 2:
3108 raise UsageError("%bookmark: too many arguments")
3108 raise UsageError("%bookmark: too many arguments")
3109
3109
3110 bkms = self.db.get('bookmarks',{})
3110 bkms = self.db.get('bookmarks',{})
3111
3111
3112 if opts.has_key('d'):
3112 if opts.has_key('d'):
3113 try:
3113 try:
3114 todel = args[0]
3114 todel = args[0]
3115 except IndexError:
3115 except IndexError:
3116 raise UsageError(
3116 raise UsageError(
3117 "%bookmark -d: must provide a bookmark to delete")
3117 "%bookmark -d: must provide a bookmark to delete")
3118 else:
3118 else:
3119 try:
3119 try:
3120 del bkms[todel]
3120 del bkms[todel]
3121 except KeyError:
3121 except KeyError:
3122 raise UsageError(
3122 raise UsageError(
3123 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3123 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3124
3124
3125 elif opts.has_key('r'):
3125 elif opts.has_key('r'):
3126 bkms = {}
3126 bkms = {}
3127 elif opts.has_key('l'):
3127 elif opts.has_key('l'):
3128 bks = bkms.keys()
3128 bks = bkms.keys()
3129 bks.sort()
3129 bks.sort()
3130 if bks:
3130 if bks:
3131 size = max(map(len,bks))
3131 size = max(map(len,bks))
3132 else:
3132 else:
3133 size = 0
3133 size = 0
3134 fmt = '%-'+str(size)+'s -> %s'
3134 fmt = '%-'+str(size)+'s -> %s'
3135 print 'Current bookmarks:'
3135 print 'Current bookmarks:'
3136 for bk in bks:
3136 for bk in bks:
3137 print fmt % (bk,bkms[bk])
3137 print fmt % (bk,bkms[bk])
3138 else:
3138 else:
3139 if not args:
3139 if not args:
3140 raise UsageError("%bookmark: You must specify the bookmark name")
3140 raise UsageError("%bookmark: You must specify the bookmark name")
3141 elif len(args)==1:
3141 elif len(args)==1:
3142 bkms[args[0]] = os.getcwd()
3142 bkms[args[0]] = os.getcwd()
3143 elif len(args)==2:
3143 elif len(args)==2:
3144 bkms[args[0]] = args[1]
3144 bkms[args[0]] = args[1]
3145 self.db['bookmarks'] = bkms
3145 self.db['bookmarks'] = bkms
3146
3146
3147 def magic_pycat(self, parameter_s=''):
3147 def magic_pycat(self, parameter_s=''):
3148 """Show a syntax-highlighted file through a pager.
3148 """Show a syntax-highlighted file through a pager.
3149
3149
3150 This magic is similar to the cat utility, but it will assume the file
3150 This magic is similar to the cat utility, but it will assume the file
3151 to be Python source and will show it with syntax highlighting. """
3151 to be Python source and will show it with syntax highlighting. """
3152
3152
3153 try:
3153 try:
3154 filename = get_py_filename(parameter_s)
3154 filename = get_py_filename(parameter_s)
3155 cont = file_read(filename)
3155 cont = file_read(filename)
3156 except IOError:
3156 except IOError:
3157 try:
3157 try:
3158 cont = eval(parameter_s,self.user_ns)
3158 cont = eval(parameter_s,self.user_ns)
3159 except NameError:
3159 except NameError:
3160 cont = None
3160 cont = None
3161 if cont is None:
3161 if cont is None:
3162 print "Error: no such file or variable"
3162 print "Error: no such file or variable"
3163 return
3163 return
3164
3164
3165 page(self.shell.pycolorize(cont),
3165 page(self.shell.pycolorize(cont),
3166 screen_lines=self.shell.rc.screen_length)
3166 screen_lines=self.shell.rc.screen_length)
3167
3167
3168 def magic_cpaste(self, parameter_s=''):
3168 def magic_cpaste(self, parameter_s=''):
3169 """Allows you to paste & execute a pre-formatted code block from clipboard.
3169 """Allows you to paste & execute a pre-formatted code block from clipboard.
3170
3170
3171 You must terminate the block with '--' (two minus-signs) alone on the
3171 You must terminate the block with '--' (two minus-signs) alone on the
3172 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3172 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3173 is the new sentinel for this operation)
3173 is the new sentinel for this operation)
3174
3174
3175 The block is dedented prior to execution to enable execution of method
3175 The block is dedented prior to execution to enable execution of method
3176 definitions. '>' and '+' characters at the beginning of a line are
3176 definitions. '>' and '+' characters at the beginning of a line are
3177 ignored, to allow pasting directly from e-mails, diff files and
3177 ignored, to allow pasting directly from e-mails, diff files and
3178 doctests (the '...' continuation prompt is also stripped). The
3178 doctests (the '...' continuation prompt is also stripped). The
3179 executed block is also assigned to variable named 'pasted_block' for
3179 executed block is also assigned to variable named 'pasted_block' for
3180 later editing with '%edit pasted_block'.
3180 later editing with '%edit pasted_block'.
3181
3181
3182 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3182 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3183 This assigns the pasted block to variable 'foo' as string, without
3183 This assigns the pasted block to variable 'foo' as string, without
3184 dedenting or executing it (preceding >>> and + is still stripped)
3184 dedenting or executing it (preceding >>> and + is still stripped)
3185
3185
3186 Do not be alarmed by garbled output on Windows (it's a readline bug).
3186 Do not be alarmed by garbled output on Windows (it's a readline bug).
3187 Just press enter and type -- (and press enter again) and the block
3187 Just press enter and type -- (and press enter again) and the block
3188 will be what was just pasted.
3188 will be what was just pasted.
3189
3189
3190 IPython statements (magics, shell escapes) are not supported (yet).
3190 IPython statements (magics, shell escapes) are not supported (yet).
3191 """
3191 """
3192 opts,args = self.parse_options(parameter_s,'s:',mode='string')
3192 opts,args = self.parse_options(parameter_s,'s:',mode='string')
3193 par = args.strip()
3193 par = args.strip()
3194 sentinel = opts.get('s','--')
3194 sentinel = opts.get('s','--')
3195
3195
3196 # Regular expressions that declare text we strip from the input:
3196 # Regular expressions that declare text we strip from the input:
3197 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3197 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3198 r'^\s*(\s?>)+', # Python input prompt
3198 r'^\s*(\s?>)+', # Python input prompt
3199 r'^\s*\.{3,}', # Continuation prompts
3199 r'^\s*\.{3,}', # Continuation prompts
3200 r'^\++',
3200 r'^\++',
3201 ]
3201 ]
3202
3202
3203 strip_from_start = map(re.compile,strip_re)
3203 strip_from_start = map(re.compile,strip_re)
3204
3204
3205 from IPython import iplib
3205 from IPython import iplib
3206 lines = []
3206 lines = []
3207 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3207 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3208 while 1:
3208 while 1:
3209 l = iplib.raw_input_original(':')
3209 l = iplib.raw_input_original(':')
3210 if l ==sentinel:
3210 if l ==sentinel:
3211 break
3211 break
3212
3212
3213 for pat in strip_from_start:
3213 for pat in strip_from_start:
3214 l = pat.sub('',l)
3214 l = pat.sub('',l)
3215 lines.append(l)
3215 lines.append(l)
3216
3216
3217 block = "\n".join(lines) + '\n'
3217 block = "\n".join(lines) + '\n'
3218 #print "block:\n",block
3218 #print "block:\n",block
3219 if not par:
3219 if not par:
3220 b = textwrap.dedent(block)
3220 b = textwrap.dedent(block)
3221 exec b in self.user_ns
3221 exec b in self.user_ns
3222 self.user_ns['pasted_block'] = b
3222 self.user_ns['pasted_block'] = b
3223 else:
3223 else:
3224 self.user_ns[par] = SList(block.splitlines())
3224 self.user_ns[par] = SList(block.splitlines())
3225 print "Block assigned to '%s'" % par
3225 print "Block assigned to '%s'" % par
3226
3226
3227 def magic_quickref(self,arg):
3227 def magic_quickref(self,arg):
3228 """ Show a quick reference sheet """
3228 """ Show a quick reference sheet """
3229 import IPython.usage
3229 import IPython.usage
3230 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
3230 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
3231
3231
3232 page(qr)
3232 page(qr)
3233
3233
3234 def magic_upgrade(self,arg):
3234 def magic_upgrade(self,arg):
3235 """ Upgrade your IPython installation
3235 """ Upgrade your IPython installation
3236
3236
3237 This will copy the config files that don't yet exist in your
3237 This will copy the config files that don't yet exist in your
3238 ipython dir from the system config dir. Use this after upgrading
3238 ipython dir from the system config dir. Use this after upgrading
3239 IPython if you don't wish to delete your .ipython dir.
3239 IPython if you don't wish to delete your .ipython dir.
3240
3240
3241 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3241 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3242 new users)
3242 new users)
3243
3243
3244 """
3244 """
3245 ip = self.getapi()
3245 ip = self.getapi()
3246 ipinstallation = path(IPython.__file__).dirname()
3246 ipinstallation = path(IPython.__file__).dirname()
3247 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
3247 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
3248 src_config = ipinstallation / 'UserConfig'
3248 src_config = ipinstallation / 'UserConfig'
3249 userdir = path(ip.options.ipythondir)
3249 userdir = path(ip.options.ipythondir)
3250 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3250 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3251 print ">",cmd
3251 print ">",cmd
3252 shell(cmd)
3252 shell(cmd)
3253 if arg == '-nolegacy':
3253 if arg == '-nolegacy':
3254 legacy = userdir.files('ipythonrc*')
3254 legacy = userdir.files('ipythonrc*')
3255 print "Nuking legacy files:",legacy
3255 print "Nuking legacy files:",legacy
3256
3256
3257 [p.remove() for p in legacy]
3257 [p.remove() for p in legacy]
3258 suffix = (sys.platform == 'win32' and '.ini' or '')
3258 suffix = (sys.platform == 'win32' and '.ini' or '')
3259 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3259 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3260
3260
3261
3261
3262 def magic_doctest_mode(self,parameter_s=''):
3262 def magic_doctest_mode(self,parameter_s=''):
3263 """Toggle doctest mode on and off.
3263 """Toggle doctest mode on and off.
3264
3264
3265 This mode allows you to toggle the prompt behavior between normal
3265 This mode allows you to toggle the prompt behavior between normal
3266 IPython prompts and ones that are as similar to the default IPython
3266 IPython prompts and ones that are as similar to the default IPython
3267 interpreter as possible.
3267 interpreter as possible.
3268
3268
3269 It also supports the pasting of code snippets that have leading '>>>'
3269 It also supports the pasting of code snippets that have leading '>>>'
3270 and '...' prompts in them. This means that you can paste doctests from
3270 and '...' prompts in them. This means that you can paste doctests from
3271 files or docstrings (even if they have leading whitespace), and the
3271 files or docstrings (even if they have leading whitespace), and the
3272 code will execute correctly. You can then use '%history -tn' to see
3272 code will execute correctly. You can then use '%history -tn' to see
3273 the translated history without line numbers; this will give you the
3273 the translated history without line numbers; this will give you the
3274 input after removal of all the leading prompts and whitespace, which
3274 input after removal of all the leading prompts and whitespace, which
3275 can be pasted back into an editor.
3275 can be pasted back into an editor.
3276
3276
3277 With these features, you can switch into this mode easily whenever you
3277 With these features, you can switch into this mode easily whenever you
3278 need to do testing and changes to doctests, without having to leave
3278 need to do testing and changes to doctests, without having to leave
3279 your existing IPython session.
3279 your existing IPython session.
3280 """
3280 """
3281
3281
3282 # XXX - Fix this to have cleaner activate/deactivate calls.
3282 # XXX - Fix this to have cleaner activate/deactivate calls.
3283 from IPython.Extensions import InterpreterPasteInput as ipaste
3283 from IPython.Extensions import InterpreterPasteInput as ipaste
3284 from IPython.ipstruct import Struct
3284 from IPython.ipstruct import Struct
3285
3285
3286 # Shorthands
3286 # Shorthands
3287 shell = self.shell
3287 shell = self.shell
3288 oc = shell.outputcache
3288 oc = shell.outputcache
3289 rc = shell.rc
3289 rc = shell.rc
3290 meta = shell.meta
3290 meta = shell.meta
3291 # dstore is a data store kept in the instance metadata bag to track any
3291 # dstore is a data store kept in the instance metadata bag to track any
3292 # changes we make, so we can undo them later.
3292 # changes we make, so we can undo them later.
3293 dstore = meta.setdefault('doctest_mode',Struct())
3293 dstore = meta.setdefault('doctest_mode',Struct())
3294 save_dstore = dstore.setdefault
3294 save_dstore = dstore.setdefault
3295
3295
3296 # save a few values we'll need to recover later
3296 # save a few values we'll need to recover later
3297 mode = save_dstore('mode',False)
3297 mode = save_dstore('mode',False)
3298 save_dstore('rc_pprint',rc.pprint)
3298 save_dstore('rc_pprint',rc.pprint)
3299 save_dstore('xmode',shell.InteractiveTB.mode)
3299 save_dstore('xmode',shell.InteractiveTB.mode)
3300 save_dstore('rc_separate_out',rc.separate_out)
3300 save_dstore('rc_separate_out',rc.separate_out)
3301 save_dstore('rc_separate_out2',rc.separate_out2)
3301 save_dstore('rc_separate_out2',rc.separate_out2)
3302 save_dstore('rc_prompts_pad_left',rc.prompts_pad_left)
3302 save_dstore('rc_prompts_pad_left',rc.prompts_pad_left)
3303 save_dstore('rc_separate_in',rc.separate_in)
3303 save_dstore('rc_separate_in',rc.separate_in)
3304
3304
3305 if mode == False:
3305 if mode == False:
3306 # turn on
3306 # turn on
3307 ipaste.activate_prefilter()
3307 ipaste.activate_prefilter()
3308
3308
3309 oc.prompt1.p_template = '>>> '
3309 oc.prompt1.p_template = '>>> '
3310 oc.prompt2.p_template = '... '
3310 oc.prompt2.p_template = '... '
3311 oc.prompt_out.p_template = ''
3311 oc.prompt_out.p_template = ''
3312
3312
3313 # Prompt separators like plain python
3313 # Prompt separators like plain python
3314 oc.input_sep = oc.prompt1.sep = ''
3314 oc.input_sep = oc.prompt1.sep = ''
3315 oc.output_sep = ''
3315 oc.output_sep = ''
3316 oc.output_sep2 = ''
3316 oc.output_sep2 = ''
3317
3317
3318 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3318 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3319 oc.prompt_out.pad_left = False
3319 oc.prompt_out.pad_left = False
3320
3320
3321 rc.pprint = False
3321 rc.pprint = False
3322
3322
3323 shell.magic_xmode('Plain')
3323 shell.magic_xmode('Plain')
3324
3324
3325 else:
3325 else:
3326 # turn off
3326 # turn off
3327 ipaste.deactivate_prefilter()
3327 ipaste.deactivate_prefilter()
3328
3328
3329 oc.prompt1.p_template = rc.prompt_in1
3329 oc.prompt1.p_template = rc.prompt_in1
3330 oc.prompt2.p_template = rc.prompt_in2
3330 oc.prompt2.p_template = rc.prompt_in2
3331 oc.prompt_out.p_template = rc.prompt_out
3331 oc.prompt_out.p_template = rc.prompt_out
3332
3332
3333 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3333 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3334
3334
3335 oc.output_sep = dstore.rc_separate_out
3335 oc.output_sep = dstore.rc_separate_out
3336 oc.output_sep2 = dstore.rc_separate_out2
3336 oc.output_sep2 = dstore.rc_separate_out2
3337
3337
3338 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3338 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3339 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3339 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3340
3340
3341 rc.pprint = dstore.rc_pprint
3341 rc.pprint = dstore.rc_pprint
3342
3342
3343 shell.magic_xmode(dstore.xmode)
3343 shell.magic_xmode(dstore.xmode)
3344
3344
3345 # Store new mode and inform
3345 # Store new mode and inform
3346 dstore.mode = bool(1-int(mode))
3346 dstore.mode = bool(1-int(mode))
3347 print 'Doctest mode is:',
3347 print 'Doctest mode is:',
3348 print ['OFF','ON'][dstore.mode]
3348 print ['OFF','ON'][dstore.mode]
3349
3349
3350 # end Magic
3350 # end Magic
@@ -1,560 +1,560 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 # -*- test-case-name: IPython.frontend.cocoa.tests.test_cocoa_frontend -*-
2 # -*- test-case-name: IPython.frontend.cocoa.tests.test_cocoa_frontend -*-
3
3
4 """PyObjC classes to provide a Cocoa frontend to the
4 """PyObjC classes to provide a Cocoa frontend to the
5 IPython.kernel.engineservice.IEngineBase.
5 IPython.kernel.engineservice.IEngineBase.
6
6
7 To add an IPython interpreter to a cocoa app, instantiate an
7 To add an IPython interpreter to a cocoa app, instantiate an
8 IPythonCocoaController in a XIB and connect its textView outlet to an
8 IPythonCocoaController in a XIB and connect its textView outlet to an
9 NSTextView instance in your UI. That's it.
9 NSTextView instance in your UI. That's it.
10
10
11 Author: Barry Wark
11 Author: Barry Wark
12 """
12 """
13
13
14 __docformat__ = "restructuredtext en"
14 __docformat__ = "restructuredtext en"
15
15
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Copyright (C) 2008 The IPython Development Team
17 # Copyright (C) 2008 The IPython Development Team
18 #
18 #
19 # Distributed under the terms of the BSD License. The full license is in
19 # Distributed under the terms of the BSD License. The full license is in
20 # the file COPYING, distributed as part of this software.
20 # the file COPYING, distributed as part of this software.
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24 # Imports
24 # Imports
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26
26
27 import sys
27 import sys
28 import objc
28 import objc
29 import uuid
29 import uuid
30
30
31 from Foundation import NSObject, NSMutableArray, NSMutableDictionary,\
31 from Foundation import NSObject, NSMutableArray, NSMutableDictionary,\
32 NSLog, NSNotificationCenter, NSMakeRange,\
32 NSLog, NSNotificationCenter, NSMakeRange,\
33 NSLocalizedString, NSIntersectionRange,\
33 NSLocalizedString, NSIntersectionRange,\
34 NSString, NSAutoreleasePool
34 NSString, NSAutoreleasePool
35
35
36 from AppKit import NSApplicationWillTerminateNotification, NSBeep,\
36 from AppKit import NSApplicationWillTerminateNotification, NSBeep,\
37 NSTextView, NSRulerView, NSVerticalRuler
37 NSTextView, NSRulerView, NSVerticalRuler
38
38
39 from pprint import saferepr
39 from pprint import saferepr
40
40
41 import IPython
41 import IPython
42 from IPython.kernel.engineservice import ThreadedEngineService
42 from IPython.kernel.engineservice import ThreadedEngineService
43 from IPython.frontend.frontendbase import AsyncFrontEndBase
43 from IPython.frontend.asyncfrontendbase import AsyncFrontEndBase
44
44
45 from twisted.internet.threads import blockingCallFromThread
45 from twisted.internet.threads import blockingCallFromThread
46 from twisted.python.failure import Failure
46 from twisted.python.failure import Failure
47
47
48 #-----------------------------------------------------------------------------
48 #-----------------------------------------------------------------------------
49 # Classes to implement the Cocoa frontend
49 # Classes to implement the Cocoa frontend
50 #-----------------------------------------------------------------------------
50 #-----------------------------------------------------------------------------
51
51
52 # TODO:
52 # TODO:
53 # 1. use MultiEngineClient and out-of-process engine rather than
53 # 1. use MultiEngineClient and out-of-process engine rather than
54 # ThreadedEngineService?
54 # ThreadedEngineService?
55 # 2. integrate Xgrid launching of engines
55 # 2. integrate Xgrid launching of engines
56
56
57 class AutoreleasePoolWrappedThreadedEngineService(ThreadedEngineService):
57 class AutoreleasePoolWrappedThreadedEngineService(ThreadedEngineService):
58 """Wrap all blocks in an NSAutoreleasePool"""
58 """Wrap all blocks in an NSAutoreleasePool"""
59
59
60 def wrapped_execute(self, msg, lines):
60 def wrapped_execute(self, msg, lines):
61 """wrapped_execute"""
61 """wrapped_execute"""
62 try:
62 try:
63 p = NSAutoreleasePool.alloc().init()
63 p = NSAutoreleasePool.alloc().init()
64 result = super(AutoreleasePoolWrappedThreadedEngineService,
64 result = super(AutoreleasePoolWrappedThreadedEngineService,
65 self).wrapped_execute(msg, lines)
65 self).wrapped_execute(msg, lines)
66 finally:
66 finally:
67 p.drain()
67 p.drain()
68
68
69 return result
69 return result
70
70
71
71
72
72
73 class Cell(NSObject):
73 class Cell(NSObject):
74 """
74 """
75 Representation of the prompts, input and output of a cell in the
75 Representation of the prompts, input and output of a cell in the
76 frontend
76 frontend
77 """
77 """
78
78
79 blockNumber = objc.ivar().unsigned_long()
79 blockNumber = objc.ivar().unsigned_long()
80 blockID = objc.ivar()
80 blockID = objc.ivar()
81 inputBlock = objc.ivar()
81 inputBlock = objc.ivar()
82 output = objc.ivar()
82 output = objc.ivar()
83
83
84
84
85
85
86 class CellBlock(object):
86 class CellBlock(object):
87 """
87 """
88 Storage for information about text ranges relating to a single cell
88 Storage for information about text ranges relating to a single cell
89 """
89 """
90
90
91
91
92 def __init__(self, inputPromptRange, inputRange=None, outputPromptRange=None,
92 def __init__(self, inputPromptRange, inputRange=None, outputPromptRange=None,
93 outputRange=None):
93 outputRange=None):
94 super(CellBlock, self).__init__()
94 super(CellBlock, self).__init__()
95 self.inputPromptRange = inputPromptRange
95 self.inputPromptRange = inputPromptRange
96 self.inputRange = inputRange
96 self.inputRange = inputRange
97 self.outputPromptRange = outputPromptRange
97 self.outputPromptRange = outputPromptRange
98 self.outputRange = outputRange
98 self.outputRange = outputRange
99
99
100 def update_ranges_for_insertion(self, text, textRange):
100 def update_ranges_for_insertion(self, text, textRange):
101 """Update ranges for text insertion at textRange"""
101 """Update ranges for text insertion at textRange"""
102
102
103 for r in [self.inputPromptRange,self.inputRange,
103 for r in [self.inputPromptRange,self.inputRange,
104 self.outputPromptRange, self.outputRange]:
104 self.outputPromptRange, self.outputRange]:
105 if(r == None):
105 if(r == None):
106 continue
106 continue
107 intersection = NSIntersectionRange(r,textRange)
107 intersection = NSIntersectionRange(r,textRange)
108 if(intersection.length == 0): #ranges don't intersect
108 if(intersection.length == 0): #ranges don't intersect
109 if r.location >= textRange.location:
109 if r.location >= textRange.location:
110 r.location += len(text)
110 r.location += len(text)
111 else: #ranges intersect
111 else: #ranges intersect
112 if(r.location > textRange.location):
112 if(r.location > textRange.location):
113 offset = len(text) - intersection.length
113 offset = len(text) - intersection.length
114 r.length -= offset
114 r.length -= offset
115 r.location += offset
115 r.location += offset
116 elif(r.location == textRange.location):
116 elif(r.location == textRange.location):
117 r.length += len(text) - intersection.length
117 r.length += len(text) - intersection.length
118 else:
118 else:
119 r.length -= intersection.length
119 r.length -= intersection.length
120
120
121
121
122 def update_ranges_for_deletion(self, textRange):
122 def update_ranges_for_deletion(self, textRange):
123 """Update ranges for text deletion at textRange"""
123 """Update ranges for text deletion at textRange"""
124
124
125 for r in [self.inputPromptRange,self.inputRange,
125 for r in [self.inputPromptRange,self.inputRange,
126 self.outputPromptRange, self.outputRange]:
126 self.outputPromptRange, self.outputRange]:
127 if(r==None):
127 if(r==None):
128 continue
128 continue
129 intersection = NSIntersectionRange(r, textRange)
129 intersection = NSIntersectionRange(r, textRange)
130 if(intersection.length == 0): #ranges don't intersect
130 if(intersection.length == 0): #ranges don't intersect
131 if r.location >= textRange.location:
131 if r.location >= textRange.location:
132 r.location -= textRange.length
132 r.location -= textRange.length
133 else: #ranges intersect
133 else: #ranges intersect
134 if(r.location > textRange.location):
134 if(r.location > textRange.location):
135 offset = intersection.length
135 offset = intersection.length
136 r.length -= offset
136 r.length -= offset
137 r.location += offset
137 r.location += offset
138 elif(r.location == textRange.location):
138 elif(r.location == textRange.location):
139 r.length += intersection.length
139 r.length += intersection.length
140 else:
140 else:
141 r.length -= intersection.length
141 r.length -= intersection.length
142
142
143 def __repr__(self):
143 def __repr__(self):
144 return 'CellBlock('+ str((self.inputPromptRange,
144 return 'CellBlock('+ str((self.inputPromptRange,
145 self.inputRange,
145 self.inputRange,
146 self.outputPromptRange,
146 self.outputPromptRange,
147 self.outputRange)) + ')'
147 self.outputRange)) + ')'
148
148
149
149
150
150
151
151
152 class IPythonCocoaController(NSObject, AsyncFrontEndBase):
152 class IPythonCocoaController(NSObject, AsyncFrontEndBase):
153 userNS = objc.ivar() #mirror of engine.user_ns (key=>str(value))
153 userNS = objc.ivar() #mirror of engine.user_ns (key=>str(value))
154 waitingForEngine = objc.ivar().bool()
154 waitingForEngine = objc.ivar().bool()
155 textView = objc.IBOutlet()
155 textView = objc.IBOutlet()
156
156
157 def init(self):
157 def init(self):
158 self = super(IPythonCocoaController, self).init()
158 self = super(IPythonCocoaController, self).init()
159 AsyncFrontEndBase.__init__(self,
159 AsyncFrontEndBase.__init__(self,
160 engine=AutoreleasePoolWrappedThreadedEngineService())
160 engine=AutoreleasePoolWrappedThreadedEngineService())
161 if(self != None):
161 if(self != None):
162 self._common_init()
162 self._common_init()
163
163
164 return self
164 return self
165
165
166 def _common_init(self):
166 def _common_init(self):
167 """_common_init"""
167 """_common_init"""
168
168
169 self.userNS = NSMutableDictionary.dictionary()
169 self.userNS = NSMutableDictionary.dictionary()
170 self.waitingForEngine = False
170 self.waitingForEngine = False
171
171
172 self.lines = {}
172 self.lines = {}
173 self.tabSpaces = 4
173 self.tabSpaces = 4
174 self.tabUsesSpaces = True
174 self.tabUsesSpaces = True
175 self.currentBlockID = self.next_block_ID()
175 self.currentBlockID = self.next_block_ID()
176 self.blockRanges = {} # blockID=>CellBlock
176 self.blockRanges = {} # blockID=>CellBlock
177
177
178
178
179 def awakeFromNib(self):
179 def awakeFromNib(self):
180 """awakeFromNib"""
180 """awakeFromNib"""
181
181
182 self._common_init()
182 self._common_init()
183
183
184 # Start the IPython engine
184 # Start the IPython engine
185 self.engine.startService()
185 self.engine.startService()
186 NSLog('IPython engine started')
186 NSLog('IPython engine started')
187
187
188 # Register for app termination
188 # Register for app termination
189 nc = NSNotificationCenter.defaultCenter()
189 nc = NSNotificationCenter.defaultCenter()
190 nc.addObserver_selector_name_object_(
190 nc.addObserver_selector_name_object_(
191 self,
191 self,
192 'appWillTerminate:',
192 'appWillTerminate:',
193 NSApplicationWillTerminateNotification,
193 NSApplicationWillTerminateNotification,
194 None)
194 None)
195
195
196 self.textView.setDelegate_(self)
196 self.textView.setDelegate_(self)
197 self.textView.enclosingScrollView().setHasVerticalRuler_(True)
197 self.textView.enclosingScrollView().setHasVerticalRuler_(True)
198 r = NSRulerView.alloc().initWithScrollView_orientation_(
198 r = NSRulerView.alloc().initWithScrollView_orientation_(
199 self.textView.enclosingScrollView(),
199 self.textView.enclosingScrollView(),
200 NSVerticalRuler)
200 NSVerticalRuler)
201 self.verticalRulerView = r
201 self.verticalRulerView = r
202 self.verticalRulerView.setClientView_(self.textView)
202 self.verticalRulerView.setClientView_(self.textView)
203 self._start_cli_banner()
203 self._start_cli_banner()
204 self.start_new_block()
204 self.start_new_block()
205
205
206
206
207 def appWillTerminate_(self, notification):
207 def appWillTerminate_(self, notification):
208 """appWillTerminate"""
208 """appWillTerminate"""
209
209
210 self.engine.stopService()
210 self.engine.stopService()
211
211
212
212
213 def complete(self, token):
213 def complete(self, token):
214 """Complete token in engine's user_ns
214 """Complete token in engine's user_ns
215
215
216 Parameters
216 Parameters
217 ----------
217 ----------
218 token : string
218 token : string
219
219
220 Result
220 Result
221 ------
221 ------
222 Deferred result of
222 Deferred result of
223 IPython.kernel.engineservice.IEngineBase.complete
223 IPython.kernel.engineservice.IEngineBase.complete
224 """
224 """
225
225
226 return self.engine.complete(token)
226 return self.engine.complete(token)
227
227
228
228
229 def execute(self, block, blockID=None):
229 def execute(self, block, blockID=None):
230 self.waitingForEngine = True
230 self.waitingForEngine = True
231 self.willChangeValueForKey_('commandHistory')
231 self.willChangeValueForKey_('commandHistory')
232 d = super(IPythonCocoaController, self).execute(block,
232 d = super(IPythonCocoaController, self).execute(block,
233 blockID)
233 blockID)
234 d.addBoth(self._engine_done)
234 d.addBoth(self._engine_done)
235 d.addCallback(self._update_user_ns)
235 d.addCallback(self._update_user_ns)
236
236
237 return d
237 return d
238
238
239
239
240 def push_(self, namespace):
240 def push_(self, namespace):
241 """Push dictionary of key=>values to python namespace"""
241 """Push dictionary of key=>values to python namespace"""
242
242
243 self.waitingForEngine = True
243 self.waitingForEngine = True
244 self.willChangeValueForKey_('commandHistory')
244 self.willChangeValueForKey_('commandHistory')
245 d = self.engine.push(namespace)
245 d = self.engine.push(namespace)
246 d.addBoth(self._engine_done)
246 d.addBoth(self._engine_done)
247 d.addCallback(self._update_user_ns)
247 d.addCallback(self._update_user_ns)
248
248
249
249
250 def pull_(self, keys):
250 def pull_(self, keys):
251 """Pull keys from python namespace"""
251 """Pull keys from python namespace"""
252
252
253 self.waitingForEngine = True
253 self.waitingForEngine = True
254 result = blockingCallFromThread(self.engine.pull, keys)
254 result = blockingCallFromThread(self.engine.pull, keys)
255 self.waitingForEngine = False
255 self.waitingForEngine = False
256
256
257 @objc.signature('v@:@I')
257 @objc.signature('v@:@I')
258 def executeFileAtPath_encoding_(self, path, encoding):
258 def executeFileAtPath_encoding_(self, path, encoding):
259 """Execute file at path in an empty namespace. Update the engine
259 """Execute file at path in an empty namespace. Update the engine
260 user_ns with the resulting locals."""
260 user_ns with the resulting locals."""
261
261
262 lines,err = NSString.stringWithContentsOfFile_encoding_error_(
262 lines,err = NSString.stringWithContentsOfFile_encoding_error_(
263 path,
263 path,
264 encoding,
264 encoding,
265 None)
265 None)
266 self.engine.execute(lines)
266 self.engine.execute(lines)
267
267
268
268
269 def _engine_done(self, x):
269 def _engine_done(self, x):
270 self.waitingForEngine = False
270 self.waitingForEngine = False
271 self.didChangeValueForKey_('commandHistory')
271 self.didChangeValueForKey_('commandHistory')
272 return x
272 return x
273
273
274 def _update_user_ns(self, result):
274 def _update_user_ns(self, result):
275 """Update self.userNS from self.engine's namespace"""
275 """Update self.userNS from self.engine's namespace"""
276 d = self.engine.keys()
276 d = self.engine.keys()
277 d.addCallback(self._get_engine_namespace_values_for_keys)
277 d.addCallback(self._get_engine_namespace_values_for_keys)
278
278
279 return result
279 return result
280
280
281
281
282 def _get_engine_namespace_values_for_keys(self, keys):
282 def _get_engine_namespace_values_for_keys(self, keys):
283 d = self.engine.pull(keys)
283 d = self.engine.pull(keys)
284 d.addCallback(self._store_engine_namespace_values, keys=keys)
284 d.addCallback(self._store_engine_namespace_values, keys=keys)
285
285
286
286
287 def _store_engine_namespace_values(self, values, keys=[]):
287 def _store_engine_namespace_values(self, values, keys=[]):
288 assert(len(values) == len(keys))
288 assert(len(values) == len(keys))
289 self.willChangeValueForKey_('userNS')
289 self.willChangeValueForKey_('userNS')
290 for (k,v) in zip(keys,values):
290 for (k,v) in zip(keys,values):
291 self.userNS[k] = saferepr(v)
291 self.userNS[k] = saferepr(v)
292 self.didChangeValueForKey_('userNS')
292 self.didChangeValueForKey_('userNS')
293
293
294
294
295 def update_cell_prompt(self, result, blockID=None):
295 def update_cell_prompt(self, result, blockID=None):
296 print self.blockRanges
296 print self.blockRanges
297 if(isinstance(result, Failure)):
297 if(isinstance(result, Failure)):
298 prompt = self.input_prompt()
298 prompt = self.input_prompt()
299
299
300 else:
300 else:
301 prompt = self.input_prompt(number=result['number'])
301 prompt = self.input_prompt(number=result['number'])
302
302
303 r = self.blockRanges[blockID].inputPromptRange
303 r = self.blockRanges[blockID].inputPromptRange
304 self.insert_text(prompt,
304 self.insert_text(prompt,
305 textRange=r,
305 textRange=r,
306 scrollToVisible=False
306 scrollToVisible=False
307 )
307 )
308
308
309 return result
309 return result
310
310
311
311
312 def render_result(self, result):
312 def render_result(self, result):
313 blockID = result['blockID']
313 blockID = result['blockID']
314 inputRange = self.blockRanges[blockID].inputRange
314 inputRange = self.blockRanges[blockID].inputRange
315 del self.blockRanges[blockID]
315 del self.blockRanges[blockID]
316
316
317 #print inputRange,self.current_block_range()
317 #print inputRange,self.current_block_range()
318 self.insert_text('\n' +
318 self.insert_text('\n' +
319 self.output_prompt(number=result['number']) +
319 self.output_prompt(number=result['number']) +
320 result.get('display',{}).get('pprint','') +
320 result.get('display',{}).get('pprint','') +
321 '\n\n',
321 '\n\n',
322 textRange=NSMakeRange(inputRange.location+inputRange.length,
322 textRange=NSMakeRange(inputRange.location+inputRange.length,
323 0))
323 0))
324 return result
324 return result
325
325
326
326
327 def render_error(self, failure):
327 def render_error(self, failure):
328 print failure
328 print failure
329 blockID = failure.blockID
329 blockID = failure.blockID
330 inputRange = self.blockRanges[blockID].inputRange
330 inputRange = self.blockRanges[blockID].inputRange
331 self.insert_text('\n' +
331 self.insert_text('\n' +
332 self.output_prompt() +
332 self.output_prompt() +
333 '\n' +
333 '\n' +
334 failure.getErrorMessage() +
334 failure.getErrorMessage() +
335 '\n\n',
335 '\n\n',
336 textRange=NSMakeRange(inputRange.location +
336 textRange=NSMakeRange(inputRange.location +
337 inputRange.length,
337 inputRange.length,
338 0))
338 0))
339 self.start_new_block()
339 self.start_new_block()
340 return failure
340 return failure
341
341
342
342
343 def _start_cli_banner(self):
343 def _start_cli_banner(self):
344 """Print banner"""
344 """Print banner"""
345
345
346 banner = """IPython1 %s -- An enhanced Interactive Python.""" % \
346 banner = """IPython1 %s -- An enhanced Interactive Python.""" % \
347 IPython.__version__
347 IPython.__version__
348
348
349 self.insert_text(banner + '\n\n')
349 self.insert_text(banner + '\n\n')
350
350
351
351
352 def start_new_block(self):
352 def start_new_block(self):
353 """"""
353 """"""
354
354
355 self.currentBlockID = self.next_block_ID()
355 self.currentBlockID = self.next_block_ID()
356 self.blockRanges[self.currentBlockID] = self.new_cell_block()
356 self.blockRanges[self.currentBlockID] = self.new_cell_block()
357 self.insert_text(self.input_prompt(),
357 self.insert_text(self.input_prompt(),
358 textRange=self.current_block_range().inputPromptRange)
358 textRange=self.current_block_range().inputPromptRange)
359
359
360
360
361
361
362 def next_block_ID(self):
362 def next_block_ID(self):
363
363
364 return uuid.uuid4()
364 return uuid.uuid4()
365
365
366 def new_cell_block(self):
366 def new_cell_block(self):
367 """A new CellBlock at the end of self.textView.textStorage()"""
367 """A new CellBlock at the end of self.textView.textStorage()"""
368
368
369 return CellBlock(NSMakeRange(self.textView.textStorage().length(),
369 return CellBlock(NSMakeRange(self.textView.textStorage().length(),
370 0), #len(self.input_prompt())),
370 0), #len(self.input_prompt())),
371 NSMakeRange(self.textView.textStorage().length(),# + len(self.input_prompt()),
371 NSMakeRange(self.textView.textStorage().length(),# + len(self.input_prompt()),
372 0))
372 0))
373
373
374
374
375 def current_block_range(self):
375 def current_block_range(self):
376 return self.blockRanges.get(self.currentBlockID,
376 return self.blockRanges.get(self.currentBlockID,
377 self.new_cell_block())
377 self.new_cell_block())
378
378
379 def current_block(self):
379 def current_block(self):
380 """The current block's text"""
380 """The current block's text"""
381
381
382 return self.text_for_range(self.current_block_range().inputRange)
382 return self.text_for_range(self.current_block_range().inputRange)
383
383
384 def text_for_range(self, textRange):
384 def text_for_range(self, textRange):
385 """text_for_range"""
385 """text_for_range"""
386
386
387 ts = self.textView.textStorage()
387 ts = self.textView.textStorage()
388 return ts.string().substringWithRange_(textRange)
388 return ts.string().substringWithRange_(textRange)
389
389
390 def current_line(self):
390 def current_line(self):
391 block = self.text_for_range(self.current_block_range().inputRange)
391 block = self.text_for_range(self.current_block_range().inputRange)
392 block = block.split('\n')
392 block = block.split('\n')
393 return block[-1]
393 return block[-1]
394
394
395
395
396 def insert_text(self, string=None, textRange=None, scrollToVisible=True):
396 def insert_text(self, string=None, textRange=None, scrollToVisible=True):
397 """Insert text into textView at textRange, updating blockRanges
397 """Insert text into textView at textRange, updating blockRanges
398 as necessary
398 as necessary
399 """
399 """
400 if(textRange == None):
400 if(textRange == None):
401 #range for end of text
401 #range for end of text
402 textRange = NSMakeRange(self.textView.textStorage().length(), 0)
402 textRange = NSMakeRange(self.textView.textStorage().length(), 0)
403
403
404
404
405 self.textView.replaceCharactersInRange_withString_(
405 self.textView.replaceCharactersInRange_withString_(
406 textRange, string)
406 textRange, string)
407
407
408 for r in self.blockRanges.itervalues():
408 for r in self.blockRanges.itervalues():
409 r.update_ranges_for_insertion(string, textRange)
409 r.update_ranges_for_insertion(string, textRange)
410
410
411 self.textView.setSelectedRange_(textRange)
411 self.textView.setSelectedRange_(textRange)
412 if(scrollToVisible):
412 if(scrollToVisible):
413 self.textView.scrollRangeToVisible_(textRange)
413 self.textView.scrollRangeToVisible_(textRange)
414
414
415
415
416
416
417 def replace_current_block_with_string(self, textView, string):
417 def replace_current_block_with_string(self, textView, string):
418 textView.replaceCharactersInRange_withString_(
418 textView.replaceCharactersInRange_withString_(
419 self.current_block_range().inputRange,
419 self.current_block_range().inputRange,
420 string)
420 string)
421 self.current_block_range().inputRange.length = len(string)
421 self.current_block_range().inputRange.length = len(string)
422 r = NSMakeRange(textView.textStorage().length(), 0)
422 r = NSMakeRange(textView.textStorage().length(), 0)
423 textView.scrollRangeToVisible_(r)
423 textView.scrollRangeToVisible_(r)
424 textView.setSelectedRange_(r)
424 textView.setSelectedRange_(r)
425
425
426
426
427 def current_indent_string(self):
427 def current_indent_string(self):
428 """returns string for indent or None if no indent"""
428 """returns string for indent or None if no indent"""
429
429
430 return self._indent_for_block(self.current_block())
430 return self._indent_for_block(self.current_block())
431
431
432
432
433 def _indent_for_block(self, block):
433 def _indent_for_block(self, block):
434 lines = block.split('\n')
434 lines = block.split('\n')
435 if(len(lines) > 1):
435 if(len(lines) > 1):
436 currentIndent = len(lines[-1]) - len(lines[-1].lstrip())
436 currentIndent = len(lines[-1]) - len(lines[-1].lstrip())
437 if(currentIndent == 0):
437 if(currentIndent == 0):
438 currentIndent = self.tabSpaces
438 currentIndent = self.tabSpaces
439
439
440 if(self.tabUsesSpaces):
440 if(self.tabUsesSpaces):
441 result = ' ' * currentIndent
441 result = ' ' * currentIndent
442 else:
442 else:
443 result = '\t' * (currentIndent/self.tabSpaces)
443 result = '\t' * (currentIndent/self.tabSpaces)
444 else:
444 else:
445 result = None
445 result = None
446
446
447 return result
447 return result
448
448
449
449
450 # NSTextView delegate methods...
450 # NSTextView delegate methods...
451 def textView_doCommandBySelector_(self, textView, selector):
451 def textView_doCommandBySelector_(self, textView, selector):
452 assert(textView == self.textView)
452 assert(textView == self.textView)
453 NSLog("textView_doCommandBySelector_: "+selector)
453 NSLog("textView_doCommandBySelector_: "+selector)
454
454
455
455
456 if(selector == 'insertNewline:'):
456 if(selector == 'insertNewline:'):
457 indent = self.current_indent_string()
457 indent = self.current_indent_string()
458 if(indent):
458 if(indent):
459 line = indent + self.current_line()
459 line = indent + self.current_line()
460 else:
460 else:
461 line = self.current_line()
461 line = self.current_line()
462
462
463 if(self.is_complete(self.current_block())):
463 if(self.is_complete(self.current_block())):
464 self.execute(self.current_block(),
464 self.execute(self.current_block(),
465 blockID=self.currentBlockID)
465 blockID=self.currentBlockID)
466 self.start_new_block()
466 self.start_new_block()
467
467
468 return True
468 return True
469
469
470 return False
470 return False
471
471
472 elif(selector == 'moveUp:'):
472 elif(selector == 'moveUp:'):
473 prevBlock = self.get_history_previous(self.current_block())
473 prevBlock = self.get_history_previous(self.current_block())
474 if(prevBlock != None):
474 if(prevBlock != None):
475 self.replace_current_block_with_string(textView, prevBlock)
475 self.replace_current_block_with_string(textView, prevBlock)
476 else:
476 else:
477 NSBeep()
477 NSBeep()
478 return True
478 return True
479
479
480 elif(selector == 'moveDown:'):
480 elif(selector == 'moveDown:'):
481 nextBlock = self.get_history_next()
481 nextBlock = self.get_history_next()
482 if(nextBlock != None):
482 if(nextBlock != None):
483 self.replace_current_block_with_string(textView, nextBlock)
483 self.replace_current_block_with_string(textView, nextBlock)
484 else:
484 else:
485 NSBeep()
485 NSBeep()
486 return True
486 return True
487
487
488 elif(selector == 'moveToBeginningOfParagraph:'):
488 elif(selector == 'moveToBeginningOfParagraph:'):
489 textView.setSelectedRange_(NSMakeRange(
489 textView.setSelectedRange_(NSMakeRange(
490 self.current_block_range().inputRange.location,
490 self.current_block_range().inputRange.location,
491 0))
491 0))
492 return True
492 return True
493 elif(selector == 'moveToEndOfParagraph:'):
493 elif(selector == 'moveToEndOfParagraph:'):
494 textView.setSelectedRange_(NSMakeRange(
494 textView.setSelectedRange_(NSMakeRange(
495 self.current_block_range().inputRange.location + \
495 self.current_block_range().inputRange.location + \
496 self.current_block_range().inputRange.length, 0))
496 self.current_block_range().inputRange.length, 0))
497 return True
497 return True
498 elif(selector == 'deleteToEndOfParagraph:'):
498 elif(selector == 'deleteToEndOfParagraph:'):
499 if(textView.selectedRange().location <= \
499 if(textView.selectedRange().location <= \
500 self.current_block_range().location):
500 self.current_block_range().location):
501 raise NotImplemented()
501 raise NotImplemented()
502
502
503 return False # don't actually handle the delete
503 return False # don't actually handle the delete
504
504
505 elif(selector == 'insertTab:'):
505 elif(selector == 'insertTab:'):
506 if(len(self.current_line().strip()) == 0): #only white space
506 if(len(self.current_line().strip()) == 0): #only white space
507 return False
507 return False
508 else:
508 else:
509 self.textView.complete_(self)
509 self.textView.complete_(self)
510 return True
510 return True
511
511
512 elif(selector == 'deleteBackward:'):
512 elif(selector == 'deleteBackward:'):
513 #if we're at the beginning of the current block, ignore
513 #if we're at the beginning of the current block, ignore
514 if(textView.selectedRange().location == \
514 if(textView.selectedRange().location == \
515 self.current_block_range().inputRange.location):
515 self.current_block_range().inputRange.location):
516 return True
516 return True
517 else:
517 else:
518 for r in self.blockRanges.itervalues():
518 for r in self.blockRanges.itervalues():
519 deleteRange = textView.selectedRange
519 deleteRange = textView.selectedRange
520 if(deleteRange.length == 0):
520 if(deleteRange.length == 0):
521 deleteRange.location -= 1
521 deleteRange.location -= 1
522 deleteRange.length = 1
522 deleteRange.length = 1
523 r.update_ranges_for_deletion(deleteRange)
523 r.update_ranges_for_deletion(deleteRange)
524 return False
524 return False
525 return False
525 return False
526
526
527
527
528 def textView_shouldChangeTextInRanges_replacementStrings_(self,
528 def textView_shouldChangeTextInRanges_replacementStrings_(self,
529 textView, ranges, replacementStrings):
529 textView, ranges, replacementStrings):
530 """
530 """
531 Delegate method for NSTextView.
531 Delegate method for NSTextView.
532
532
533 Refuse change text in ranges not at end, but make those changes at
533 Refuse change text in ranges not at end, but make those changes at
534 end.
534 end.
535 """
535 """
536
536
537 assert(len(ranges) == len(replacementStrings))
537 assert(len(ranges) == len(replacementStrings))
538 allow = True
538 allow = True
539 for r,s in zip(ranges, replacementStrings):
539 for r,s in zip(ranges, replacementStrings):
540 r = r.rangeValue()
540 r = r.rangeValue()
541 if(textView.textStorage().length() > 0 and
541 if(textView.textStorage().length() > 0 and
542 r.location < self.current_block_range().inputRange.location):
542 r.location < self.current_block_range().inputRange.location):
543 self.insert_text(s)
543 self.insert_text(s)
544 allow = False
544 allow = False
545
545
546 return allow
546 return allow
547
547
548 def textView_completions_forPartialWordRange_indexOfSelectedItem_(self,
548 def textView_completions_forPartialWordRange_indexOfSelectedItem_(self,
549 textView, words, charRange, index):
549 textView, words, charRange, index):
550 try:
550 try:
551 ts = textView.textStorage()
551 ts = textView.textStorage()
552 token = ts.string().substringWithRange_(charRange)
552 token = ts.string().substringWithRange_(charRange)
553 completions = blockingCallFromThread(self.complete, token)
553 completions = blockingCallFromThread(self.complete, token)
554 except:
554 except:
555 completions = objc.nil
555 completions = objc.nil
556 NSBeep()
556 NSBeep()
557
557
558 return (completions,0)
558 return (completions,0)
559
559
560
560
@@ -1,400 +1,359 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 # -*- test-case-name: IPython.frontend.tests.test_frontendbase -*-
2 # -*- test-case-name: IPython.frontend.tests.test_frontendbase -*-
3 """
3 """
4 frontendbase provides an interface and base class for GUI frontends for
4 frontendbase provides an interface and base class for GUI frontends for
5 IPython.kernel/IPython.kernel.core.
5 IPython.kernel/IPython.kernel.core.
6
6
7 Frontend implementations will likely want to subclass FrontEndBase.
7 Frontend implementations will likely want to subclass FrontEndBase.
8
8
9 Author: Barry Wark
9 Author: Barry Wark
10 """
10 """
11 __docformat__ = "restructuredtext en"
11 __docformat__ = "restructuredtext en"
12
12
13 #-------------------------------------------------------------------------------
13 #-------------------------------------------------------------------------------
14 # Copyright (C) 2008 The IPython Development Team
14 # Copyright (C) 2008 The IPython Development Team
15 #
15 #
16 # Distributed under the terms of the BSD License. The full license is in
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
17 # the file COPYING, distributed as part of this software.
18 #-------------------------------------------------------------------------------
18 #-------------------------------------------------------------------------------
19
19
20 #-------------------------------------------------------------------------------
20 #-------------------------------------------------------------------------------
21 # Imports
21 # Imports
22 #-------------------------------------------------------------------------------
22 #-------------------------------------------------------------------------------
23 import string
23 import string
24 import uuid
24 import uuid
25 import _ast
25 import _ast
26
26
27 try:
27 from zopeinterface import Interface, Attribute, implements, classProvides
28 from zope.interface import Interface, Attribute, implements, classProvides
29 except ImportError:
30 #zope.interface is not available
31 Interface = object
32 def Attribute(name, doc): pass
33 def implements(interface): pass
34 def classProvides(interface): pass
35
28
36 from IPython.kernel.core.history import FrontEndHistory
29 from IPython.kernel.core.history import FrontEndHistory
37 from IPython.kernel.core.util import Bunch
30 from IPython.kernel.core.util import Bunch
38 from IPython.kernel.engineservice import IEngineCore
31 from IPython.kernel.engineservice import IEngineCore
39
32
40
41 ##############################################################################
33 ##############################################################################
42 # TEMPORARY!!! fake configuration, while we decide whether to use tconfig or
34 # TEMPORARY!!! fake configuration, while we decide whether to use tconfig or
43 # not
35 # not
44
36
45 rc = Bunch()
37 rc = Bunch()
46 rc.prompt_in1 = r'In [$number]: '
38 rc.prompt_in1 = r'In [$number]: '
47 rc.prompt_in2 = r'...'
39 rc.prompt_in2 = r'...'
48 rc.prompt_out = r'Out [$number]: '
40 rc.prompt_out = r'Out [$number]: '
49
41
50 ##############################################################################
42 ##############################################################################
43 # Interface definitions
44 ##############################################################################
51
45
52 class IFrontEndFactory(Interface):
46 class IFrontEndFactory(Interface):
53 """Factory interface for frontends."""
47 """Factory interface for frontends."""
54
48
55 def __call__(engine=None, history=None):
49 def __call__(engine=None, history=None):
56 """
50 """
57 Parameters:
51 Parameters:
58 interpreter : IPython.kernel.engineservice.IEngineCore
52 interpreter : IPython.kernel.engineservice.IEngineCore
59 """
53 """
60
54
61 pass
55 pass
62
56
63
57
64
65 class IFrontEnd(Interface):
58 class IFrontEnd(Interface):
66 """Interface for frontends. All methods return t.i.d.Deferred"""
59 """Interface for frontends. All methods return t.i.d.Deferred"""
67
60
68 Attribute("input_prompt_template", "string.Template instance\
61 Attribute("input_prompt_template", "string.Template instance\
69 substituteable with execute result.")
62 substituteable with execute result.")
70 Attribute("output_prompt_template", "string.Template instance\
63 Attribute("output_prompt_template", "string.Template instance\
71 substituteable with execute result.")
64 substituteable with execute result.")
72 Attribute("continuation_prompt_template", "string.Template instance\
65 Attribute("continuation_prompt_template", "string.Template instance\
73 substituteable with execute result.")
66 substituteable with execute result.")
74
67
75 def update_cell_prompt(result, blockID=None):
68 def update_cell_prompt(result, blockID=None):
76 """Subclass may override to update the input prompt for a block.
69 """Subclass may override to update the input prompt for a block.
77 Since this method will be called as a
70
78 twisted.internet.defer.Deferred's callback/errback,
71 In asynchronous frontends, this method will be called as a
79 implementations should return result when finished.
72 twisted.internet.defer.Deferred's callback/errback.
73 Implementations should thus return result when finished.
80
74
81 Result is a result dict in case of success, and a
75 Result is a result dict in case of success, and a
82 twisted.python.util.failure.Failure in case of an error
76 twisted.python.util.failure.Failure in case of an error
83 """
77 """
84
78
85 pass
79 pass
86
80
87
88 def render_result(result):
81 def render_result(result):
89 """Render the result of an execute call. Implementors may choose the
82 """Render the result of an execute call. Implementors may choose the
90 method of rendering.
83 method of rendering.
91 For example, a notebook-style frontend might render a Chaco plot
84 For example, a notebook-style frontend might render a Chaco plot
92 inline.
85 inline.
93
86
94 Parameters:
87 Parameters:
95 result : dict (result of IEngineBase.execute )
88 result : dict (result of IEngineBase.execute )
96 blockID = result['blockID']
89 blockID = result['blockID']
97
90
98 Result:
91 Result:
99 Output of frontend rendering
92 Output of frontend rendering
100 """
93 """
101
94
102 pass
95 pass
103
96
104 def render_error(failure):
97 def render_error(failure):
105 """Subclasses must override to render the failure. Since this method
98 """Subclasses must override to render the failure.
106 will be called as a twisted.internet.defer.Deferred's callback,
99
107 implementations should return result when finished.
100 In asynchronous frontend, since this method will be called as a
101 twisted.internet.defer.Deferred's callback. Implementations
102 should thus return result when finished.
108
103
109 blockID = failure.blockID
104 blockID = failure.blockID
110 """
105 """
111
106
112 pass
107 pass
113
108
114
115 def input_prompt(number=''):
109 def input_prompt(number=''):
116 """Returns the input prompt by subsituting into
110 """Returns the input prompt by subsituting into
117 self.input_prompt_template
111 self.input_prompt_template
118 """
112 """
119 pass
113 pass
120
114
121 def output_prompt(number=''):
115 def output_prompt(number=''):
122 """Returns the output prompt by subsituting into
116 """Returns the output prompt by subsituting into
123 self.output_prompt_template
117 self.output_prompt_template
124 """
118 """
125
119
126 pass
120 pass
127
121
128 def continuation_prompt():
122 def continuation_prompt():
129 """Returns the continuation prompt by subsituting into
123 """Returns the continuation prompt by subsituting into
130 self.continuation_prompt_template
124 self.continuation_prompt_template
131 """
125 """
132
126
133 pass
127 pass
134
128
135 def is_complete(block):
129 def is_complete(block):
136 """Returns True if block is complete, False otherwise."""
130 """Returns True if block is complete, False otherwise."""
137
131
138 pass
132 pass
139
133
140 def compile_ast(block):
134 def compile_ast(block):
141 """Compiles block to an _ast.AST"""
135 """Compiles block to an _ast.AST"""
142
136
143 pass
137 pass
144
138
145
139 def get_history_previous(current_block):
146 def get_history_previous(currentBlock):
147 """Returns the block previous in the history. Saves currentBlock if
140 """Returns the block previous in the history. Saves currentBlock if
148 the history_cursor is currently at the end of the input history"""
141 the history_cursor is currently at the end of the input history"""
149 pass
142 pass
150
143
151 def get_history_next():
144 def get_history_next():
152 """Returns the next block in the history."""
145 """Returns the next block in the history."""
153
146
154 pass
147 pass
155
148
149 def complete(self, line):
150 """Returns the list of possible completions, and the completed
151 line.
152
153 The input argument is the full line to be completed. This method
154 returns both the line completed as much as possible, and the list
155 of further possible completions (full words).
156 """
157 pass
158
159
160 ##############################################################################
161 # Base class for all the frontends.
162 ##############################################################################
156
163
157 class FrontEndBase(object):
164 class FrontEndBase(object):
158 """
165 """
159 FrontEndBase manages the state tasks for a CLI frontend:
166 FrontEndBase manages the state tasks for a CLI frontend:
160 - Input and output history management
167 - Input and output history management
161 - Input/continuation and output prompt generation
168 - Input/continuation and output prompt generation
162
169
163 Some issues (due to possibly unavailable engine):
170 Some issues (due to possibly unavailable engine):
164 - How do we get the current cell number for the engine?
171 - How do we get the current cell number for the engine?
165 - How do we handle completions?
172 - How do we handle completions?
166 """
173 """
167
174
168 history_cursor = 0
175 history_cursor = 0
169
176
170 current_indent_level = 0
171
172
173 input_prompt_template = string.Template(rc.prompt_in1)
177 input_prompt_template = string.Template(rc.prompt_in1)
174 output_prompt_template = string.Template(rc.prompt_out)
178 output_prompt_template = string.Template(rc.prompt_out)
175 continuation_prompt_template = string.Template(rc.prompt_in2)
179 continuation_prompt_template = string.Template(rc.prompt_in2)
176
180
177 def __init__(self, shell=None, history=None):
181 def __init__(self, shell=None, history=None):
178 self.shell = shell
182 self.shell = shell
179 if history is None:
183 if history is None:
180 self.history = FrontEndHistory(input_cache=[''])
184 self.history = FrontEndHistory(input_cache=[''])
181 else:
185 else:
182 self.history = history
186 self.history = history
183
187
184
188
185 def input_prompt(self, number=''):
189 def input_prompt(self, number=''):
186 """Returns the current input prompt
190 """Returns the current input prompt
187
191
188 It would be great to use ipython1.core.prompts.Prompt1 here
192 It would be great to use ipython1.core.prompts.Prompt1 here
189 """
193 """
190 return self.input_prompt_template.safe_substitute({'number':number})
194 return self.input_prompt_template.safe_substitute({'number':number})
191
195
192
196
193 def continuation_prompt(self):
197 def continuation_prompt(self):
194 """Returns the current continuation prompt"""
198 """Returns the current continuation prompt"""
195
199
196 return self.continuation_prompt_template.safe_substitute()
200 return self.continuation_prompt_template.safe_substitute()
197
201
198 def output_prompt(self, number=''):
202 def output_prompt(self, number=''):
199 """Returns the output prompt for result"""
203 """Returns the output prompt for result"""
200
204
201 return self.output_prompt_template.safe_substitute({'number':number})
205 return self.output_prompt_template.safe_substitute({'number':number})
202
206
203
207
204 def is_complete(self, block):
208 def is_complete(self, block):
205 """Determine if block is complete.
209 """Determine if block is complete.
206
210
207 Parameters
211 Parameters
208 block : string
212 block : string
209
213
210 Result
214 Result
211 True if block can be sent to the engine without compile errors.
215 True if block can be sent to the engine without compile errors.
212 False otherwise.
216 False otherwise.
213 """
217 """
214
218
215 try:
219 try:
216 ast = self.compile_ast(block)
220 ast = self.compile_ast(block)
217 except:
221 except:
218 return False
222 return False
219
223
220 lines = block.split('\n')
224 lines = block.split('\n')
221 return (len(lines)==1 or str(lines[-1])=='')
225 return (len(lines)==1 or str(lines[-1])=='')
222
226
223
227
224 def compile_ast(self, block):
228 def compile_ast(self, block):
225 """Compile block to an AST
229 """Compile block to an AST
226
230
227 Parameters:
231 Parameters:
228 block : str
232 block : str
229
233
230 Result:
234 Result:
231 AST
235 AST
232
236
233 Throws:
237 Throws:
234 Exception if block cannot be compiled
238 Exception if block cannot be compiled
235 """
239 """
236
240
237 return compile(block, "<string>", "exec", _ast.PyCF_ONLY_AST)
241 return compile(block, "<string>", "exec", _ast.PyCF_ONLY_AST)
238
242
239
243
240 def execute(self, block, blockID=None):
244 def execute(self, block, blockID=None):
241 """Execute the block and return the result.
245 """Execute the block and return the result.
242
246
243 Parameters:
247 Parameters:
244 block : {str, AST}
248 block : {str, AST}
245 blockID : any
249 blockID : any
246 Caller may provide an ID to identify this block.
250 Caller may provide an ID to identify this block.
247 result['blockID'] := blockID
251 result['blockID'] := blockID
248
252
249 Result:
253 Result:
250 Deferred result of self.interpreter.execute
254 Deferred result of self.interpreter.execute
251 """
255 """
252
256
253 if(not self.is_complete(block)):
257 if(not self.is_complete(block)):
254 raise Exception("Block is not compilable")
258 raise Exception("Block is not compilable")
255
259
256 if(blockID == None):
260 if(blockID == None):
257 blockID = uuid.uuid4() #random UUID
261 blockID = uuid.uuid4() #random UUID
258
262
259 try:
263 try:
260 result = self.shell.execute(block)
264 result = self.shell.execute(block)
261 except Exception,e:
265 except Exception,e:
262 e = self._add_block_id_for_failure(e, blockID=blockID)
266 e = self._add_block_id_for_failure(e, blockID=blockID)
263 e = self.update_cell_prompt(e, blockID=blockID)
267 e = self.update_cell_prompt(e, blockID=blockID)
264 e = self.render_error(e)
268 e = self.render_error(e)
265 else:
269 else:
266 result = self._add_block_id_for_result(result, blockID=blockID)
270 result = self._add_block_id_for_result(result, blockID=blockID)
267 result = self.update_cell_prompt(result, blockID=blockID)
271 result = self.update_cell_prompt(result, blockID=blockID)
268 result = self.render_result(result)
272 result = self.render_result(result)
269
273
270 return result
274 return result
271
275
272
276
273 def _add_block_id_for_result(self, result, blockID):
277 def _add_block_id_for_result(self, result, blockID):
274 """Add the blockID to result or failure. Unfortunatley, we have to
278 """Add the blockID to result or failure. Unfortunatley, we have to
275 treat failures differently than result dicts.
279 treat failures differently than result dicts.
276 """
280 """
277
281
278 result['blockID'] = blockID
282 result['blockID'] = blockID
279
283
280 return result
284 return result
281
285
282 def _add_block_id_for_failure(self, failure, blockID):
286 def _add_block_id_for_failure(self, failure, blockID):
283 """_add_block_id_for_failure"""
287 """_add_block_id_for_failure"""
284 failure.blockID = blockID
288 failure.blockID = blockID
285 return failure
289 return failure
286
290
287
291
288 def _add_history(self, result, block=None):
292 def _add_history(self, result, block=None):
289 """Add block to the history"""
293 """Add block to the history"""
290
294
291 assert(block != None)
295 assert(block != None)
292 self.history.add_items([block])
296 self.history.add_items([block])
293 self.history_cursor += 1
297 self.history_cursor += 1
294
298
295 return result
299 return result
296
300
297
301
298 def get_history_previous(self, currentBlock):
302 def get_history_previous(self, current_block):
299 """ Returns previous history string and decrement history cursor.
303 """ Returns previous history string and decrement history cursor.
300 """
304 """
301 command = self.history.get_history_item(self.history_cursor - 1)
305 command = self.history.get_history_item(self.history_cursor - 1)
302
306
303 if command is not None:
307 if command is not None:
304 if(self.history_cursor == len(self.history.input_cache)):
308 if(self.history_cursor+1 == len(self.history.input_cache)):
305 self.history.input_cache[self.history_cursor] = currentBlock
309 self.history.input_cache[self.history_cursor] = current_block
306 self.history_cursor -= 1
310 self.history_cursor -= 1
307 return command
311 return command
308
312
309
313
310 def get_history_next(self):
314 def get_history_next(self):
311 """ Returns next history string and increment history cursor.
315 """ Returns next history string and increment history cursor.
312 """
316 """
313 command = self.history.get_history_item(self.history_cursor+1)
317 command = self.history.get_history_item(self.history_cursor+1)
314
318
315 if command is not None:
319 if command is not None:
316 self.history_cursor += 1
320 self.history_cursor += 1
317 return command
321 return command
318
322
319 ###
323 ###
320 # Subclasses probably want to override these methods...
324 # Subclasses probably want to override these methods...
321 ###
325 ###
322
326
323 def update_cell_prompt(self, result, blockID=None):
327 def update_cell_prompt(self, result, blockID=None):
324 """Subclass may override to update the input prompt for a block.
328 """Subclass may override to update the input prompt for a block.
329
330 This method only really makes sens in asyncrhonous frontend.
325 Since this method will be called as a
331 Since this method will be called as a
326 twisted.internet.defer.Deferred's callback, implementations should
332 twisted.internet.defer.Deferred's callback, implementations should
327 return result when finished.
333 return result when finished.
328 """
334 """
329
335
330 return result
336 raise NotImplementedError
331
337
332
338
333 def render_result(self, result):
339 def render_result(self, result):
334 """Subclasses must override to render result. Since this method will
340 """Subclasses must override to render result.
335 be called as a twisted.internet.defer.Deferred's callback,
336 implementations should return result when finished.
337 """
338
341
339 return result
342 In asynchronous frontends, this method will be called as a
340
343 twisted.internet.defer.Deferred's callback. Implementations
341
344 should thus return result when finished.
342 def render_error(self, failure):
343 """Subclasses must override to render the failure. Since this method
344 will be called as a twisted.internet.defer.Deferred's callback,
345 implementations should return result when finished.
346 """
345 """
347
346
348 return failure
347 raise NotImplementedError
349
350
351
352 class AsyncFrontEndBase(FrontEndBase):
353 """
354 Overrides FrontEndBase to wrap execute in a deferred result.
355 All callbacks are made as callbacks on the deferred result.
356 """
357
358 implements(IFrontEnd)
359 classProvides(IFrontEndFactory)
360
361 def __init__(self, engine=None, history=None):
362 assert(engine==None or IEngineCore.providedBy(engine))
363 self.engine = IEngineCore(engine)
364 if history is None:
365 self.history = FrontEndHistory(input_cache=[''])
366 else:
367 self.history = history
368
348
369
349
370 def execute(self, block, blockID=None):
350 def render_error(self, failure):
371 """Execute the block and return the deferred result.
351 """Subclasses must override to render the failure.
372
373 Parameters:
374 block : {str, AST}
375 blockID : any
376 Caller may provide an ID to identify this block.
377 result['blockID'] := blockID
378
352
379 Result:
353 In asynchronous frontends, this method will be called as a
380 Deferred result of self.interpreter.execute
354 twisted.internet.defer.Deferred's callback. Implementations
355 should thus return result when finished.
381 """
356 """
382
357
383 if(not self.is_complete(block)):
358 raise NotImplementedError
384 from twisted.python.failure import Failure
385 return Failure(Exception("Block is not compilable"))
386
387 if(blockID == None):
388 blockID = uuid.uuid4() #random UUID
389
390 d = self.engine.execute(block)
391 d.addCallback(self._add_history, block=block)
392 d.addCallback(self._add_block_id_for_result, blockID)
393 d.addErrback(self._add_block_id_for_failure, blockID)
394 d.addBoth(self.update_cell_prompt, blockID=blockID)
395 d.addCallbacks(self.render_result,
396 errback=self.render_error)
397
398 return d
399
400
359
@@ -1,151 +1,152 b''
1 # encoding: utf-8
1 # encoding: utf-8
2
2
3 """This file contains unittests for the frontendbase module."""
3 """This file contains unittests for the frontendbase module."""
4
4
5 __docformat__ = "restructuredtext en"
5 __docformat__ = "restructuredtext en"
6
6
7 #---------------------------------------------------------------------------
7 #---------------------------------------------------------------------------
8 # Copyright (C) 2008 The IPython Development Team
8 # Copyright (C) 2008 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 unittest
18 import unittest
19 from IPython.frontend import frontendbase
19 from IPython.frontend.asyncfrontendbase import AsyncFrontEndBase
20 from IPython.frontend import frontendbase
20 from IPython.kernel.engineservice import EngineService
21 from IPython.kernel.engineservice import EngineService
21
22
22 class FrontEndCallbackChecker(frontendbase.AsyncFrontEndBase):
23 class FrontEndCallbackChecker(AsyncFrontEndBase):
23 """FrontEndBase subclass for checking callbacks"""
24 """FrontEndBase subclass for checking callbacks"""
24 def __init__(self, engine=None, history=None):
25 def __init__(self, engine=None, history=None):
25 super(FrontEndCallbackChecker, self).__init__(engine=engine,
26 super(FrontEndCallbackChecker, self).__init__(engine=engine,
26 history=history)
27 history=history)
27 self.updateCalled = False
28 self.updateCalled = False
28 self.renderResultCalled = False
29 self.renderResultCalled = False
29 self.renderErrorCalled = False
30 self.renderErrorCalled = False
30
31
31 def update_cell_prompt(self, result, blockID=None):
32 def update_cell_prompt(self, result, blockID=None):
32 self.updateCalled = True
33 self.updateCalled = True
33 return result
34 return result
34
35
35 def render_result(self, result):
36 def render_result(self, result):
36 self.renderResultCalled = True
37 self.renderResultCalled = True
37 return result
38 return result
38
39
39
40
40 def render_error(self, failure):
41 def render_error(self, failure):
41 self.renderErrorCalled = True
42 self.renderErrorCalled = True
42 return failure
43 return failure
43
44
44
45
45
46
46
47
47 class TestAsyncFrontendBase(unittest.TestCase):
48 class TestAsyncFrontendBase(unittest.TestCase):
48 def setUp(self):
49 def setUp(self):
49 """Setup the EngineService and FrontEndBase"""
50 """Setup the EngineService and FrontEndBase"""
50
51
51 self.fb = FrontEndCallbackChecker(engine=EngineService())
52 self.fb = FrontEndCallbackChecker(engine=EngineService())
52
53
53
54
54 def test_implements_IFrontEnd(self):
55 def test_implements_IFrontEnd(self):
55 assert(frontendbase.IFrontEnd.implementedBy(
56 assert(frontendbase.IFrontEnd.implementedBy(
56 frontendbase.AsyncFrontEndBase))
57 AsyncFrontEndBase))
57
58
58
59
59 def test_is_complete_returns_False_for_incomplete_block(self):
60 def test_is_complete_returns_False_for_incomplete_block(self):
60 """"""
61 """"""
61
62
62 block = """def test(a):"""
63 block = """def test(a):"""
63
64
64 assert(self.fb.is_complete(block) == False)
65 assert(self.fb.is_complete(block) == False)
65
66
66 def test_is_complete_returns_True_for_complete_block(self):
67 def test_is_complete_returns_True_for_complete_block(self):
67 """"""
68 """"""
68
69
69 block = """def test(a): pass"""
70 block = """def test(a): pass"""
70
71
71 assert(self.fb.is_complete(block))
72 assert(self.fb.is_complete(block))
72
73
73 block = """a=3"""
74 block = """a=3"""
74
75
75 assert(self.fb.is_complete(block))
76 assert(self.fb.is_complete(block))
76
77
77
78
78 def test_blockID_added_to_result(self):
79 def test_blockID_added_to_result(self):
79 block = """3+3"""
80 block = """3+3"""
80
81
81 d = self.fb.execute(block, blockID='TEST_ID')
82 d = self.fb.execute(block, blockID='TEST_ID')
82
83
83 d.addCallback(self.checkBlockID, expected='TEST_ID')
84 d.addCallback(self.checkBlockID, expected='TEST_ID')
84
85
85 def test_blockID_added_to_failure(self):
86 def test_blockID_added_to_failure(self):
86 block = "raise Exception()"
87 block = "raise Exception()"
87
88
88 d = self.fb.execute(block,blockID='TEST_ID')
89 d = self.fb.execute(block,blockID='TEST_ID')
89 d.addErrback(self.checkFailureID, expected='TEST_ID')
90 d.addErrback(self.checkFailureID, expected='TEST_ID')
90
91
91 def checkBlockID(self, result, expected=""):
92 def checkBlockID(self, result, expected=""):
92 assert(result['blockID'] == expected)
93 assert(result['blockID'] == expected)
93
94
94
95
95 def checkFailureID(self, failure, expected=""):
96 def checkFailureID(self, failure, expected=""):
96 assert(failure.blockID == expected)
97 assert(failure.blockID == expected)
97
98
98
99
99 def test_callbacks_added_to_execute(self):
100 def test_callbacks_added_to_execute(self):
100 """test that
101 """test that
101 update_cell_prompt
102 update_cell_prompt
102 render_result
103 render_result
103
104
104 are added to execute request
105 are added to execute request
105 """
106 """
106
107
107 d = self.fb.execute("10+10")
108 d = self.fb.execute("10+10")
108 d.addCallback(self.checkCallbacks)
109 d.addCallback(self.checkCallbacks)
109
110
110
111
111 def checkCallbacks(self, result):
112 def checkCallbacks(self, result):
112 assert(self.fb.updateCalled)
113 assert(self.fb.updateCalled)
113 assert(self.fb.renderResultCalled)
114 assert(self.fb.renderResultCalled)
114
115
115
116
116 def test_error_callback_added_to_execute(self):
117 def test_error_callback_added_to_execute(self):
117 """test that render_error called on execution error"""
118 """test that render_error called on execution error"""
118
119
119 d = self.fb.execute("raise Exception()")
120 d = self.fb.execute("raise Exception()")
120 d.addCallback(self.checkRenderError)
121 d.addCallback(self.checkRenderError)
121
122
122 def checkRenderError(self, result):
123 def checkRenderError(self, result):
123 assert(self.fb.renderErrorCalled)
124 assert(self.fb.renderErrorCalled)
124
125
125 def test_history_returns_expected_block(self):
126 def test_history_returns_expected_block(self):
126 """Make sure history browsing doesn't fail"""
127 """Make sure history browsing doesn't fail"""
127
128
128 blocks = ["a=1","a=2","a=3"]
129 blocks = ["a=1","a=2","a=3"]
129 for b in blocks:
130 for b in blocks:
130 d = self.fb.execute(b)
131 d = self.fb.execute(b)
131
132
132 # d is now the deferred for the last executed block
133 # d is now the deferred for the last executed block
133 d.addCallback(self.historyTests, blocks)
134 d.addCallback(self.historyTests, blocks)
134
135
135
136
136 def historyTests(self, result, blocks):
137 def historyTests(self, result, blocks):
137 """historyTests"""
138 """historyTests"""
138
139
139 assert(len(blocks) >= 3)
140 assert(len(blocks) >= 3)
140 assert(self.fb.get_history_previous("") == blocks[-2])
141 assert(self.fb.get_history_previous("") == blocks[-2])
141 assert(self.fb.get_history_previous("") == blocks[-3])
142 assert(self.fb.get_history_previous("") == blocks[-3])
142 assert(self.fb.get_history_next() == blocks[-2])
143 assert(self.fb.get_history_next() == blocks[-2])
143
144
144
145
145 def test_history_returns_none_at_startup(self):
146 def test_history_returns_none_at_startup(self):
146 """test_history_returns_none_at_startup"""
147 """test_history_returns_none_at_startup"""
147
148
148 assert(self.fb.get_history_previous("")==None)
149 assert(self.fb.get_history_previous("")==None)
149 assert(self.fb.get_history_next()==None)
150 assert(self.fb.get_history_next()==None)
150
151
151
152
@@ -1,2681 +1,2686 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 IPython -- An enhanced Interactive Python
4
4
5 Requires Python 2.3 or newer.
5 Requires Python 2.3 or newer.
6
6
7 This file contains all the classes and helper functions specific to IPython.
7 This file contains all the classes and helper functions specific to IPython.
8
8
9 """
9 """
10
10
11 #*****************************************************************************
11 #*****************************************************************************
12 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
12 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
13 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
17 #
17 #
18 # Note: this code originally subclassed code.InteractiveConsole from the
18 # Note: this code originally subclassed code.InteractiveConsole from the
19 # Python standard library. Over time, all of that class has been copied
19 # Python standard library. Over time, all of that class has been copied
20 # verbatim here for modifications which could not be accomplished by
20 # verbatim here for modifications which could not be accomplished by
21 # subclassing. At this point, there are no dependencies at all on the code
21 # subclassing. At this point, there are no dependencies at all on the code
22 # module anymore (it is not even imported). The Python License (sec. 2)
22 # module anymore (it is not even imported). The Python License (sec. 2)
23 # allows for this, but it's always nice to acknowledge credit where credit is
23 # allows for this, but it's always nice to acknowledge credit where credit is
24 # due.
24 # due.
25 #*****************************************************************************
25 #*****************************************************************************
26
26
27 #****************************************************************************
27 #****************************************************************************
28 # Modules and globals
28 # Modules and globals
29
29
30 from IPython import Release
30 from IPython import Release
31 __author__ = '%s <%s>\n%s <%s>' % \
31 __author__ = '%s <%s>\n%s <%s>' % \
32 ( Release.authors['Janko'] + Release.authors['Fernando'] )
32 ( Release.authors['Janko'] + Release.authors['Fernando'] )
33 __license__ = Release.license
33 __license__ = Release.license
34 __version__ = Release.version
34 __version__ = Release.version
35
35
36 # Python standard modules
36 # Python standard modules
37 import __main__
37 import __main__
38 import __builtin__
38 import __builtin__
39 import StringIO
39 import StringIO
40 import bdb
40 import bdb
41 import cPickle as pickle
41 import cPickle as pickle
42 import codeop
42 import codeop
43 import exceptions
43 import exceptions
44 import glob
44 import glob
45 import inspect
45 import inspect
46 import keyword
46 import keyword
47 import new
47 import new
48 import os
48 import os
49 import pydoc
49 import pydoc
50 import re
50 import re
51 import shutil
51 import shutil
52 import string
52 import string
53 import sys
53 import sys
54 import tempfile
54 import tempfile
55 import traceback
55 import traceback
56 import types
56 import types
57 import warnings
57 import warnings
58 warnings.filterwarnings('ignore', r'.*sets module*')
58 warnings.filterwarnings('ignore', r'.*sets module*')
59 from sets import Set
59 from sets import Set
60 from pprint import pprint, pformat
60 from pprint import pprint, pformat
61
61
62 # IPython's own modules
62 # IPython's own modules
63 #import IPython
63 #import IPython
64 from IPython import Debugger,OInspect,PyColorize,ultraTB
64 from IPython import Debugger,OInspect,PyColorize,ultraTB
65 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
65 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
66 from IPython.Extensions import pickleshare
66 from IPython.Extensions import pickleshare
67 from IPython.FakeModule import FakeModule
67 from IPython.FakeModule import FakeModule
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 from IPython.Logger import Logger
69 from IPython.Logger import Logger
70 from IPython.Magic import Magic
70 from IPython.Magic import Magic
71 from IPython.Prompts import CachedOutput
71 from IPython.Prompts import CachedOutput
72 from IPython.ipstruct import Struct
72 from IPython.ipstruct import Struct
73 from IPython.background_jobs import BackgroundJobManager
73 from IPython.background_jobs import BackgroundJobManager
74 from IPython.usage import cmd_line_usage,interactive_usage
74 from IPython.usage import cmd_line_usage,interactive_usage
75 from IPython.genutils import *
75 from IPython.genutils import *
76 from IPython.strdispatch import StrDispatch
76 from IPython.strdispatch import StrDispatch
77 import IPython.ipapi
77 import IPython.ipapi
78 import IPython.history
78 import IPython.history
79 import IPython.prefilter as prefilter
79 import IPython.prefilter as prefilter
80 import IPython.shadowns
80 import IPython.shadowns
81 # Globals
81 # Globals
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 # compiled regexps for autoindent management
87 # compiled regexps for autoindent management
88 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
88 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
89
89
90
90
91 #****************************************************************************
91 #****************************************************************************
92 # Some utility function definitions
92 # Some utility function definitions
93
93
94 ini_spaces_re = re.compile(r'^(\s+)')
94 ini_spaces_re = re.compile(r'^(\s+)')
95
95
96 def num_ini_spaces(strng):
96 def num_ini_spaces(strng):
97 """Return the number of initial spaces in a string"""
97 """Return the number of initial spaces in a string"""
98
98
99 ini_spaces = ini_spaces_re.match(strng)
99 ini_spaces = ini_spaces_re.match(strng)
100 if ini_spaces:
100 if ini_spaces:
101 return ini_spaces.end()
101 return ini_spaces.end()
102 else:
102 else:
103 return 0
103 return 0
104
104
105 def softspace(file, newvalue):
105 def softspace(file, newvalue):
106 """Copied from code.py, to remove the dependency"""
106 """Copied from code.py, to remove the dependency"""
107
107
108 oldvalue = 0
108 oldvalue = 0
109 try:
109 try:
110 oldvalue = file.softspace
110 oldvalue = file.softspace
111 except AttributeError:
111 except AttributeError:
112 pass
112 pass
113 try:
113 try:
114 file.softspace = newvalue
114 file.softspace = newvalue
115 except (AttributeError, TypeError):
115 except (AttributeError, TypeError):
116 # "attribute-less object" or "read-only attributes"
116 # "attribute-less object" or "read-only attributes"
117 pass
117 pass
118 return oldvalue
118 return oldvalue
119
119
120
120
121 #****************************************************************************
121 #****************************************************************************
122 # Local use exceptions
122 # Local use exceptions
123 class SpaceInInput(exceptions.Exception): pass
123 class SpaceInInput(exceptions.Exception): pass
124
124
125
125
126 #****************************************************************************
126 #****************************************************************************
127 # Local use classes
127 # Local use classes
128 class Bunch: pass
128 class Bunch: pass
129
129
130 class Undefined: pass
130 class Undefined: pass
131
131
132 class Quitter(object):
132 class Quitter(object):
133 """Simple class to handle exit, similar to Python 2.5's.
133 """Simple class to handle exit, similar to Python 2.5's.
134
134
135 It handles exiting in an ipython-safe manner, which the one in Python 2.5
135 It handles exiting in an ipython-safe manner, which the one in Python 2.5
136 doesn't do (obviously, since it doesn't know about ipython)."""
136 doesn't do (obviously, since it doesn't know about ipython)."""
137
137
138 def __init__(self,shell,name):
138 def __init__(self,shell,name):
139 self.shell = shell
139 self.shell = shell
140 self.name = name
140 self.name = name
141
141
142 def __repr__(self):
142 def __repr__(self):
143 return 'Type %s() to exit.' % self.name
143 return 'Type %s() to exit.' % self.name
144 __str__ = __repr__
144 __str__ = __repr__
145
145
146 def __call__(self):
146 def __call__(self):
147 self.shell.exit()
147 self.shell.exit()
148
148
149 class InputList(list):
149 class InputList(list):
150 """Class to store user input.
150 """Class to store user input.
151
151
152 It's basically a list, but slices return a string instead of a list, thus
152 It's basically a list, but slices return a string instead of a list, thus
153 allowing things like (assuming 'In' is an instance):
153 allowing things like (assuming 'In' is an instance):
154
154
155 exec In[4:7]
155 exec In[4:7]
156
156
157 or
157 or
158
158
159 exec In[5:9] + In[14] + In[21:25]"""
159 exec In[5:9] + In[14] + In[21:25]"""
160
160
161 def __getslice__(self,i,j):
161 def __getslice__(self,i,j):
162 return ''.join(list.__getslice__(self,i,j))
162 return ''.join(list.__getslice__(self,i,j))
163
163
164 class SyntaxTB(ultraTB.ListTB):
164 class SyntaxTB(ultraTB.ListTB):
165 """Extension which holds some state: the last exception value"""
165 """Extension which holds some state: the last exception value"""
166
166
167 def __init__(self,color_scheme = 'NoColor'):
167 def __init__(self,color_scheme = 'NoColor'):
168 ultraTB.ListTB.__init__(self,color_scheme)
168 ultraTB.ListTB.__init__(self,color_scheme)
169 self.last_syntax_error = None
169 self.last_syntax_error = None
170
170
171 def __call__(self, etype, value, elist):
171 def __call__(self, etype, value, elist):
172 self.last_syntax_error = value
172 self.last_syntax_error = value
173 ultraTB.ListTB.__call__(self,etype,value,elist)
173 ultraTB.ListTB.__call__(self,etype,value,elist)
174
174
175 def clear_err_state(self):
175 def clear_err_state(self):
176 """Return the current error state and clear it"""
176 """Return the current error state and clear it"""
177 e = self.last_syntax_error
177 e = self.last_syntax_error
178 self.last_syntax_error = None
178 self.last_syntax_error = None
179 return e
179 return e
180
180
181 #****************************************************************************
181 #****************************************************************************
182 # Main IPython class
182 # Main IPython class
183
183
184 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
184 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
185 # until a full rewrite is made. I've cleaned all cross-class uses of
185 # until a full rewrite is made. I've cleaned all cross-class uses of
186 # attributes and methods, but too much user code out there relies on the
186 # attributes and methods, but too much user code out there relies on the
187 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
187 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
188 #
188 #
189 # But at least now, all the pieces have been separated and we could, in
189 # But at least now, all the pieces have been separated and we could, in
190 # principle, stop using the mixin. This will ease the transition to the
190 # principle, stop using the mixin. This will ease the transition to the
191 # chainsaw branch.
191 # chainsaw branch.
192
192
193 # For reference, the following is the list of 'self.foo' uses in the Magic
193 # For reference, the following is the list of 'self.foo' uses in the Magic
194 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
194 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
195 # class, to prevent clashes.
195 # class, to prevent clashes.
196
196
197 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
197 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
198 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
198 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
199 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
199 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
200 # 'self.value']
200 # 'self.value']
201
201
202 class InteractiveShell(object,Magic):
202 class InteractiveShell(object,Magic):
203 """An enhanced console for Python."""
203 """An enhanced console for Python."""
204
204
205 # class attribute to indicate whether the class supports threads or not.
205 # class attribute to indicate whether the class supports threads or not.
206 # Subclasses with thread support should override this as needed.
206 # Subclasses with thread support should override this as needed.
207 isthreaded = False
207 isthreaded = False
208
208
209 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
209 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
210 user_ns=None,user_global_ns=None,banner2='',
210 user_ns=None,user_global_ns=None,banner2='',
211 custom_exceptions=((),None),embedded=False):
211 custom_exceptions=((),None),embedded=False):
212
212
213 # log system
213 # log system
214 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
214 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
215
215
216 # Job manager (for jobs run as background threads)
216 # Job manager (for jobs run as background threads)
217 self.jobs = BackgroundJobManager()
217 self.jobs = BackgroundJobManager()
218
218
219 # Store the actual shell's name
219 # Store the actual shell's name
220 self.name = name
220 self.name = name
221 self.more = False
221 self.more = False
222
222
223 # We need to know whether the instance is meant for embedding, since
223 # We need to know whether the instance is meant for embedding, since
224 # global/local namespaces need to be handled differently in that case
224 # global/local namespaces need to be handled differently in that case
225 self.embedded = embedded
225 self.embedded = embedded
226 if embedded:
226 if embedded:
227 # Control variable so users can, from within the embedded instance,
227 # Control variable so users can, from within the embedded instance,
228 # permanently deactivate it.
228 # permanently deactivate it.
229 self.embedded_active = True
229 self.embedded_active = True
230
230
231 # command compiler
231 # command compiler
232 self.compile = codeop.CommandCompiler()
232 self.compile = codeop.CommandCompiler()
233
233
234 # User input buffer
234 # User input buffer
235 self.buffer = []
235 self.buffer = []
236
236
237 # Default name given in compilation of code
237 # Default name given in compilation of code
238 self.filename = '<ipython console>'
238 self.filename = '<ipython console>'
239
239
240 # Install our own quitter instead of the builtins. For python2.3-2.4,
240 # Install our own quitter instead of the builtins. For python2.3-2.4,
241 # this brings in behavior like 2.5, and for 2.5 it's identical.
241 # this brings in behavior like 2.5, and for 2.5 it's identical.
242 __builtin__.exit = Quitter(self,'exit')
242 __builtin__.exit = Quitter(self,'exit')
243 __builtin__.quit = Quitter(self,'quit')
243 __builtin__.quit = Quitter(self,'quit')
244
244
245 # Make an empty namespace, which extension writers can rely on both
245 # Make an empty namespace, which extension writers can rely on both
246 # existing and NEVER being used by ipython itself. This gives them a
246 # existing and NEVER being used by ipython itself. This gives them a
247 # convenient location for storing additional information and state
247 # convenient location for storing additional information and state
248 # their extensions may require, without fear of collisions with other
248 # their extensions may require, without fear of collisions with other
249 # ipython names that may develop later.
249 # ipython names that may develop later.
250 self.meta = Struct()
250 self.meta = Struct()
251
251
252 # Create the namespace where the user will operate. user_ns is
252 # Create the namespace where the user will operate. user_ns is
253 # normally the only one used, and it is passed to the exec calls as
253 # normally the only one used, and it is passed to the exec calls as
254 # the locals argument. But we do carry a user_global_ns namespace
254 # the locals argument. But we do carry a user_global_ns namespace
255 # given as the exec 'globals' argument, This is useful in embedding
255 # given as the exec 'globals' argument, This is useful in embedding
256 # situations where the ipython shell opens in a context where the
256 # situations where the ipython shell opens in a context where the
257 # distinction between locals and globals is meaningful. For
257 # distinction between locals and globals is meaningful. For
258 # non-embedded contexts, it is just the same object as the user_ns dict.
258 # non-embedded contexts, it is just the same object as the user_ns dict.
259
259
260 # FIXME. For some strange reason, __builtins__ is showing up at user
260 # FIXME. For some strange reason, __builtins__ is showing up at user
261 # level as a dict instead of a module. This is a manual fix, but I
261 # level as a dict instead of a module. This is a manual fix, but I
262 # should really track down where the problem is coming from. Alex
262 # should really track down where the problem is coming from. Alex
263 # Schmolck reported this problem first.
263 # Schmolck reported this problem first.
264
264
265 # A useful post by Alex Martelli on this topic:
265 # A useful post by Alex Martelli on this topic:
266 # Re: inconsistent value from __builtins__
266 # Re: inconsistent value from __builtins__
267 # Von: Alex Martelli <aleaxit@yahoo.com>
267 # Von: Alex Martelli <aleaxit@yahoo.com>
268 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
268 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
269 # Gruppen: comp.lang.python
269 # Gruppen: comp.lang.python
270
270
271 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
271 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
272 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
272 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
273 # > <type 'dict'>
273 # > <type 'dict'>
274 # > >>> print type(__builtins__)
274 # > >>> print type(__builtins__)
275 # > <type 'module'>
275 # > <type 'module'>
276 # > Is this difference in return value intentional?
276 # > Is this difference in return value intentional?
277
277
278 # Well, it's documented that '__builtins__' can be either a dictionary
278 # Well, it's documented that '__builtins__' can be either a dictionary
279 # or a module, and it's been that way for a long time. Whether it's
279 # or a module, and it's been that way for a long time. Whether it's
280 # intentional (or sensible), I don't know. In any case, the idea is
280 # intentional (or sensible), I don't know. In any case, the idea is
281 # that if you need to access the built-in namespace directly, you
281 # that if you need to access the built-in namespace directly, you
282 # should start with "import __builtin__" (note, no 's') which will
282 # should start with "import __builtin__" (note, no 's') which will
283 # definitely give you a module. Yeah, it's somewhat confusing:-(.
283 # definitely give you a module. Yeah, it's somewhat confusing:-(.
284
284
285 # These routines return properly built dicts as needed by the rest of
285 # These routines return properly built dicts as needed by the rest of
286 # the code, and can also be used by extension writers to generate
286 # the code, and can also be used by extension writers to generate
287 # properly initialized namespaces.
287 # properly initialized namespaces.
288 user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns,
288 user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns,
289 user_global_ns)
289 user_global_ns)
290
290
291 # Assign namespaces
291 # Assign namespaces
292 # This is the namespace where all normal user variables live
292 # This is the namespace where all normal user variables live
293 self.user_ns = user_ns
293 self.user_ns = user_ns
294 self.user_global_ns = user_global_ns
294 self.user_global_ns = user_global_ns
295 # A namespace to keep track of internal data structures to prevent
295 # A namespace to keep track of internal data structures to prevent
296 # them from cluttering user-visible stuff. Will be updated later
296 # them from cluttering user-visible stuff. Will be updated later
297 self.internal_ns = {}
297 self.internal_ns = {}
298
298
299 # Namespace of system aliases. Each entry in the alias
299 # Namespace of system aliases. Each entry in the alias
300 # table must be a 2-tuple of the form (N,name), where N is the number
300 # table must be a 2-tuple of the form (N,name), where N is the number
301 # of positional arguments of the alias.
301 # of positional arguments of the alias.
302 self.alias_table = {}
302 self.alias_table = {}
303
303
304 # A table holding all the namespaces IPython deals with, so that
304 # A table holding all the namespaces IPython deals with, so that
305 # introspection facilities can search easily.
305 # introspection facilities can search easily.
306 self.ns_table = {'user':user_ns,
306 self.ns_table = {'user':user_ns,
307 'user_global':user_global_ns,
307 'user_global':user_global_ns,
308 'alias':self.alias_table,
308 'alias':self.alias_table,
309 'internal':self.internal_ns,
309 'internal':self.internal_ns,
310 'builtin':__builtin__.__dict__
310 'builtin':__builtin__.__dict__
311 }
311 }
312 # The user namespace MUST have a pointer to the shell itself.
312 # The user namespace MUST have a pointer to the shell itself.
313 self.user_ns[name] = self
313 self.user_ns[name] = self
314
314
315 # We need to insert into sys.modules something that looks like a
315 # We need to insert into sys.modules something that looks like a
316 # module but which accesses the IPython namespace, for shelve and
316 # module but which accesses the IPython namespace, for shelve and
317 # pickle to work interactively. Normally they rely on getting
317 # pickle to work interactively. Normally they rely on getting
318 # everything out of __main__, but for embedding purposes each IPython
318 # everything out of __main__, but for embedding purposes each IPython
319 # instance has its own private namespace, so we can't go shoving
319 # instance has its own private namespace, so we can't go shoving
320 # everything into __main__.
320 # everything into __main__.
321
321
322 # note, however, that we should only do this for non-embedded
322 # note, however, that we should only do this for non-embedded
323 # ipythons, which really mimic the __main__.__dict__ with their own
323 # ipythons, which really mimic the __main__.__dict__ with their own
324 # namespace. Embedded instances, on the other hand, should not do
324 # namespace. Embedded instances, on the other hand, should not do
325 # this because they need to manage the user local/global namespaces
325 # this because they need to manage the user local/global namespaces
326 # only, but they live within a 'normal' __main__ (meaning, they
326 # only, but they live within a 'normal' __main__ (meaning, they
327 # shouldn't overtake the execution environment of the script they're
327 # shouldn't overtake the execution environment of the script they're
328 # embedded in).
328 # embedded in).
329
329
330 if not embedded:
330 if not embedded:
331 try:
331 try:
332 main_name = self.user_ns['__name__']
332 main_name = self.user_ns['__name__']
333 except KeyError:
333 except KeyError:
334 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
334 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
335 else:
335 else:
336 #print "pickle hack in place" # dbg
336 #print "pickle hack in place" # dbg
337 #print 'main_name:',main_name # dbg
337 #print 'main_name:',main_name # dbg
338 sys.modules[main_name] = FakeModule(self.user_ns)
338 sys.modules[main_name] = FakeModule(self.user_ns)
339
339
340 # Now that FakeModule produces a real module, we've run into a nasty
340 # Now that FakeModule produces a real module, we've run into a nasty
341 # problem: after script execution (via %run), the module where the user
341 # problem: after script execution (via %run), the module where the user
342 # code ran is deleted. Now that this object is a true module (needed
342 # code ran is deleted. Now that this object is a true module (needed
343 # so docetst and other tools work correctly), the Python module
343 # so docetst and other tools work correctly), the Python module
344 # teardown mechanism runs over it, and sets to None every variable
344 # teardown mechanism runs over it, and sets to None every variable
345 # present in that module. This means that later calls to functions
345 # present in that module. This means that later calls to functions
346 # defined in the script (which have become interactively visible after
346 # defined in the script (which have become interactively visible after
347 # script exit) fail, because they hold references to objects that have
347 # script exit) fail, because they hold references to objects that have
348 # become overwritten into None. The only solution I see right now is
348 # become overwritten into None. The only solution I see right now is
349 # to protect every FakeModule used by %run by holding an internal
349 # to protect every FakeModule used by %run by holding an internal
350 # reference to it. This private list will be used for that. The
350 # reference to it. This private list will be used for that. The
351 # %reset command will flush it as well.
351 # %reset command will flush it as well.
352 self._user_main_modules = []
352 self._user_main_modules = []
353
353
354 # List of input with multi-line handling.
354 # List of input with multi-line handling.
355 # Fill its zero entry, user counter starts at 1
355 # Fill its zero entry, user counter starts at 1
356 self.input_hist = InputList(['\n'])
356 self.input_hist = InputList(['\n'])
357 # This one will hold the 'raw' input history, without any
357 # This one will hold the 'raw' input history, without any
358 # pre-processing. This will allow users to retrieve the input just as
358 # pre-processing. This will allow users to retrieve the input just as
359 # it was exactly typed in by the user, with %hist -r.
359 # it was exactly typed in by the user, with %hist -r.
360 self.input_hist_raw = InputList(['\n'])
360 self.input_hist_raw = InputList(['\n'])
361
361
362 # list of visited directories
362 # list of visited directories
363 try:
363 try:
364 self.dir_hist = [os.getcwd()]
364 self.dir_hist = [os.getcwd()]
365 except OSError:
365 except OSError:
366 self.dir_hist = []
366 self.dir_hist = []
367
367
368 # dict of output history
368 # dict of output history
369 self.output_hist = {}
369 self.output_hist = {}
370
370
371 # Get system encoding at startup time. Certain terminals (like Emacs
371 # Get system encoding at startup time. Certain terminals (like Emacs
372 # under Win32 have it set to None, and we need to have a known valid
372 # under Win32 have it set to None, and we need to have a known valid
373 # encoding to use in the raw_input() method
373 # encoding to use in the raw_input() method
374 try:
374 try:
375 self.stdin_encoding = sys.stdin.encoding or 'ascii'
375 self.stdin_encoding = sys.stdin.encoding or 'ascii'
376 except AttributeError:
376 except AttributeError:
377 self.stdin_encoding = 'ascii'
377 self.stdin_encoding = 'ascii'
378
378
379 # dict of things NOT to alias (keywords, builtins and some magics)
379 # dict of things NOT to alias (keywords, builtins and some magics)
380 no_alias = {}
380 no_alias = {}
381 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
381 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
382 for key in keyword.kwlist + no_alias_magics:
382 for key in keyword.kwlist + no_alias_magics:
383 no_alias[key] = 1
383 no_alias[key] = 1
384 no_alias.update(__builtin__.__dict__)
384 no_alias.update(__builtin__.__dict__)
385 self.no_alias = no_alias
385 self.no_alias = no_alias
386
386
387 # make global variables for user access to these
387 # make global variables for user access to these
388 self.user_ns['_ih'] = self.input_hist
388 self.user_ns['_ih'] = self.input_hist
389 self.user_ns['_oh'] = self.output_hist
389 self.user_ns['_oh'] = self.output_hist
390 self.user_ns['_dh'] = self.dir_hist
390 self.user_ns['_dh'] = self.dir_hist
391
391
392 # user aliases to input and output histories
392 # user aliases to input and output histories
393 self.user_ns['In'] = self.input_hist
393 self.user_ns['In'] = self.input_hist
394 self.user_ns['Out'] = self.output_hist
394 self.user_ns['Out'] = self.output_hist
395
395
396 self.user_ns['_sh'] = IPython.shadowns
396 self.user_ns['_sh'] = IPython.shadowns
397 # Object variable to store code object waiting execution. This is
397 # Object variable to store code object waiting execution. This is
398 # used mainly by the multithreaded shells, but it can come in handy in
398 # used mainly by the multithreaded shells, but it can come in handy in
399 # other situations. No need to use a Queue here, since it's a single
399 # other situations. No need to use a Queue here, since it's a single
400 # item which gets cleared once run.
400 # item which gets cleared once run.
401 self.code_to_run = None
401 self.code_to_run = None
402
402
403 # escapes for automatic behavior on the command line
403 # escapes for automatic behavior on the command line
404 self.ESC_SHELL = '!'
404 self.ESC_SHELL = '!'
405 self.ESC_SH_CAP = '!!'
405 self.ESC_SH_CAP = '!!'
406 self.ESC_HELP = '?'
406 self.ESC_HELP = '?'
407 self.ESC_MAGIC = '%'
407 self.ESC_MAGIC = '%'
408 self.ESC_QUOTE = ','
408 self.ESC_QUOTE = ','
409 self.ESC_QUOTE2 = ';'
409 self.ESC_QUOTE2 = ';'
410 self.ESC_PAREN = '/'
410 self.ESC_PAREN = '/'
411
411
412 # And their associated handlers
412 # And their associated handlers
413 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
413 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
414 self.ESC_QUOTE : self.handle_auto,
414 self.ESC_QUOTE : self.handle_auto,
415 self.ESC_QUOTE2 : self.handle_auto,
415 self.ESC_QUOTE2 : self.handle_auto,
416 self.ESC_MAGIC : self.handle_magic,
416 self.ESC_MAGIC : self.handle_magic,
417 self.ESC_HELP : self.handle_help,
417 self.ESC_HELP : self.handle_help,
418 self.ESC_SHELL : self.handle_shell_escape,
418 self.ESC_SHELL : self.handle_shell_escape,
419 self.ESC_SH_CAP : self.handle_shell_escape,
419 self.ESC_SH_CAP : self.handle_shell_escape,
420 }
420 }
421
421
422 # class initializations
422 # class initializations
423 Magic.__init__(self,self)
423 Magic.__init__(self,self)
424
424
425 # Python source parser/formatter for syntax highlighting
425 # Python source parser/formatter for syntax highlighting
426 pyformat = PyColorize.Parser().format
426 pyformat = PyColorize.Parser().format
427 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
427 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
428
428
429 # hooks holds pointers used for user-side customizations
429 # hooks holds pointers used for user-side customizations
430 self.hooks = Struct()
430 self.hooks = Struct()
431
431
432 self.strdispatchers = {}
432 self.strdispatchers = {}
433
433
434 # Set all default hooks, defined in the IPython.hooks module.
434 # Set all default hooks, defined in the IPython.hooks module.
435 hooks = IPython.hooks
435 hooks = IPython.hooks
436 for hook_name in hooks.__all__:
436 for hook_name in hooks.__all__:
437 # default hooks have priority 100, i.e. low; user hooks should have
437 # default hooks have priority 100, i.e. low; user hooks should have
438 # 0-100 priority
438 # 0-100 priority
439 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
439 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
440 #print "bound hook",hook_name
440 #print "bound hook",hook_name
441
441
442 # Flag to mark unconditional exit
442 # Flag to mark unconditional exit
443 self.exit_now = False
443 self.exit_now = False
444
444
445 self.usage_min = """\
445 self.usage_min = """\
446 An enhanced console for Python.
446 An enhanced console for Python.
447 Some of its features are:
447 Some of its features are:
448 - Readline support if the readline library is present.
448 - Readline support if the readline library is present.
449 - Tab completion in the local namespace.
449 - Tab completion in the local namespace.
450 - Logging of input, see command-line options.
450 - Logging of input, see command-line options.
451 - System shell escape via ! , eg !ls.
451 - System shell escape via ! , eg !ls.
452 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
452 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
453 - Keeps track of locally defined variables via %who, %whos.
453 - Keeps track of locally defined variables via %who, %whos.
454 - Show object information with a ? eg ?x or x? (use ?? for more info).
454 - Show object information with a ? eg ?x or x? (use ?? for more info).
455 """
455 """
456 if usage: self.usage = usage
456 if usage: self.usage = usage
457 else: self.usage = self.usage_min
457 else: self.usage = self.usage_min
458
458
459 # Storage
459 # Storage
460 self.rc = rc # This will hold all configuration information
460 self.rc = rc # This will hold all configuration information
461 self.pager = 'less'
461 self.pager = 'less'
462 # temporary files used for various purposes. Deleted at exit.
462 # temporary files used for various purposes. Deleted at exit.
463 self.tempfiles = []
463 self.tempfiles = []
464
464
465 # Keep track of readline usage (later set by init_readline)
465 # Keep track of readline usage (later set by init_readline)
466 self.has_readline = False
466 self.has_readline = False
467
467
468 # template for logfile headers. It gets resolved at runtime by the
468 # template for logfile headers. It gets resolved at runtime by the
469 # logstart method.
469 # logstart method.
470 self.loghead_tpl = \
470 self.loghead_tpl = \
471 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
471 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
472 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
472 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
473 #log# opts = %s
473 #log# opts = %s
474 #log# args = %s
474 #log# args = %s
475 #log# It is safe to make manual edits below here.
475 #log# It is safe to make manual edits below here.
476 #log#-----------------------------------------------------------------------
476 #log#-----------------------------------------------------------------------
477 """
477 """
478 # for pushd/popd management
478 # for pushd/popd management
479 try:
479 try:
480 self.home_dir = get_home_dir()
480 self.home_dir = get_home_dir()
481 except HomeDirError,msg:
481 except HomeDirError,msg:
482 fatal(msg)
482 fatal(msg)
483
483
484 self.dir_stack = []
484 self.dir_stack = []
485
485
486 # Functions to call the underlying shell.
486 # Functions to call the underlying shell.
487
487
488 # The first is similar to os.system, but it doesn't return a value,
488 # The first is similar to os.system, but it doesn't return a value,
489 # and it allows interpolation of variables in the user's namespace.
489 # and it allows interpolation of variables in the user's namespace.
490 self.system = lambda cmd: \
490 self.system = lambda cmd: \
491 self.hooks.shell_hook(self.var_expand(cmd,depth=2))
491 self.hooks.shell_hook(self.var_expand(cmd,depth=2))
492
492
493 # These are for getoutput and getoutputerror:
493 # These are for getoutput and getoutputerror:
494 self.getoutput = lambda cmd: \
494 self.getoutput = lambda cmd: \
495 getoutput(self.var_expand(cmd,depth=2),
495 getoutput(self.var_expand(cmd,depth=2),
496 header=self.rc.system_header,
496 header=self.rc.system_header,
497 verbose=self.rc.system_verbose)
497 verbose=self.rc.system_verbose)
498
498
499 self.getoutputerror = lambda cmd: \
499 self.getoutputerror = lambda cmd: \
500 getoutputerror(self.var_expand(cmd,depth=2),
500 getoutputerror(self.var_expand(cmd,depth=2),
501 header=self.rc.system_header,
501 header=self.rc.system_header,
502 verbose=self.rc.system_verbose)
502 verbose=self.rc.system_verbose)
503
503
504
504
505 # keep track of where we started running (mainly for crash post-mortem)
505 # keep track of where we started running (mainly for crash post-mortem)
506 self.starting_dir = os.getcwd()
506 self.starting_dir = os.getcwd()
507
507
508 # Various switches which can be set
508 # Various switches which can be set
509 self.CACHELENGTH = 5000 # this is cheap, it's just text
509 self.CACHELENGTH = 5000 # this is cheap, it's just text
510 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
510 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
511 self.banner2 = banner2
511 self.banner2 = banner2
512
512
513 # TraceBack handlers:
513 # TraceBack handlers:
514
514
515 # Syntax error handler.
515 # Syntax error handler.
516 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
516 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
517
517
518 # The interactive one is initialized with an offset, meaning we always
518 # The interactive one is initialized with an offset, meaning we always
519 # want to remove the topmost item in the traceback, which is our own
519 # want to remove the topmost item in the traceback, which is our own
520 # internal code. Valid modes: ['Plain','Context','Verbose']
520 # internal code. Valid modes: ['Plain','Context','Verbose']
521 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
521 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
522 color_scheme='NoColor',
522 color_scheme='NoColor',
523 tb_offset = 1)
523 tb_offset = 1)
524
524
525 # IPython itself shouldn't crash. This will produce a detailed
525 # IPython itself shouldn't crash. This will produce a detailed
526 # post-mortem if it does. But we only install the crash handler for
526 # post-mortem if it does. But we only install the crash handler for
527 # non-threaded shells, the threaded ones use a normal verbose reporter
527 # non-threaded shells, the threaded ones use a normal verbose reporter
528 # and lose the crash handler. This is because exceptions in the main
528 # and lose the crash handler. This is because exceptions in the main
529 # thread (such as in GUI code) propagate directly to sys.excepthook,
529 # thread (such as in GUI code) propagate directly to sys.excepthook,
530 # and there's no point in printing crash dumps for every user exception.
530 # and there's no point in printing crash dumps for every user exception.
531 if self.isthreaded:
531 if self.isthreaded:
532 ipCrashHandler = ultraTB.FormattedTB()
532 ipCrashHandler = ultraTB.FormattedTB()
533 else:
533 else:
534 from IPython import CrashHandler
534 from IPython import CrashHandler
535 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
535 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
536 self.set_crash_handler(ipCrashHandler)
536 self.set_crash_handler(ipCrashHandler)
537
537
538 # and add any custom exception handlers the user may have specified
538 # and add any custom exception handlers the user may have specified
539 self.set_custom_exc(*custom_exceptions)
539 self.set_custom_exc(*custom_exceptions)
540
540
541 # indentation management
541 # indentation management
542 self.autoindent = False
542 self.autoindent = False
543 self.indent_current_nsp = 0
543 self.indent_current_nsp = 0
544
544
545 # Make some aliases automatically
545 # Make some aliases automatically
546 # Prepare list of shell aliases to auto-define
546 # Prepare list of shell aliases to auto-define
547 if os.name == 'posix':
547 if os.name == 'posix':
548 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
548 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
549 'mv mv -i','rm rm -i','cp cp -i',
549 'mv mv -i','rm rm -i','cp cp -i',
550 'cat cat','less less','clear clear',
550 'cat cat','less less','clear clear',
551 # a better ls
551 # a better ls
552 'ls ls -F',
552 'ls ls -F',
553 # long ls
553 # long ls
554 'll ls -lF')
554 'll ls -lF')
555 # Extra ls aliases with color, which need special treatment on BSD
555 # Extra ls aliases with color, which need special treatment on BSD
556 # variants
556 # variants
557 ls_extra = ( # color ls
557 ls_extra = ( # color ls
558 'lc ls -F -o --color',
558 'lc ls -F -o --color',
559 # ls normal files only
559 # ls normal files only
560 'lf ls -F -o --color %l | grep ^-',
560 'lf ls -F -o --color %l | grep ^-',
561 # ls symbolic links
561 # ls symbolic links
562 'lk ls -F -o --color %l | grep ^l',
562 'lk ls -F -o --color %l | grep ^l',
563 # directories or links to directories,
563 # directories or links to directories,
564 'ldir ls -F -o --color %l | grep /$',
564 'ldir ls -F -o --color %l | grep /$',
565 # things which are executable
565 # things which are executable
566 'lx ls -F -o --color %l | grep ^-..x',
566 'lx ls -F -o --color %l | grep ^-..x',
567 )
567 )
568 # The BSDs don't ship GNU ls, so they don't understand the
568 # The BSDs don't ship GNU ls, so they don't understand the
569 # --color switch out of the box
569 # --color switch out of the box
570 if 'bsd' in sys.platform:
570 if 'bsd' in sys.platform:
571 ls_extra = ( # ls normal files only
571 ls_extra = ( # ls normal files only
572 'lf ls -lF | grep ^-',
572 'lf ls -lF | grep ^-',
573 # ls symbolic links
573 # ls symbolic links
574 'lk ls -lF | grep ^l',
574 'lk ls -lF | grep ^l',
575 # directories or links to directories,
575 # directories or links to directories,
576 'ldir ls -lF | grep /$',
576 'ldir ls -lF | grep /$',
577 # things which are executable
577 # things which are executable
578 'lx ls -lF | grep ^-..x',
578 'lx ls -lF | grep ^-..x',
579 )
579 )
580 auto_alias = auto_alias + ls_extra
580 auto_alias = auto_alias + ls_extra
581 elif os.name in ['nt','dos']:
581 elif os.name in ['nt','dos']:
582 auto_alias = ('ls dir /on',
582 auto_alias = ('ls dir /on',
583 'ddir dir /ad /on', 'ldir dir /ad /on',
583 'ddir dir /ad /on', 'ldir dir /ad /on',
584 'mkdir mkdir','rmdir rmdir','echo echo',
584 'mkdir mkdir','rmdir rmdir','echo echo',
585 'ren ren','cls cls','copy copy')
585 'ren ren','cls cls','copy copy')
586 else:
586 else:
587 auto_alias = ()
587 auto_alias = ()
588 self.auto_alias = [s.split(None,1) for s in auto_alias]
588 self.auto_alias = [s.split(None,1) for s in auto_alias]
589
589
590
590
591 # Produce a public API instance
591 # Produce a public API instance
592 self.api = IPython.ipapi.IPApi(self)
592 self.api = IPython.ipapi.IPApi(self)
593
593
594 # Call the actual (public) initializer
594 # Call the actual (public) initializer
595 self.init_auto_alias()
595 self.init_auto_alias()
596
596
597 # track which builtins we add, so we can clean up later
597 # track which builtins we add, so we can clean up later
598 self.builtins_added = {}
598 self.builtins_added = {}
599 # This method will add the necessary builtins for operation, but
599 # This method will add the necessary builtins for operation, but
600 # tracking what it did via the builtins_added dict.
600 # tracking what it did via the builtins_added dict.
601
601
602 #TODO: remove this, redundant
602 #TODO: remove this, redundant
603 self.add_builtins()
603 self.add_builtins()
604
604
605
605
606
606
607
607
608 # end __init__
608 # end __init__
609
609
610 def var_expand(self,cmd,depth=0):
610 def var_expand(self,cmd,depth=0):
611 """Expand python variables in a string.
611 """Expand python variables in a string.
612
612
613 The depth argument indicates how many frames above the caller should
613 The depth argument indicates how many frames above the caller should
614 be walked to look for the local namespace where to expand variables.
614 be walked to look for the local namespace where to expand variables.
615
615
616 The global namespace for expansion is always the user's interactive
616 The global namespace for expansion is always the user's interactive
617 namespace.
617 namespace.
618 """
618 """
619
619
620 return str(ItplNS(cmd,
620 return str(ItplNS(cmd,
621 self.user_ns, # globals
621 self.user_ns, # globals
622 # Skip our own frame in searching for locals:
622 # Skip our own frame in searching for locals:
623 sys._getframe(depth+1).f_locals # locals
623 sys._getframe(depth+1).f_locals # locals
624 ))
624 ))
625
625
626 def pre_config_initialization(self):
626 def pre_config_initialization(self):
627 """Pre-configuration init method
627 """Pre-configuration init method
628
628
629 This is called before the configuration files are processed to
629 This is called before the configuration files are processed to
630 prepare the services the config files might need.
630 prepare the services the config files might need.
631
631
632 self.rc already has reasonable default values at this point.
632 self.rc already has reasonable default values at this point.
633 """
633 """
634 rc = self.rc
634 rc = self.rc
635 try:
635 try:
636 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
636 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
637 except exceptions.UnicodeDecodeError:
637 except exceptions.UnicodeDecodeError:
638 print "Your ipythondir can't be decoded to unicode!"
638 print "Your ipythondir can't be decoded to unicode!"
639 print "Please set HOME environment variable to something that"
639 print "Please set HOME environment variable to something that"
640 print r"only has ASCII characters, e.g. c:\home"
640 print r"only has ASCII characters, e.g. c:\home"
641 print "Now it is",rc.ipythondir
641 print "Now it is",rc.ipythondir
642 sys.exit()
642 sys.exit()
643 self.shadowhist = IPython.history.ShadowHist(self.db)
643 self.shadowhist = IPython.history.ShadowHist(self.db)
644
644
645
645
646 def post_config_initialization(self):
646 def post_config_initialization(self):
647 """Post configuration init method
647 """Post configuration init method
648
648
649 This is called after the configuration files have been processed to
649 This is called after the configuration files have been processed to
650 'finalize' the initialization."""
650 'finalize' the initialization."""
651
651
652 rc = self.rc
652 rc = self.rc
653
653
654 # Object inspector
654 # Object inspector
655 self.inspector = OInspect.Inspector(OInspect.InspectColors,
655 self.inspector = OInspect.Inspector(OInspect.InspectColors,
656 PyColorize.ANSICodeColors,
656 PyColorize.ANSICodeColors,
657 'NoColor',
657 'NoColor',
658 rc.object_info_string_level)
658 rc.object_info_string_level)
659
659
660 self.rl_next_input = None
660 self.rl_next_input = None
661 self.rl_do_indent = False
661 self.rl_do_indent = False
662 # Load readline proper
662 # Load readline proper
663 if rc.readline:
663 if rc.readline:
664 self.init_readline()
664 self.init_readline()
665
665
666
666
667 # local shortcut, this is used a LOT
667 # local shortcut, this is used a LOT
668 self.log = self.logger.log
668 self.log = self.logger.log
669
669
670 # Initialize cache, set in/out prompts and printing system
670 # Initialize cache, set in/out prompts and printing system
671 self.outputcache = CachedOutput(self,
671 self.outputcache = CachedOutput(self,
672 rc.cache_size,
672 rc.cache_size,
673 rc.pprint,
673 rc.pprint,
674 input_sep = rc.separate_in,
674 input_sep = rc.separate_in,
675 output_sep = rc.separate_out,
675 output_sep = rc.separate_out,
676 output_sep2 = rc.separate_out2,
676 output_sep2 = rc.separate_out2,
677 ps1 = rc.prompt_in1,
677 ps1 = rc.prompt_in1,
678 ps2 = rc.prompt_in2,
678 ps2 = rc.prompt_in2,
679 ps_out = rc.prompt_out,
679 ps_out = rc.prompt_out,
680 pad_left = rc.prompts_pad_left)
680 pad_left = rc.prompts_pad_left)
681
681
682 # user may have over-ridden the default print hook:
682 # user may have over-ridden the default print hook:
683 try:
683 try:
684 self.outputcache.__class__.display = self.hooks.display
684 self.outputcache.__class__.display = self.hooks.display
685 except AttributeError:
685 except AttributeError:
686 pass
686 pass
687
687
688 # I don't like assigning globally to sys, because it means when
688 # I don't like assigning globally to sys, because it means when
689 # embedding instances, each embedded instance overrides the previous
689 # embedding instances, each embedded instance overrides the previous
690 # choice. But sys.displayhook seems to be called internally by exec,
690 # choice. But sys.displayhook seems to be called internally by exec,
691 # so I don't see a way around it. We first save the original and then
691 # so I don't see a way around it. We first save the original and then
692 # overwrite it.
692 # overwrite it.
693 self.sys_displayhook = sys.displayhook
693 self.sys_displayhook = sys.displayhook
694 sys.displayhook = self.outputcache
694 sys.displayhook = self.outputcache
695
695
696 # Do a proper resetting of doctest, including the necessary displayhook
696 # Do a proper resetting of doctest, including the necessary displayhook
697 # monkeypatching
697 # monkeypatching
698 try:
698 try:
699 doctest_reload()
699 doctest_reload()
700 except ImportError:
700 except ImportError:
701 warn("doctest module does not exist.")
701 warn("doctest module does not exist.")
702
702
703 # Set user colors (don't do it in the constructor above so that it
703 # Set user colors (don't do it in the constructor above so that it
704 # doesn't crash if colors option is invalid)
704 # doesn't crash if colors option is invalid)
705 self.magic_colors(rc.colors)
705 self.magic_colors(rc.colors)
706
706
707 # Set calling of pdb on exceptions
707 # Set calling of pdb on exceptions
708 self.call_pdb = rc.pdb
708 self.call_pdb = rc.pdb
709
709
710 # Load user aliases
710 # Load user aliases
711 for alias in rc.alias:
711 for alias in rc.alias:
712 self.magic_alias(alias)
712 self.magic_alias(alias)
713
713
714 self.hooks.late_startup_hook()
714 self.hooks.late_startup_hook()
715
715
716 for cmd in self.rc.autoexec:
716 for cmd in self.rc.autoexec:
717 #print "autoexec>",cmd #dbg
717 #print "autoexec>",cmd #dbg
718 self.api.runlines(cmd)
718 self.api.runlines(cmd)
719
719
720 batchrun = False
720 batchrun = False
721 for batchfile in [path(arg) for arg in self.rc.args
721 for batchfile in [path(arg) for arg in self.rc.args
722 if arg.lower().endswith('.ipy')]:
722 if arg.lower().endswith('.ipy')]:
723 if not batchfile.isfile():
723 if not batchfile.isfile():
724 print "No such batch file:", batchfile
724 print "No such batch file:", batchfile
725 continue
725 continue
726 self.api.runlines(batchfile.text())
726 self.api.runlines(batchfile.text())
727 batchrun = True
727 batchrun = True
728 # without -i option, exit after running the batch file
728 # without -i option, exit after running the batch file
729 if batchrun and not self.rc.interact:
729 if batchrun and not self.rc.interact:
730 self.exit_now = True
730 self.ask_exit()
731
731
732 def add_builtins(self):
732 def add_builtins(self):
733 """Store ipython references into the builtin namespace.
733 """Store ipython references into the builtin namespace.
734
734
735 Some parts of ipython operate via builtins injected here, which hold a
735 Some parts of ipython operate via builtins injected here, which hold a
736 reference to IPython itself."""
736 reference to IPython itself."""
737
737
738 # TODO: deprecate all of these, they are unsafe
738 # TODO: deprecate all of these, they are unsafe
739 builtins_new = dict(__IPYTHON__ = self,
739 builtins_new = dict(__IPYTHON__ = self,
740 ip_set_hook = self.set_hook,
740 ip_set_hook = self.set_hook,
741 jobs = self.jobs,
741 jobs = self.jobs,
742 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
742 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
743 ipalias = wrap_deprecated(self.ipalias),
743 ipalias = wrap_deprecated(self.ipalias),
744 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
744 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
745 #_ip = self.api
745 #_ip = self.api
746 )
746 )
747 for biname,bival in builtins_new.items():
747 for biname,bival in builtins_new.items():
748 try:
748 try:
749 # store the orignal value so we can restore it
749 # store the orignal value so we can restore it
750 self.builtins_added[biname] = __builtin__.__dict__[biname]
750 self.builtins_added[biname] = __builtin__.__dict__[biname]
751 except KeyError:
751 except KeyError:
752 # or mark that it wasn't defined, and we'll just delete it at
752 # or mark that it wasn't defined, and we'll just delete it at
753 # cleanup
753 # cleanup
754 self.builtins_added[biname] = Undefined
754 self.builtins_added[biname] = Undefined
755 __builtin__.__dict__[biname] = bival
755 __builtin__.__dict__[biname] = bival
756
756
757 # Keep in the builtins a flag for when IPython is active. We set it
757 # Keep in the builtins a flag for when IPython is active. We set it
758 # with setdefault so that multiple nested IPythons don't clobber one
758 # with setdefault so that multiple nested IPythons don't clobber one
759 # another. Each will increase its value by one upon being activated,
759 # another. Each will increase its value by one upon being activated,
760 # which also gives us a way to determine the nesting level.
760 # which also gives us a way to determine the nesting level.
761 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
761 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
762
762
763 def clean_builtins(self):
763 def clean_builtins(self):
764 """Remove any builtins which might have been added by add_builtins, or
764 """Remove any builtins which might have been added by add_builtins, or
765 restore overwritten ones to their previous values."""
765 restore overwritten ones to their previous values."""
766 for biname,bival in self.builtins_added.items():
766 for biname,bival in self.builtins_added.items():
767 if bival is Undefined:
767 if bival is Undefined:
768 del __builtin__.__dict__[biname]
768 del __builtin__.__dict__[biname]
769 else:
769 else:
770 __builtin__.__dict__[biname] = bival
770 __builtin__.__dict__[biname] = bival
771 self.builtins_added.clear()
771 self.builtins_added.clear()
772
772
773 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
773 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
774 """set_hook(name,hook) -> sets an internal IPython hook.
774 """set_hook(name,hook) -> sets an internal IPython hook.
775
775
776 IPython exposes some of its internal API as user-modifiable hooks. By
776 IPython exposes some of its internal API as user-modifiable hooks. By
777 adding your function to one of these hooks, you can modify IPython's
777 adding your function to one of these hooks, you can modify IPython's
778 behavior to call at runtime your own routines."""
778 behavior to call at runtime your own routines."""
779
779
780 # At some point in the future, this should validate the hook before it
780 # At some point in the future, this should validate the hook before it
781 # accepts it. Probably at least check that the hook takes the number
781 # accepts it. Probably at least check that the hook takes the number
782 # of args it's supposed to.
782 # of args it's supposed to.
783
783
784 f = new.instancemethod(hook,self,self.__class__)
784 f = new.instancemethod(hook,self,self.__class__)
785
785
786 # check if the hook is for strdispatcher first
786 # check if the hook is for strdispatcher first
787 if str_key is not None:
787 if str_key is not None:
788 sdp = self.strdispatchers.get(name, StrDispatch())
788 sdp = self.strdispatchers.get(name, StrDispatch())
789 sdp.add_s(str_key, f, priority )
789 sdp.add_s(str_key, f, priority )
790 self.strdispatchers[name] = sdp
790 self.strdispatchers[name] = sdp
791 return
791 return
792 if re_key is not None:
792 if re_key is not None:
793 sdp = self.strdispatchers.get(name, StrDispatch())
793 sdp = self.strdispatchers.get(name, StrDispatch())
794 sdp.add_re(re.compile(re_key), f, priority )
794 sdp.add_re(re.compile(re_key), f, priority )
795 self.strdispatchers[name] = sdp
795 self.strdispatchers[name] = sdp
796 return
796 return
797
797
798 dp = getattr(self.hooks, name, None)
798 dp = getattr(self.hooks, name, None)
799 if name not in IPython.hooks.__all__:
799 if name not in IPython.hooks.__all__:
800 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
800 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
801 if not dp:
801 if not dp:
802 dp = IPython.hooks.CommandChainDispatcher()
802 dp = IPython.hooks.CommandChainDispatcher()
803
803
804 try:
804 try:
805 dp.add(f,priority)
805 dp.add(f,priority)
806 except AttributeError:
806 except AttributeError:
807 # it was not commandchain, plain old func - replace
807 # it was not commandchain, plain old func - replace
808 dp = f
808 dp = f
809
809
810 setattr(self.hooks,name, dp)
810 setattr(self.hooks,name, dp)
811
811
812
812
813 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
813 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
814
814
815 def set_crash_handler(self,crashHandler):
815 def set_crash_handler(self,crashHandler):
816 """Set the IPython crash handler.
816 """Set the IPython crash handler.
817
817
818 This must be a callable with a signature suitable for use as
818 This must be a callable with a signature suitable for use as
819 sys.excepthook."""
819 sys.excepthook."""
820
820
821 # Install the given crash handler as the Python exception hook
821 # Install the given crash handler as the Python exception hook
822 sys.excepthook = crashHandler
822 sys.excepthook = crashHandler
823
823
824 # The instance will store a pointer to this, so that runtime code
824 # The instance will store a pointer to this, so that runtime code
825 # (such as magics) can access it. This is because during the
825 # (such as magics) can access it. This is because during the
826 # read-eval loop, it gets temporarily overwritten (to deal with GUI
826 # read-eval loop, it gets temporarily overwritten (to deal with GUI
827 # frameworks).
827 # frameworks).
828 self.sys_excepthook = sys.excepthook
828 self.sys_excepthook = sys.excepthook
829
829
830
830
831 def set_custom_exc(self,exc_tuple,handler):
831 def set_custom_exc(self,exc_tuple,handler):
832 """set_custom_exc(exc_tuple,handler)
832 """set_custom_exc(exc_tuple,handler)
833
833
834 Set a custom exception handler, which will be called if any of the
834 Set a custom exception handler, which will be called if any of the
835 exceptions in exc_tuple occur in the mainloop (specifically, in the
835 exceptions in exc_tuple occur in the mainloop (specifically, in the
836 runcode() method.
836 runcode() method.
837
837
838 Inputs:
838 Inputs:
839
839
840 - exc_tuple: a *tuple* of valid exceptions to call the defined
840 - exc_tuple: a *tuple* of valid exceptions to call the defined
841 handler for. It is very important that you use a tuple, and NOT A
841 handler for. It is very important that you use a tuple, and NOT A
842 LIST here, because of the way Python's except statement works. If
842 LIST here, because of the way Python's except statement works. If
843 you only want to trap a single exception, use a singleton tuple:
843 you only want to trap a single exception, use a singleton tuple:
844
844
845 exc_tuple == (MyCustomException,)
845 exc_tuple == (MyCustomException,)
846
846
847 - handler: this must be defined as a function with the following
847 - handler: this must be defined as a function with the following
848 basic interface: def my_handler(self,etype,value,tb).
848 basic interface: def my_handler(self,etype,value,tb).
849
849
850 This will be made into an instance method (via new.instancemethod)
850 This will be made into an instance method (via new.instancemethod)
851 of IPython itself, and it will be called if any of the exceptions
851 of IPython itself, and it will be called if any of the exceptions
852 listed in the exc_tuple are caught. If the handler is None, an
852 listed in the exc_tuple are caught. If the handler is None, an
853 internal basic one is used, which just prints basic info.
853 internal basic one is used, which just prints basic info.
854
854
855 WARNING: by putting in your own exception handler into IPython's main
855 WARNING: by putting in your own exception handler into IPython's main
856 execution loop, you run a very good chance of nasty crashes. This
856 execution loop, you run a very good chance of nasty crashes. This
857 facility should only be used if you really know what you are doing."""
857 facility should only be used if you really know what you are doing."""
858
858
859 assert type(exc_tuple)==type(()) , \
859 assert type(exc_tuple)==type(()) , \
860 "The custom exceptions must be given AS A TUPLE."
860 "The custom exceptions must be given AS A TUPLE."
861
861
862 def dummy_handler(self,etype,value,tb):
862 def dummy_handler(self,etype,value,tb):
863 print '*** Simple custom exception handler ***'
863 print '*** Simple custom exception handler ***'
864 print 'Exception type :',etype
864 print 'Exception type :',etype
865 print 'Exception value:',value
865 print 'Exception value:',value
866 print 'Traceback :',tb
866 print 'Traceback :',tb
867 print 'Source code :','\n'.join(self.buffer)
867 print 'Source code :','\n'.join(self.buffer)
868
868
869 if handler is None: handler = dummy_handler
869 if handler is None: handler = dummy_handler
870
870
871 self.CustomTB = new.instancemethod(handler,self,self.__class__)
871 self.CustomTB = new.instancemethod(handler,self,self.__class__)
872 self.custom_exceptions = exc_tuple
872 self.custom_exceptions = exc_tuple
873
873
874 def set_custom_completer(self,completer,pos=0):
874 def set_custom_completer(self,completer,pos=0):
875 """set_custom_completer(completer,pos=0)
875 """set_custom_completer(completer,pos=0)
876
876
877 Adds a new custom completer function.
877 Adds a new custom completer function.
878
878
879 The position argument (defaults to 0) is the index in the completers
879 The position argument (defaults to 0) is the index in the completers
880 list where you want the completer to be inserted."""
880 list where you want the completer to be inserted."""
881
881
882 newcomp = new.instancemethod(completer,self.Completer,
882 newcomp = new.instancemethod(completer,self.Completer,
883 self.Completer.__class__)
883 self.Completer.__class__)
884 self.Completer.matchers.insert(pos,newcomp)
884 self.Completer.matchers.insert(pos,newcomp)
885
885
886 def set_completer(self):
886 def set_completer(self):
887 """reset readline's completer to be our own."""
887 """reset readline's completer to be our own."""
888 self.readline.set_completer(self.Completer.complete)
888 self.readline.set_completer(self.Completer.complete)
889
889
890 def _get_call_pdb(self):
890 def _get_call_pdb(self):
891 return self._call_pdb
891 return self._call_pdb
892
892
893 def _set_call_pdb(self,val):
893 def _set_call_pdb(self,val):
894
894
895 if val not in (0,1,False,True):
895 if val not in (0,1,False,True):
896 raise ValueError,'new call_pdb value must be boolean'
896 raise ValueError,'new call_pdb value must be boolean'
897
897
898 # store value in instance
898 # store value in instance
899 self._call_pdb = val
899 self._call_pdb = val
900
900
901 # notify the actual exception handlers
901 # notify the actual exception handlers
902 self.InteractiveTB.call_pdb = val
902 self.InteractiveTB.call_pdb = val
903 if self.isthreaded:
903 if self.isthreaded:
904 try:
904 try:
905 self.sys_excepthook.call_pdb = val
905 self.sys_excepthook.call_pdb = val
906 except:
906 except:
907 warn('Failed to activate pdb for threaded exception handler')
907 warn('Failed to activate pdb for threaded exception handler')
908
908
909 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
909 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
910 'Control auto-activation of pdb at exceptions')
910 'Control auto-activation of pdb at exceptions')
911
911
912
912
913 # These special functions get installed in the builtin namespace, to
913 # These special functions get installed in the builtin namespace, to
914 # provide programmatic (pure python) access to magics, aliases and system
914 # provide programmatic (pure python) access to magics, aliases and system
915 # calls. This is important for logging, user scripting, and more.
915 # calls. This is important for logging, user scripting, and more.
916
916
917 # We are basically exposing, via normal python functions, the three
917 # We are basically exposing, via normal python functions, the three
918 # mechanisms in which ipython offers special call modes (magics for
918 # mechanisms in which ipython offers special call modes (magics for
919 # internal control, aliases for direct system access via pre-selected
919 # internal control, aliases for direct system access via pre-selected
920 # names, and !cmd for calling arbitrary system commands).
920 # names, and !cmd for calling arbitrary system commands).
921
921
922 def ipmagic(self,arg_s):
922 def ipmagic(self,arg_s):
923 """Call a magic function by name.
923 """Call a magic function by name.
924
924
925 Input: a string containing the name of the magic function to call and any
925 Input: a string containing the name of the magic function to call and any
926 additional arguments to be passed to the magic.
926 additional arguments to be passed to the magic.
927
927
928 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
928 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
929 prompt:
929 prompt:
930
930
931 In[1]: %name -opt foo bar
931 In[1]: %name -opt foo bar
932
932
933 To call a magic without arguments, simply use ipmagic('name').
933 To call a magic without arguments, simply use ipmagic('name').
934
934
935 This provides a proper Python function to call IPython's magics in any
935 This provides a proper Python function to call IPython's magics in any
936 valid Python code you can type at the interpreter, including loops and
936 valid Python code you can type at the interpreter, including loops and
937 compound statements. It is added by IPython to the Python builtin
937 compound statements. It is added by IPython to the Python builtin
938 namespace upon initialization."""
938 namespace upon initialization."""
939
939
940 args = arg_s.split(' ',1)
940 args = arg_s.split(' ',1)
941 magic_name = args[0]
941 magic_name = args[0]
942 magic_name = magic_name.lstrip(self.ESC_MAGIC)
942 magic_name = magic_name.lstrip(self.ESC_MAGIC)
943
943
944 try:
944 try:
945 magic_args = args[1]
945 magic_args = args[1]
946 except IndexError:
946 except IndexError:
947 magic_args = ''
947 magic_args = ''
948 fn = getattr(self,'magic_'+magic_name,None)
948 fn = getattr(self,'magic_'+magic_name,None)
949 if fn is None:
949 if fn is None:
950 error("Magic function `%s` not found." % magic_name)
950 error("Magic function `%s` not found." % magic_name)
951 else:
951 else:
952 magic_args = self.var_expand(magic_args,1)
952 magic_args = self.var_expand(magic_args,1)
953 return fn(magic_args)
953 return fn(magic_args)
954
954
955 def ipalias(self,arg_s):
955 def ipalias(self,arg_s):
956 """Call an alias by name.
956 """Call an alias by name.
957
957
958 Input: a string containing the name of the alias to call and any
958 Input: a string containing the name of the alias to call and any
959 additional arguments to be passed to the magic.
959 additional arguments to be passed to the magic.
960
960
961 ipalias('name -opt foo bar') is equivalent to typing at the ipython
961 ipalias('name -opt foo bar') is equivalent to typing at the ipython
962 prompt:
962 prompt:
963
963
964 In[1]: name -opt foo bar
964 In[1]: name -opt foo bar
965
965
966 To call an alias without arguments, simply use ipalias('name').
966 To call an alias without arguments, simply use ipalias('name').
967
967
968 This provides a proper Python function to call IPython's aliases in any
968 This provides a proper Python function to call IPython's aliases in any
969 valid Python code you can type at the interpreter, including loops and
969 valid Python code you can type at the interpreter, including loops and
970 compound statements. It is added by IPython to the Python builtin
970 compound statements. It is added by IPython to the Python builtin
971 namespace upon initialization."""
971 namespace upon initialization."""
972
972
973 args = arg_s.split(' ',1)
973 args = arg_s.split(' ',1)
974 alias_name = args[0]
974 alias_name = args[0]
975 try:
975 try:
976 alias_args = args[1]
976 alias_args = args[1]
977 except IndexError:
977 except IndexError:
978 alias_args = ''
978 alias_args = ''
979 if alias_name in self.alias_table:
979 if alias_name in self.alias_table:
980 self.call_alias(alias_name,alias_args)
980 self.call_alias(alias_name,alias_args)
981 else:
981 else:
982 error("Alias `%s` not found." % alias_name)
982 error("Alias `%s` not found." % alias_name)
983
983
984 def ipsystem(self,arg_s):
984 def ipsystem(self,arg_s):
985 """Make a system call, using IPython."""
985 """Make a system call, using IPython."""
986
986
987 self.system(arg_s)
987 self.system(arg_s)
988
988
989 def complete(self,text):
989 def complete(self,text):
990 """Return a sorted list of all possible completions on text.
990 """Return a sorted list of all possible completions on text.
991
991
992 Inputs:
992 Inputs:
993
993
994 - text: a string of text to be completed on.
994 - text: a string of text to be completed on.
995
995
996 This is a wrapper around the completion mechanism, similar to what
996 This is a wrapper around the completion mechanism, similar to what
997 readline does at the command line when the TAB key is hit. By
997 readline does at the command line when the TAB key is hit. By
998 exposing it as a method, it can be used by other non-readline
998 exposing it as a method, it can be used by other non-readline
999 environments (such as GUIs) for text completion.
999 environments (such as GUIs) for text completion.
1000
1000
1001 Simple usage example:
1001 Simple usage example:
1002
1002
1003 In [7]: x = 'hello'
1003 In [7]: x = 'hello'
1004
1004
1005 In [8]: x
1005 In [8]: x
1006 Out[8]: 'hello'
1006 Out[8]: 'hello'
1007
1007
1008 In [9]: print x
1008 In [9]: print x
1009 hello
1009 hello
1010
1010
1011 In [10]: _ip.IP.complete('x.l')
1011 In [10]: _ip.IP.complete('x.l')
1012 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] # randomX
1012 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] # randomX
1013 """
1013 """
1014
1014
1015 complete = self.Completer.complete
1015 complete = self.Completer.complete
1016 state = 0
1016 state = 0
1017 # use a dict so we get unique keys, since ipyhton's multiple
1017 # use a dict so we get unique keys, since ipyhton's multiple
1018 # completers can return duplicates. When we make 2.4 a requirement,
1018 # completers can return duplicates. When we make 2.4 a requirement,
1019 # start using sets instead, which are faster.
1019 # start using sets instead, which are faster.
1020 comps = {}
1020 comps = {}
1021 while True:
1021 while True:
1022 newcomp = complete(text,state,line_buffer=text)
1022 newcomp = complete(text,state,line_buffer=text)
1023 if newcomp is None:
1023 if newcomp is None:
1024 break
1024 break
1025 comps[newcomp] = 1
1025 comps[newcomp] = 1
1026 state += 1
1026 state += 1
1027 outcomps = comps.keys()
1027 outcomps = comps.keys()
1028 outcomps.sort()
1028 outcomps.sort()
1029 #print "T:",text,"OC:",outcomps # dbg
1029 #print "T:",text,"OC:",outcomps # dbg
1030 #print "vars:",self.user_ns.keys()
1030 #print "vars:",self.user_ns.keys()
1031 return outcomps
1031 return outcomps
1032
1032
1033 def set_completer_frame(self, frame=None):
1033 def set_completer_frame(self, frame=None):
1034 if frame:
1034 if frame:
1035 self.Completer.namespace = frame.f_locals
1035 self.Completer.namespace = frame.f_locals
1036 self.Completer.global_namespace = frame.f_globals
1036 self.Completer.global_namespace = frame.f_globals
1037 else:
1037 else:
1038 self.Completer.namespace = self.user_ns
1038 self.Completer.namespace = self.user_ns
1039 self.Completer.global_namespace = self.user_global_ns
1039 self.Completer.global_namespace = self.user_global_ns
1040
1040
1041 def init_auto_alias(self):
1041 def init_auto_alias(self):
1042 """Define some aliases automatically.
1042 """Define some aliases automatically.
1043
1043
1044 These are ALL parameter-less aliases"""
1044 These are ALL parameter-less aliases"""
1045
1045
1046 for alias,cmd in self.auto_alias:
1046 for alias,cmd in self.auto_alias:
1047 self.getapi().defalias(alias,cmd)
1047 self.getapi().defalias(alias,cmd)
1048
1048
1049
1049
1050 def alias_table_validate(self,verbose=0):
1050 def alias_table_validate(self,verbose=0):
1051 """Update information about the alias table.
1051 """Update information about the alias table.
1052
1052
1053 In particular, make sure no Python keywords/builtins are in it."""
1053 In particular, make sure no Python keywords/builtins are in it."""
1054
1054
1055 no_alias = self.no_alias
1055 no_alias = self.no_alias
1056 for k in self.alias_table.keys():
1056 for k in self.alias_table.keys():
1057 if k in no_alias:
1057 if k in no_alias:
1058 del self.alias_table[k]
1058 del self.alias_table[k]
1059 if verbose:
1059 if verbose:
1060 print ("Deleting alias <%s>, it's a Python "
1060 print ("Deleting alias <%s>, it's a Python "
1061 "keyword or builtin." % k)
1061 "keyword or builtin." % k)
1062
1062
1063 def set_autoindent(self,value=None):
1063 def set_autoindent(self,value=None):
1064 """Set the autoindent flag, checking for readline support.
1064 """Set the autoindent flag, checking for readline support.
1065
1065
1066 If called with no arguments, it acts as a toggle."""
1066 If called with no arguments, it acts as a toggle."""
1067
1067
1068 if not self.has_readline:
1068 if not self.has_readline:
1069 if os.name == 'posix':
1069 if os.name == 'posix':
1070 warn("The auto-indent feature requires the readline library")
1070 warn("The auto-indent feature requires the readline library")
1071 self.autoindent = 0
1071 self.autoindent = 0
1072 return
1072 return
1073 if value is None:
1073 if value is None:
1074 self.autoindent = not self.autoindent
1074 self.autoindent = not self.autoindent
1075 else:
1075 else:
1076 self.autoindent = value
1076 self.autoindent = value
1077
1077
1078 def rc_set_toggle(self,rc_field,value=None):
1078 def rc_set_toggle(self,rc_field,value=None):
1079 """Set or toggle a field in IPython's rc config. structure.
1079 """Set or toggle a field in IPython's rc config. structure.
1080
1080
1081 If called with no arguments, it acts as a toggle.
1081 If called with no arguments, it acts as a toggle.
1082
1082
1083 If called with a non-existent field, the resulting AttributeError
1083 If called with a non-existent field, the resulting AttributeError
1084 exception will propagate out."""
1084 exception will propagate out."""
1085
1085
1086 rc_val = getattr(self.rc,rc_field)
1086 rc_val = getattr(self.rc,rc_field)
1087 if value is None:
1087 if value is None:
1088 value = not rc_val
1088 value = not rc_val
1089 setattr(self.rc,rc_field,value)
1089 setattr(self.rc,rc_field,value)
1090
1090
1091 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1091 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1092 """Install the user configuration directory.
1092 """Install the user configuration directory.
1093
1093
1094 Can be called when running for the first time or to upgrade the user's
1094 Can be called when running for the first time or to upgrade the user's
1095 .ipython/ directory with the mode parameter. Valid modes are 'install'
1095 .ipython/ directory with the mode parameter. Valid modes are 'install'
1096 and 'upgrade'."""
1096 and 'upgrade'."""
1097
1097
1098 def wait():
1098 def wait():
1099 try:
1099 try:
1100 raw_input("Please press <RETURN> to start IPython.")
1100 raw_input("Please press <RETURN> to start IPython.")
1101 except EOFError:
1101 except EOFError:
1102 print >> Term.cout
1102 print >> Term.cout
1103 print '*'*70
1103 print '*'*70
1104
1104
1105 cwd = os.getcwd() # remember where we started
1105 cwd = os.getcwd() # remember where we started
1106 glb = glob.glob
1106 glb = glob.glob
1107 print '*'*70
1107 print '*'*70
1108 if mode == 'install':
1108 if mode == 'install':
1109 print \
1109 print \
1110 """Welcome to IPython. I will try to create a personal configuration directory
1110 """Welcome to IPython. I will try to create a personal configuration directory
1111 where you can customize many aspects of IPython's functionality in:\n"""
1111 where you can customize many aspects of IPython's functionality in:\n"""
1112 else:
1112 else:
1113 print 'I am going to upgrade your configuration in:'
1113 print 'I am going to upgrade your configuration in:'
1114
1114
1115 print ipythondir
1115 print ipythondir
1116
1116
1117 rcdirend = os.path.join('IPython','UserConfig')
1117 rcdirend = os.path.join('IPython','UserConfig')
1118 cfg = lambda d: os.path.join(d,rcdirend)
1118 cfg = lambda d: os.path.join(d,rcdirend)
1119 try:
1119 try:
1120 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1120 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1121 print "Initializing from configuration",rcdir
1121 print "Initializing from configuration",rcdir
1122 except IndexError:
1122 except IndexError:
1123 warning = """
1123 warning = """
1124 Installation error. IPython's directory was not found.
1124 Installation error. IPython's directory was not found.
1125
1125
1126 Check the following:
1126 Check the following:
1127
1127
1128 The ipython/IPython directory should be in a directory belonging to your
1128 The ipython/IPython directory should be in a directory belonging to your
1129 PYTHONPATH environment variable (that is, it should be in a directory
1129 PYTHONPATH environment variable (that is, it should be in a directory
1130 belonging to sys.path). You can copy it explicitly there or just link to it.
1130 belonging to sys.path). You can copy it explicitly there or just link to it.
1131
1131
1132 IPython will create a minimal default configuration for you.
1132 IPython will create a minimal default configuration for you.
1133
1133
1134 """
1134 """
1135 warn(warning)
1135 warn(warning)
1136 wait()
1136 wait()
1137
1137
1138 if sys.platform =='win32':
1138 if sys.platform =='win32':
1139 inif = 'ipythonrc.ini'
1139 inif = 'ipythonrc.ini'
1140 else:
1140 else:
1141 inif = 'ipythonrc'
1141 inif = 'ipythonrc'
1142 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', inif : '# intentionally left blank' }
1142 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', inif : '# intentionally left blank' }
1143 os.makedirs(ipythondir, mode = 0777)
1143 os.makedirs(ipythondir, mode = 0777)
1144 for f, cont in minimal_setup.items():
1144 for f, cont in minimal_setup.items():
1145 open(ipythondir + '/' + f,'w').write(cont)
1145 open(ipythondir + '/' + f,'w').write(cont)
1146
1146
1147 return
1147 return
1148
1148
1149 if mode == 'install':
1149 if mode == 'install':
1150 try:
1150 try:
1151 shutil.copytree(rcdir,ipythondir)
1151 shutil.copytree(rcdir,ipythondir)
1152 os.chdir(ipythondir)
1152 os.chdir(ipythondir)
1153 rc_files = glb("ipythonrc*")
1153 rc_files = glb("ipythonrc*")
1154 for rc_file in rc_files:
1154 for rc_file in rc_files:
1155 os.rename(rc_file,rc_file+rc_suffix)
1155 os.rename(rc_file,rc_file+rc_suffix)
1156 except:
1156 except:
1157 warning = """
1157 warning = """
1158
1158
1159 There was a problem with the installation:
1159 There was a problem with the installation:
1160 %s
1160 %s
1161 Try to correct it or contact the developers if you think it's a bug.
1161 Try to correct it or contact the developers if you think it's a bug.
1162 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1162 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1163 warn(warning)
1163 warn(warning)
1164 wait()
1164 wait()
1165 return
1165 return
1166
1166
1167 elif mode == 'upgrade':
1167 elif mode == 'upgrade':
1168 try:
1168 try:
1169 os.chdir(ipythondir)
1169 os.chdir(ipythondir)
1170 except:
1170 except:
1171 print """
1171 print """
1172 Can not upgrade: changing to directory %s failed. Details:
1172 Can not upgrade: changing to directory %s failed. Details:
1173 %s
1173 %s
1174 """ % (ipythondir,sys.exc_info()[1])
1174 """ % (ipythondir,sys.exc_info()[1])
1175 wait()
1175 wait()
1176 return
1176 return
1177 else:
1177 else:
1178 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1178 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1179 for new_full_path in sources:
1179 for new_full_path in sources:
1180 new_filename = os.path.basename(new_full_path)
1180 new_filename = os.path.basename(new_full_path)
1181 if new_filename.startswith('ipythonrc'):
1181 if new_filename.startswith('ipythonrc'):
1182 new_filename = new_filename + rc_suffix
1182 new_filename = new_filename + rc_suffix
1183 # The config directory should only contain files, skip any
1183 # The config directory should only contain files, skip any
1184 # directories which may be there (like CVS)
1184 # directories which may be there (like CVS)
1185 if os.path.isdir(new_full_path):
1185 if os.path.isdir(new_full_path):
1186 continue
1186 continue
1187 if os.path.exists(new_filename):
1187 if os.path.exists(new_filename):
1188 old_file = new_filename+'.old'
1188 old_file = new_filename+'.old'
1189 if os.path.exists(old_file):
1189 if os.path.exists(old_file):
1190 os.remove(old_file)
1190 os.remove(old_file)
1191 os.rename(new_filename,old_file)
1191 os.rename(new_filename,old_file)
1192 shutil.copy(new_full_path,new_filename)
1192 shutil.copy(new_full_path,new_filename)
1193 else:
1193 else:
1194 raise ValueError,'unrecognized mode for install:',`mode`
1194 raise ValueError,'unrecognized mode for install:',`mode`
1195
1195
1196 # Fix line-endings to those native to each platform in the config
1196 # Fix line-endings to those native to each platform in the config
1197 # directory.
1197 # directory.
1198 try:
1198 try:
1199 os.chdir(ipythondir)
1199 os.chdir(ipythondir)
1200 except:
1200 except:
1201 print """
1201 print """
1202 Problem: changing to directory %s failed.
1202 Problem: changing to directory %s failed.
1203 Details:
1203 Details:
1204 %s
1204 %s
1205
1205
1206 Some configuration files may have incorrect line endings. This should not
1206 Some configuration files may have incorrect line endings. This should not
1207 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1207 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1208 wait()
1208 wait()
1209 else:
1209 else:
1210 for fname in glb('ipythonrc*'):
1210 for fname in glb('ipythonrc*'):
1211 try:
1211 try:
1212 native_line_ends(fname,backup=0)
1212 native_line_ends(fname,backup=0)
1213 except IOError:
1213 except IOError:
1214 pass
1214 pass
1215
1215
1216 if mode == 'install':
1216 if mode == 'install':
1217 print """
1217 print """
1218 Successful installation!
1218 Successful installation!
1219
1219
1220 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1220 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1221 IPython manual (there are both HTML and PDF versions supplied with the
1221 IPython manual (there are both HTML and PDF versions supplied with the
1222 distribution) to make sure that your system environment is properly configured
1222 distribution) to make sure that your system environment is properly configured
1223 to take advantage of IPython's features.
1223 to take advantage of IPython's features.
1224
1224
1225 Important note: the configuration system has changed! The old system is
1225 Important note: the configuration system has changed! The old system is
1226 still in place, but its setting may be partly overridden by the settings in
1226 still in place, but its setting may be partly overridden by the settings in
1227 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1227 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1228 if some of the new settings bother you.
1228 if some of the new settings bother you.
1229
1229
1230 """
1230 """
1231 else:
1231 else:
1232 print """
1232 print """
1233 Successful upgrade!
1233 Successful upgrade!
1234
1234
1235 All files in your directory:
1235 All files in your directory:
1236 %(ipythondir)s
1236 %(ipythondir)s
1237 which would have been overwritten by the upgrade were backed up with a .old
1237 which would have been overwritten by the upgrade were backed up with a .old
1238 extension. If you had made particular customizations in those files you may
1238 extension. If you had made particular customizations in those files you may
1239 want to merge them back into the new files.""" % locals()
1239 want to merge them back into the new files.""" % locals()
1240 wait()
1240 wait()
1241 os.chdir(cwd)
1241 os.chdir(cwd)
1242 # end user_setup()
1242 # end user_setup()
1243
1243
1244 def atexit_operations(self):
1244 def atexit_operations(self):
1245 """This will be executed at the time of exit.
1245 """This will be executed at the time of exit.
1246
1246
1247 Saving of persistent data should be performed here. """
1247 Saving of persistent data should be performed here. """
1248
1248
1249 #print '*** IPython exit cleanup ***' # dbg
1249 #print '*** IPython exit cleanup ***' # dbg
1250 # input history
1250 # input history
1251 self.savehist()
1251 self.savehist()
1252
1252
1253 # Cleanup all tempfiles left around
1253 # Cleanup all tempfiles left around
1254 for tfile in self.tempfiles:
1254 for tfile in self.tempfiles:
1255 try:
1255 try:
1256 os.unlink(tfile)
1256 os.unlink(tfile)
1257 except OSError:
1257 except OSError:
1258 pass
1258 pass
1259
1259
1260 self.hooks.shutdown_hook()
1260 self.hooks.shutdown_hook()
1261
1261
1262 def savehist(self):
1262 def savehist(self):
1263 """Save input history to a file (via readline library)."""
1263 """Save input history to a file (via readline library)."""
1264
1264
1265 if not self.has_readline:
1265 if not self.has_readline:
1266 return
1266 return
1267
1267
1268 try:
1268 try:
1269 self.readline.write_history_file(self.histfile)
1269 self.readline.write_history_file(self.histfile)
1270 except:
1270 except:
1271 print 'Unable to save IPython command history to file: ' + \
1271 print 'Unable to save IPython command history to file: ' + \
1272 `self.histfile`
1272 `self.histfile`
1273
1273
1274 def reloadhist(self):
1274 def reloadhist(self):
1275 """Reload the input history from disk file."""
1275 """Reload the input history from disk file."""
1276
1276
1277 if self.has_readline:
1277 if self.has_readline:
1278 try:
1278 try:
1279 self.readline.clear_history()
1279 self.readline.clear_history()
1280 self.readline.read_history_file(self.shell.histfile)
1280 self.readline.read_history_file(self.shell.histfile)
1281 except AttributeError:
1281 except AttributeError:
1282 pass
1282 pass
1283
1283
1284
1284
1285 def history_saving_wrapper(self, func):
1285 def history_saving_wrapper(self, func):
1286 """ Wrap func for readline history saving
1286 """ Wrap func for readline history saving
1287
1287
1288 Convert func into callable that saves & restores
1288 Convert func into callable that saves & restores
1289 history around the call """
1289 history around the call """
1290
1290
1291 if not self.has_readline:
1291 if not self.has_readline:
1292 return func
1292 return func
1293
1293
1294 def wrapper():
1294 def wrapper():
1295 self.savehist()
1295 self.savehist()
1296 try:
1296 try:
1297 func()
1297 func()
1298 finally:
1298 finally:
1299 readline.read_history_file(self.histfile)
1299 readline.read_history_file(self.histfile)
1300 return wrapper
1300 return wrapper
1301
1301
1302
1302
1303 def pre_readline(self):
1303 def pre_readline(self):
1304 """readline hook to be used at the start of each line.
1304 """readline hook to be used at the start of each line.
1305
1305
1306 Currently it handles auto-indent only."""
1306 Currently it handles auto-indent only."""
1307
1307
1308 #debugx('self.indent_current_nsp','pre_readline:')
1308 #debugx('self.indent_current_nsp','pre_readline:')
1309
1309
1310 if self.rl_do_indent:
1310 if self.rl_do_indent:
1311 self.readline.insert_text(self.indent_current_str())
1311 self.readline.insert_text(self.indent_current_str())
1312 if self.rl_next_input is not None:
1312 if self.rl_next_input is not None:
1313 self.readline.insert_text(self.rl_next_input)
1313 self.readline.insert_text(self.rl_next_input)
1314 self.rl_next_input = None
1314 self.rl_next_input = None
1315
1315
1316 def init_readline(self):
1316 def init_readline(self):
1317 """Command history completion/saving/reloading."""
1317 """Command history completion/saving/reloading."""
1318
1318
1319
1319
1320 import IPython.rlineimpl as readline
1320 import IPython.rlineimpl as readline
1321
1321
1322 if not readline.have_readline:
1322 if not readline.have_readline:
1323 self.has_readline = 0
1323 self.has_readline = 0
1324 self.readline = None
1324 self.readline = None
1325 # no point in bugging windows users with this every time:
1325 # no point in bugging windows users with this every time:
1326 warn('Readline services not available on this platform.')
1326 warn('Readline services not available on this platform.')
1327 else:
1327 else:
1328 sys.modules['readline'] = readline
1328 sys.modules['readline'] = readline
1329 import atexit
1329 import atexit
1330 from IPython.completer import IPCompleter
1330 from IPython.completer import IPCompleter
1331 self.Completer = IPCompleter(self,
1331 self.Completer = IPCompleter(self,
1332 self.user_ns,
1332 self.user_ns,
1333 self.user_global_ns,
1333 self.user_global_ns,
1334 self.rc.readline_omit__names,
1334 self.rc.readline_omit__names,
1335 self.alias_table)
1335 self.alias_table)
1336 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1336 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1337 self.strdispatchers['complete_command'] = sdisp
1337 self.strdispatchers['complete_command'] = sdisp
1338 self.Completer.custom_completers = sdisp
1338 self.Completer.custom_completers = sdisp
1339 # Platform-specific configuration
1339 # Platform-specific configuration
1340 if os.name == 'nt':
1340 if os.name == 'nt':
1341 self.readline_startup_hook = readline.set_pre_input_hook
1341 self.readline_startup_hook = readline.set_pre_input_hook
1342 else:
1342 else:
1343 self.readline_startup_hook = readline.set_startup_hook
1343 self.readline_startup_hook = readline.set_startup_hook
1344
1344
1345 # Load user's initrc file (readline config)
1345 # Load user's initrc file (readline config)
1346 # Or if libedit is used, load editrc.
1346 # Or if libedit is used, load editrc.
1347 inputrc_name = os.environ.get('INPUTRC')
1347 inputrc_name = os.environ.get('INPUTRC')
1348 if inputrc_name is None:
1348 if inputrc_name is None:
1349 home_dir = get_home_dir()
1349 home_dir = get_home_dir()
1350 if home_dir is not None:
1350 if home_dir is not None:
1351 inputrc_name = '.inputrc'
1351 inputrc_name = '.inputrc'
1352 if readline.uses_libedit:
1352 if readline.uses_libedit:
1353 inputrc_name = '.editrc'
1353 inputrc_name = '.editrc'
1354 inputrc_name = os.path.join(home_dir, inputrc_name)
1354 inputrc_name = os.path.join(home_dir, inputrc_name)
1355 if os.path.isfile(inputrc_name):
1355 if os.path.isfile(inputrc_name):
1356 try:
1356 try:
1357 readline.read_init_file(inputrc_name)
1357 readline.read_init_file(inputrc_name)
1358 except:
1358 except:
1359 warn('Problems reading readline initialization file <%s>'
1359 warn('Problems reading readline initialization file <%s>'
1360 % inputrc_name)
1360 % inputrc_name)
1361
1361
1362 self.has_readline = 1
1362 self.has_readline = 1
1363 self.readline = readline
1363 self.readline = readline
1364 # save this in sys so embedded copies can restore it properly
1364 # save this in sys so embedded copies can restore it properly
1365 sys.ipcompleter = self.Completer.complete
1365 sys.ipcompleter = self.Completer.complete
1366 self.set_completer()
1366 self.set_completer()
1367
1367
1368 # Configure readline according to user's prefs
1368 # Configure readline according to user's prefs
1369 # This is only done if GNU readline is being used. If libedit
1369 # This is only done if GNU readline is being used. If libedit
1370 # is being used (as on Leopard) the readline config is
1370 # is being used (as on Leopard) the readline config is
1371 # not run as the syntax for libedit is different.
1371 # not run as the syntax for libedit is different.
1372 if not readline.uses_libedit:
1372 if not readline.uses_libedit:
1373 for rlcommand in self.rc.readline_parse_and_bind:
1373 for rlcommand in self.rc.readline_parse_and_bind:
1374 readline.parse_and_bind(rlcommand)
1374 readline.parse_and_bind(rlcommand)
1375
1375
1376 # remove some chars from the delimiters list
1376 # remove some chars from the delimiters list
1377 delims = readline.get_completer_delims()
1377 delims = readline.get_completer_delims()
1378 delims = delims.translate(string._idmap,
1378 delims = delims.translate(string._idmap,
1379 self.rc.readline_remove_delims)
1379 self.rc.readline_remove_delims)
1380 readline.set_completer_delims(delims)
1380 readline.set_completer_delims(delims)
1381 # otherwise we end up with a monster history after a while:
1381 # otherwise we end up with a monster history after a while:
1382 readline.set_history_length(1000)
1382 readline.set_history_length(1000)
1383 try:
1383 try:
1384 #print '*** Reading readline history' # dbg
1384 #print '*** Reading readline history' # dbg
1385 readline.read_history_file(self.histfile)
1385 readline.read_history_file(self.histfile)
1386 except IOError:
1386 except IOError:
1387 pass # It doesn't exist yet.
1387 pass # It doesn't exist yet.
1388
1388
1389 atexit.register(self.atexit_operations)
1389 atexit.register(self.atexit_operations)
1390 del atexit
1390 del atexit
1391
1391
1392 # Configure auto-indent for all platforms
1392 # Configure auto-indent for all platforms
1393 self.set_autoindent(self.rc.autoindent)
1393 self.set_autoindent(self.rc.autoindent)
1394
1394
1395 def ask_yes_no(self,prompt,default=True):
1395 def ask_yes_no(self,prompt,default=True):
1396 if self.rc.quiet:
1396 if self.rc.quiet:
1397 return True
1397 return True
1398 return ask_yes_no(prompt,default)
1398 return ask_yes_no(prompt,default)
1399
1399
1400 def _should_recompile(self,e):
1400 def _should_recompile(self,e):
1401 """Utility routine for edit_syntax_error"""
1401 """Utility routine for edit_syntax_error"""
1402
1402
1403 if e.filename in ('<ipython console>','<input>','<string>',
1403 if e.filename in ('<ipython console>','<input>','<string>',
1404 '<console>','<BackgroundJob compilation>',
1404 '<console>','<BackgroundJob compilation>',
1405 None):
1405 None):
1406
1406
1407 return False
1407 return False
1408 try:
1408 try:
1409 if (self.rc.autoedit_syntax and
1409 if (self.rc.autoedit_syntax and
1410 not self.ask_yes_no('Return to editor to correct syntax error? '
1410 not self.ask_yes_no('Return to editor to correct syntax error? '
1411 '[Y/n] ','y')):
1411 '[Y/n] ','y')):
1412 return False
1412 return False
1413 except EOFError:
1413 except EOFError:
1414 return False
1414 return False
1415
1415
1416 def int0(x):
1416 def int0(x):
1417 try:
1417 try:
1418 return int(x)
1418 return int(x)
1419 except TypeError:
1419 except TypeError:
1420 return 0
1420 return 0
1421 # always pass integer line and offset values to editor hook
1421 # always pass integer line and offset values to editor hook
1422 self.hooks.fix_error_editor(e.filename,
1422 self.hooks.fix_error_editor(e.filename,
1423 int0(e.lineno),int0(e.offset),e.msg)
1423 int0(e.lineno),int0(e.offset),e.msg)
1424 return True
1424 return True
1425
1425
1426 def edit_syntax_error(self):
1426 def edit_syntax_error(self):
1427 """The bottom half of the syntax error handler called in the main loop.
1427 """The bottom half of the syntax error handler called in the main loop.
1428
1428
1429 Loop until syntax error is fixed or user cancels.
1429 Loop until syntax error is fixed or user cancels.
1430 """
1430 """
1431
1431
1432 while self.SyntaxTB.last_syntax_error:
1432 while self.SyntaxTB.last_syntax_error:
1433 # copy and clear last_syntax_error
1433 # copy and clear last_syntax_error
1434 err = self.SyntaxTB.clear_err_state()
1434 err = self.SyntaxTB.clear_err_state()
1435 if not self._should_recompile(err):
1435 if not self._should_recompile(err):
1436 return
1436 return
1437 try:
1437 try:
1438 # may set last_syntax_error again if a SyntaxError is raised
1438 # may set last_syntax_error again if a SyntaxError is raised
1439 self.safe_execfile(err.filename,self.user_ns)
1439 self.safe_execfile(err.filename,self.user_ns)
1440 except:
1440 except:
1441 self.showtraceback()
1441 self.showtraceback()
1442 else:
1442 else:
1443 try:
1443 try:
1444 f = file(err.filename)
1444 f = file(err.filename)
1445 try:
1445 try:
1446 sys.displayhook(f.read())
1446 sys.displayhook(f.read())
1447 finally:
1447 finally:
1448 f.close()
1448 f.close()
1449 except:
1449 except:
1450 self.showtraceback()
1450 self.showtraceback()
1451
1451
1452 def showsyntaxerror(self, filename=None):
1452 def showsyntaxerror(self, filename=None):
1453 """Display the syntax error that just occurred.
1453 """Display the syntax error that just occurred.
1454
1454
1455 This doesn't display a stack trace because there isn't one.
1455 This doesn't display a stack trace because there isn't one.
1456
1456
1457 If a filename is given, it is stuffed in the exception instead
1457 If a filename is given, it is stuffed in the exception instead
1458 of what was there before (because Python's parser always uses
1458 of what was there before (because Python's parser always uses
1459 "<string>" when reading from a string).
1459 "<string>" when reading from a string).
1460 """
1460 """
1461 etype, value, last_traceback = sys.exc_info()
1461 etype, value, last_traceback = sys.exc_info()
1462
1462
1463 # See note about these variables in showtraceback() below
1463 # See note about these variables in showtraceback() below
1464 sys.last_type = etype
1464 sys.last_type = etype
1465 sys.last_value = value
1465 sys.last_value = value
1466 sys.last_traceback = last_traceback
1466 sys.last_traceback = last_traceback
1467
1467
1468 if filename and etype is SyntaxError:
1468 if filename and etype is SyntaxError:
1469 # Work hard to stuff the correct filename in the exception
1469 # Work hard to stuff the correct filename in the exception
1470 try:
1470 try:
1471 msg, (dummy_filename, lineno, offset, line) = value
1471 msg, (dummy_filename, lineno, offset, line) = value
1472 except:
1472 except:
1473 # Not the format we expect; leave it alone
1473 # Not the format we expect; leave it alone
1474 pass
1474 pass
1475 else:
1475 else:
1476 # Stuff in the right filename
1476 # Stuff in the right filename
1477 try:
1477 try:
1478 # Assume SyntaxError is a class exception
1478 # Assume SyntaxError is a class exception
1479 value = SyntaxError(msg, (filename, lineno, offset, line))
1479 value = SyntaxError(msg, (filename, lineno, offset, line))
1480 except:
1480 except:
1481 # If that failed, assume SyntaxError is a string
1481 # If that failed, assume SyntaxError is a string
1482 value = msg, (filename, lineno, offset, line)
1482 value = msg, (filename, lineno, offset, line)
1483 self.SyntaxTB(etype,value,[])
1483 self.SyntaxTB(etype,value,[])
1484
1484
1485 def debugger(self,force=False):
1485 def debugger(self,force=False):
1486 """Call the pydb/pdb debugger.
1486 """Call the pydb/pdb debugger.
1487
1487
1488 Keywords:
1488 Keywords:
1489
1489
1490 - force(False): by default, this routine checks the instance call_pdb
1490 - force(False): by default, this routine checks the instance call_pdb
1491 flag and does not actually invoke the debugger if the flag is false.
1491 flag and does not actually invoke the debugger if the flag is false.
1492 The 'force' option forces the debugger to activate even if the flag
1492 The 'force' option forces the debugger to activate even if the flag
1493 is false.
1493 is false.
1494 """
1494 """
1495
1495
1496 if not (force or self.call_pdb):
1496 if not (force or self.call_pdb):
1497 return
1497 return
1498
1498
1499 if not hasattr(sys,'last_traceback'):
1499 if not hasattr(sys,'last_traceback'):
1500 error('No traceback has been produced, nothing to debug.')
1500 error('No traceback has been produced, nothing to debug.')
1501 return
1501 return
1502
1502
1503 # use pydb if available
1503 # use pydb if available
1504 if Debugger.has_pydb:
1504 if Debugger.has_pydb:
1505 from pydb import pm
1505 from pydb import pm
1506 else:
1506 else:
1507 # fallback to our internal debugger
1507 # fallback to our internal debugger
1508 pm = lambda : self.InteractiveTB.debugger(force=True)
1508 pm = lambda : self.InteractiveTB.debugger(force=True)
1509 self.history_saving_wrapper(pm)()
1509 self.history_saving_wrapper(pm)()
1510
1510
1511 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1511 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1512 """Display the exception that just occurred.
1512 """Display the exception that just occurred.
1513
1513
1514 If nothing is known about the exception, this is the method which
1514 If nothing is known about the exception, this is the method which
1515 should be used throughout the code for presenting user tracebacks,
1515 should be used throughout the code for presenting user tracebacks,
1516 rather than directly invoking the InteractiveTB object.
1516 rather than directly invoking the InteractiveTB object.
1517
1517
1518 A specific showsyntaxerror() also exists, but this method can take
1518 A specific showsyntaxerror() also exists, but this method can take
1519 care of calling it if needed, so unless you are explicitly catching a
1519 care of calling it if needed, so unless you are explicitly catching a
1520 SyntaxError exception, don't try to analyze the stack manually and
1520 SyntaxError exception, don't try to analyze the stack manually and
1521 simply call this method."""
1521 simply call this method."""
1522
1522
1523
1523
1524 # Though this won't be called by syntax errors in the input line,
1524 # Though this won't be called by syntax errors in the input line,
1525 # there may be SyntaxError cases whith imported code.
1525 # there may be SyntaxError cases whith imported code.
1526
1526
1527 try:
1527 try:
1528 if exc_tuple is None:
1528 if exc_tuple is None:
1529 etype, value, tb = sys.exc_info()
1529 etype, value, tb = sys.exc_info()
1530 else:
1530 else:
1531 etype, value, tb = exc_tuple
1531 etype, value, tb = exc_tuple
1532
1532
1533 if etype is SyntaxError:
1533 if etype is SyntaxError:
1534 self.showsyntaxerror(filename)
1534 self.showsyntaxerror(filename)
1535 elif etype is IPython.ipapi.UsageError:
1535 elif etype is IPython.ipapi.UsageError:
1536 print "UsageError:", value
1536 print "UsageError:", value
1537 else:
1537 else:
1538 # WARNING: these variables are somewhat deprecated and not
1538 # WARNING: these variables are somewhat deprecated and not
1539 # necessarily safe to use in a threaded environment, but tools
1539 # necessarily safe to use in a threaded environment, but tools
1540 # like pdb depend on their existence, so let's set them. If we
1540 # like pdb depend on their existence, so let's set them. If we
1541 # find problems in the field, we'll need to revisit their use.
1541 # find problems in the field, we'll need to revisit their use.
1542 sys.last_type = etype
1542 sys.last_type = etype
1543 sys.last_value = value
1543 sys.last_value = value
1544 sys.last_traceback = tb
1544 sys.last_traceback = tb
1545
1545
1546 if etype in self.custom_exceptions:
1546 if etype in self.custom_exceptions:
1547 self.CustomTB(etype,value,tb)
1547 self.CustomTB(etype,value,tb)
1548 else:
1548 else:
1549 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1549 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1550 if self.InteractiveTB.call_pdb and self.has_readline:
1550 if self.InteractiveTB.call_pdb and self.has_readline:
1551 # pdb mucks up readline, fix it back
1551 # pdb mucks up readline, fix it back
1552 self.set_completer()
1552 self.set_completer()
1553 except KeyboardInterrupt:
1553 except KeyboardInterrupt:
1554 self.write("\nKeyboardInterrupt\n")
1554 self.write("\nKeyboardInterrupt\n")
1555
1555
1556
1556
1557
1557
1558 def mainloop(self,banner=None):
1558 def mainloop(self,banner=None):
1559 """Creates the local namespace and starts the mainloop.
1559 """Creates the local namespace and starts the mainloop.
1560
1560
1561 If an optional banner argument is given, it will override the
1561 If an optional banner argument is given, it will override the
1562 internally created default banner."""
1562 internally created default banner."""
1563
1563
1564 if self.rc.c: # Emulate Python's -c option
1564 if self.rc.c: # Emulate Python's -c option
1565 self.exec_init_cmd()
1565 self.exec_init_cmd()
1566 if banner is None:
1566 if banner is None:
1567 if not self.rc.banner:
1567 if not self.rc.banner:
1568 banner = ''
1568 banner = ''
1569 # banner is string? Use it directly!
1569 # banner is string? Use it directly!
1570 elif isinstance(self.rc.banner,basestring):
1570 elif isinstance(self.rc.banner,basestring):
1571 banner = self.rc.banner
1571 banner = self.rc.banner
1572 else:
1572 else:
1573 banner = self.BANNER+self.banner2
1573 banner = self.BANNER+self.banner2
1574
1574
1575 while 1:
1575 while 1:
1576 try:
1576 try:
1577 self.interact(banner)
1577 self.interact(banner)
1578 #self.interact_with_readline()
1578 #self.interact_with_readline()
1579 # XXX for testing of a readline-decoupled repl loop, call interact_with_readline above
1579 # XXX for testing of a readline-decoupled repl loop, call interact_with_readline above
1580
1580
1581 break
1581 break
1582 except KeyboardInterrupt:
1582 except KeyboardInterrupt:
1583 # this should not be necessary, but KeyboardInterrupt
1583 # this should not be necessary, but KeyboardInterrupt
1584 # handling seems rather unpredictable...
1584 # handling seems rather unpredictable...
1585 self.write("\nKeyboardInterrupt in interact()\n")
1585 self.write("\nKeyboardInterrupt in interact()\n")
1586
1586
1587 def exec_init_cmd(self):
1587 def exec_init_cmd(self):
1588 """Execute a command given at the command line.
1588 """Execute a command given at the command line.
1589
1589
1590 This emulates Python's -c option."""
1590 This emulates Python's -c option."""
1591
1591
1592 #sys.argv = ['-c']
1592 #sys.argv = ['-c']
1593 self.push(self.prefilter(self.rc.c, False))
1593 self.push(self.prefilter(self.rc.c, False))
1594 if not self.rc.interact:
1594 if not self.rc.interact:
1595 self.exit_now = True
1595 self.ask_exit()
1596
1596
1597 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1597 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1598 """Embeds IPython into a running python program.
1598 """Embeds IPython into a running python program.
1599
1599
1600 Input:
1600 Input:
1601
1601
1602 - header: An optional header message can be specified.
1602 - header: An optional header message can be specified.
1603
1603
1604 - local_ns, global_ns: working namespaces. If given as None, the
1604 - local_ns, global_ns: working namespaces. If given as None, the
1605 IPython-initialized one is updated with __main__.__dict__, so that
1605 IPython-initialized one is updated with __main__.__dict__, so that
1606 program variables become visible but user-specific configuration
1606 program variables become visible but user-specific configuration
1607 remains possible.
1607 remains possible.
1608
1608
1609 - stack_depth: specifies how many levels in the stack to go to
1609 - stack_depth: specifies how many levels in the stack to go to
1610 looking for namespaces (when local_ns and global_ns are None). This
1610 looking for namespaces (when local_ns and global_ns are None). This
1611 allows an intermediate caller to make sure that this function gets
1611 allows an intermediate caller to make sure that this function gets
1612 the namespace from the intended level in the stack. By default (0)
1612 the namespace from the intended level in the stack. By default (0)
1613 it will get its locals and globals from the immediate caller.
1613 it will get its locals and globals from the immediate caller.
1614
1614
1615 Warning: it's possible to use this in a program which is being run by
1615 Warning: it's possible to use this in a program which is being run by
1616 IPython itself (via %run), but some funny things will happen (a few
1616 IPython itself (via %run), but some funny things will happen (a few
1617 globals get overwritten). In the future this will be cleaned up, as
1617 globals get overwritten). In the future this will be cleaned up, as
1618 there is no fundamental reason why it can't work perfectly."""
1618 there is no fundamental reason why it can't work perfectly."""
1619
1619
1620 # Get locals and globals from caller
1620 # Get locals and globals from caller
1621 if local_ns is None or global_ns is None:
1621 if local_ns is None or global_ns is None:
1622 call_frame = sys._getframe(stack_depth).f_back
1622 call_frame = sys._getframe(stack_depth).f_back
1623
1623
1624 if local_ns is None:
1624 if local_ns is None:
1625 local_ns = call_frame.f_locals
1625 local_ns = call_frame.f_locals
1626 if global_ns is None:
1626 if global_ns is None:
1627 global_ns = call_frame.f_globals
1627 global_ns = call_frame.f_globals
1628
1628
1629 # Update namespaces and fire up interpreter
1629 # Update namespaces and fire up interpreter
1630
1630
1631 # The global one is easy, we can just throw it in
1631 # The global one is easy, we can just throw it in
1632 self.user_global_ns = global_ns
1632 self.user_global_ns = global_ns
1633
1633
1634 # but the user/local one is tricky: ipython needs it to store internal
1634 # but the user/local one is tricky: ipython needs it to store internal
1635 # data, but we also need the locals. We'll copy locals in the user
1635 # data, but we also need the locals. We'll copy locals in the user
1636 # one, but will track what got copied so we can delete them at exit.
1636 # one, but will track what got copied so we can delete them at exit.
1637 # This is so that a later embedded call doesn't see locals from a
1637 # This is so that a later embedded call doesn't see locals from a
1638 # previous call (which most likely existed in a separate scope).
1638 # previous call (which most likely existed in a separate scope).
1639 local_varnames = local_ns.keys()
1639 local_varnames = local_ns.keys()
1640 self.user_ns.update(local_ns)
1640 self.user_ns.update(local_ns)
1641 #self.user_ns['local_ns'] = local_ns # dbg
1641 #self.user_ns['local_ns'] = local_ns # dbg
1642
1642
1643 # Patch for global embedding to make sure that things don't overwrite
1643 # Patch for global embedding to make sure that things don't overwrite
1644 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1644 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1645 # FIXME. Test this a bit more carefully (the if.. is new)
1645 # FIXME. Test this a bit more carefully (the if.. is new)
1646 if local_ns is None and global_ns is None:
1646 if local_ns is None and global_ns is None:
1647 self.user_global_ns.update(__main__.__dict__)
1647 self.user_global_ns.update(__main__.__dict__)
1648
1648
1649 # make sure the tab-completer has the correct frame information, so it
1649 # make sure the tab-completer has the correct frame information, so it
1650 # actually completes using the frame's locals/globals
1650 # actually completes using the frame's locals/globals
1651 self.set_completer_frame()
1651 self.set_completer_frame()
1652
1652
1653 # before activating the interactive mode, we need to make sure that
1653 # before activating the interactive mode, we need to make sure that
1654 # all names in the builtin namespace needed by ipython point to
1654 # all names in the builtin namespace needed by ipython point to
1655 # ourselves, and not to other instances.
1655 # ourselves, and not to other instances.
1656 self.add_builtins()
1656 self.add_builtins()
1657
1657
1658 self.interact(header)
1658 self.interact(header)
1659
1659
1660 # now, purge out the user namespace from anything we might have added
1660 # now, purge out the user namespace from anything we might have added
1661 # from the caller's local namespace
1661 # from the caller's local namespace
1662 delvar = self.user_ns.pop
1662 delvar = self.user_ns.pop
1663 for var in local_varnames:
1663 for var in local_varnames:
1664 delvar(var,None)
1664 delvar(var,None)
1665 # and clean builtins we may have overridden
1665 # and clean builtins we may have overridden
1666 self.clean_builtins()
1666 self.clean_builtins()
1667
1667
1668 def interact_prompt(self):
1668 def interact_prompt(self):
1669 """ Print the prompt (in read-eval-print loop)
1669 """ Print the prompt (in read-eval-print loop)
1670
1670
1671 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1671 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1672 used in standard IPython flow.
1672 used in standard IPython flow.
1673 """
1673 """
1674 if self.more:
1674 if self.more:
1675 try:
1675 try:
1676 prompt = self.hooks.generate_prompt(True)
1676 prompt = self.hooks.generate_prompt(True)
1677 except:
1677 except:
1678 self.showtraceback()
1678 self.showtraceback()
1679 if self.autoindent:
1679 if self.autoindent:
1680 self.rl_do_indent = True
1680 self.rl_do_indent = True
1681
1681
1682 else:
1682 else:
1683 try:
1683 try:
1684 prompt = self.hooks.generate_prompt(False)
1684 prompt = self.hooks.generate_prompt(False)
1685 except:
1685 except:
1686 self.showtraceback()
1686 self.showtraceback()
1687 self.write(prompt)
1687 self.write(prompt)
1688
1688
1689 def interact_handle_input(self,line):
1689 def interact_handle_input(self,line):
1690 """ Handle the input line (in read-eval-print loop)
1690 """ Handle the input line (in read-eval-print loop)
1691
1691
1692 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1692 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1693 used in standard IPython flow.
1693 used in standard IPython flow.
1694 """
1694 """
1695 if line.lstrip() == line:
1695 if line.lstrip() == line:
1696 self.shadowhist.add(line.strip())
1696 self.shadowhist.add(line.strip())
1697 lineout = self.prefilter(line,self.more)
1697 lineout = self.prefilter(line,self.more)
1698
1698
1699 if line.strip():
1699 if line.strip():
1700 if self.more:
1700 if self.more:
1701 self.input_hist_raw[-1] += '%s\n' % line
1701 self.input_hist_raw[-1] += '%s\n' % line
1702 else:
1702 else:
1703 self.input_hist_raw.append('%s\n' % line)
1703 self.input_hist_raw.append('%s\n' % line)
1704
1704
1705
1705
1706 self.more = self.push(lineout)
1706 self.more = self.push(lineout)
1707 if (self.SyntaxTB.last_syntax_error and
1707 if (self.SyntaxTB.last_syntax_error and
1708 self.rc.autoedit_syntax):
1708 self.rc.autoedit_syntax):
1709 self.edit_syntax_error()
1709 self.edit_syntax_error()
1710
1710
1711 def interact_with_readline(self):
1711 def interact_with_readline(self):
1712 """ Demo of using interact_handle_input, interact_prompt
1712 """ Demo of using interact_handle_input, interact_prompt
1713
1713
1714 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1714 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1715 it should work like this.
1715 it should work like this.
1716 """
1716 """
1717 self.readline_startup_hook(self.pre_readline)
1717 self.readline_startup_hook(self.pre_readline)
1718 while not self.exit_now:
1718 while not self.exit_now:
1719 self.interact_prompt()
1719 self.interact_prompt()
1720 if self.more:
1720 if self.more:
1721 self.rl_do_indent = True
1721 self.rl_do_indent = True
1722 else:
1722 else:
1723 self.rl_do_indent = False
1723 self.rl_do_indent = False
1724 line = raw_input_original().decode(self.stdin_encoding)
1724 line = raw_input_original().decode(self.stdin_encoding)
1725 self.interact_handle_input(line)
1725 self.interact_handle_input(line)
1726
1726
1727
1727
1728 def interact(self, banner=None):
1728 def interact(self, banner=None):
1729 """Closely emulate the interactive Python console.
1729 """Closely emulate the interactive Python console.
1730
1730
1731 The optional banner argument specify the banner to print
1731 The optional banner argument specify the banner to print
1732 before the first interaction; by default it prints a banner
1732 before the first interaction; by default it prints a banner
1733 similar to the one printed by the real Python interpreter,
1733 similar to the one printed by the real Python interpreter,
1734 followed by the current class name in parentheses (so as not
1734 followed by the current class name in parentheses (so as not
1735 to confuse this with the real interpreter -- since it's so
1735 to confuse this with the real interpreter -- since it's so
1736 close!).
1736 close!).
1737
1737
1738 """
1738 """
1739
1739
1740 if self.exit_now:
1740 if self.exit_now:
1741 # batch run -> do not interact
1741 # batch run -> do not interact
1742 return
1742 return
1743 cprt = 'Type "copyright", "credits" or "license" for more information.'
1743 cprt = 'Type "copyright", "credits" or "license" for more information.'
1744 if banner is None:
1744 if banner is None:
1745 self.write("Python %s on %s\n%s\n(%s)\n" %
1745 self.write("Python %s on %s\n%s\n(%s)\n" %
1746 (sys.version, sys.platform, cprt,
1746 (sys.version, sys.platform, cprt,
1747 self.__class__.__name__))
1747 self.__class__.__name__))
1748 else:
1748 else:
1749 self.write(banner)
1749 self.write(banner)
1750
1750
1751 more = 0
1751 more = 0
1752
1752
1753 # Mark activity in the builtins
1753 # Mark activity in the builtins
1754 __builtin__.__dict__['__IPYTHON__active'] += 1
1754 __builtin__.__dict__['__IPYTHON__active'] += 1
1755
1755
1756 if self.has_readline:
1756 if self.has_readline:
1757 self.readline_startup_hook(self.pre_readline)
1757 self.readline_startup_hook(self.pre_readline)
1758 # exit_now is set by a call to %Exit or %Quit
1758 # exit_now is set by a call to %Exit or %Quit, through the
1759 # ask_exit callback.
1759
1760
1760 while not self.exit_now:
1761 while not self.exit_now:
1761 self.hooks.pre_prompt_hook()
1762 self.hooks.pre_prompt_hook()
1762 if more:
1763 if more:
1763 try:
1764 try:
1764 prompt = self.hooks.generate_prompt(True)
1765 prompt = self.hooks.generate_prompt(True)
1765 except:
1766 except:
1766 self.showtraceback()
1767 self.showtraceback()
1767 if self.autoindent:
1768 if self.autoindent:
1768 self.rl_do_indent = True
1769 self.rl_do_indent = True
1769
1770
1770 else:
1771 else:
1771 try:
1772 try:
1772 prompt = self.hooks.generate_prompt(False)
1773 prompt = self.hooks.generate_prompt(False)
1773 except:
1774 except:
1774 self.showtraceback()
1775 self.showtraceback()
1775 try:
1776 try:
1776 line = self.raw_input(prompt,more)
1777 line = self.raw_input(prompt,more)
1777 if self.exit_now:
1778 if self.exit_now:
1778 # quick exit on sys.std[in|out] close
1779 # quick exit on sys.std[in|out] close
1779 break
1780 break
1780 if self.autoindent:
1781 if self.autoindent:
1781 self.rl_do_indent = False
1782 self.rl_do_indent = False
1782
1783
1783 except KeyboardInterrupt:
1784 except KeyboardInterrupt:
1784 #double-guard against keyboardinterrupts during kbdint handling
1785 #double-guard against keyboardinterrupts during kbdint handling
1785 try:
1786 try:
1786 self.write('\nKeyboardInterrupt\n')
1787 self.write('\nKeyboardInterrupt\n')
1787 self.resetbuffer()
1788 self.resetbuffer()
1788 # keep cache in sync with the prompt counter:
1789 # keep cache in sync with the prompt counter:
1789 self.outputcache.prompt_count -= 1
1790 self.outputcache.prompt_count -= 1
1790
1791
1791 if self.autoindent:
1792 if self.autoindent:
1792 self.indent_current_nsp = 0
1793 self.indent_current_nsp = 0
1793 more = 0
1794 more = 0
1794 except KeyboardInterrupt:
1795 except KeyboardInterrupt:
1795 pass
1796 pass
1796 except EOFError:
1797 except EOFError:
1797 if self.autoindent:
1798 if self.autoindent:
1798 self.rl_do_indent = False
1799 self.rl_do_indent = False
1799 self.readline_startup_hook(None)
1800 self.readline_startup_hook(None)
1800 self.write('\n')
1801 self.write('\n')
1801 self.exit()
1802 self.exit()
1802 except bdb.BdbQuit:
1803 except bdb.BdbQuit:
1803 warn('The Python debugger has exited with a BdbQuit exception.\n'
1804 warn('The Python debugger has exited with a BdbQuit exception.\n'
1804 'Because of how pdb handles the stack, it is impossible\n'
1805 'Because of how pdb handles the stack, it is impossible\n'
1805 'for IPython to properly format this particular exception.\n'
1806 'for IPython to properly format this particular exception.\n'
1806 'IPython will resume normal operation.')
1807 'IPython will resume normal operation.')
1807 except:
1808 except:
1808 # exceptions here are VERY RARE, but they can be triggered
1809 # exceptions here are VERY RARE, but they can be triggered
1809 # asynchronously by signal handlers, for example.
1810 # asynchronously by signal handlers, for example.
1810 self.showtraceback()
1811 self.showtraceback()
1811 else:
1812 else:
1812 more = self.push(line)
1813 more = self.push(line)
1813 if (self.SyntaxTB.last_syntax_error and
1814 if (self.SyntaxTB.last_syntax_error and
1814 self.rc.autoedit_syntax):
1815 self.rc.autoedit_syntax):
1815 self.edit_syntax_error()
1816 self.edit_syntax_error()
1816
1817
1817 # We are off again...
1818 # We are off again...
1818 __builtin__.__dict__['__IPYTHON__active'] -= 1
1819 __builtin__.__dict__['__IPYTHON__active'] -= 1
1819
1820
1820 def excepthook(self, etype, value, tb):
1821 def excepthook(self, etype, value, tb):
1821 """One more defense for GUI apps that call sys.excepthook.
1822 """One more defense for GUI apps that call sys.excepthook.
1822
1823
1823 GUI frameworks like wxPython trap exceptions and call
1824 GUI frameworks like wxPython trap exceptions and call
1824 sys.excepthook themselves. I guess this is a feature that
1825 sys.excepthook themselves. I guess this is a feature that
1825 enables them to keep running after exceptions that would
1826 enables them to keep running after exceptions that would
1826 otherwise kill their mainloop. This is a bother for IPython
1827 otherwise kill their mainloop. This is a bother for IPython
1827 which excepts to catch all of the program exceptions with a try:
1828 which excepts to catch all of the program exceptions with a try:
1828 except: statement.
1829 except: statement.
1829
1830
1830 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1831 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1831 any app directly invokes sys.excepthook, it will look to the user like
1832 any app directly invokes sys.excepthook, it will look to the user like
1832 IPython crashed. In order to work around this, we can disable the
1833 IPython crashed. In order to work around this, we can disable the
1833 CrashHandler and replace it with this excepthook instead, which prints a
1834 CrashHandler and replace it with this excepthook instead, which prints a
1834 regular traceback using our InteractiveTB. In this fashion, apps which
1835 regular traceback using our InteractiveTB. In this fashion, apps which
1835 call sys.excepthook will generate a regular-looking exception from
1836 call sys.excepthook will generate a regular-looking exception from
1836 IPython, and the CrashHandler will only be triggered by real IPython
1837 IPython, and the CrashHandler will only be triggered by real IPython
1837 crashes.
1838 crashes.
1838
1839
1839 This hook should be used sparingly, only in places which are not likely
1840 This hook should be used sparingly, only in places which are not likely
1840 to be true IPython errors.
1841 to be true IPython errors.
1841 """
1842 """
1842 self.showtraceback((etype,value,tb),tb_offset=0)
1843 self.showtraceback((etype,value,tb),tb_offset=0)
1843
1844
1844 def expand_aliases(self,fn,rest):
1845 def expand_aliases(self,fn,rest):
1845 """ Expand multiple levels of aliases:
1846 """ Expand multiple levels of aliases:
1846
1847
1847 if:
1848 if:
1848
1849
1849 alias foo bar /tmp
1850 alias foo bar /tmp
1850 alias baz foo
1851 alias baz foo
1851
1852
1852 then:
1853 then:
1853
1854
1854 baz huhhahhei -> bar /tmp huhhahhei
1855 baz huhhahhei -> bar /tmp huhhahhei
1855
1856
1856 """
1857 """
1857 line = fn + " " + rest
1858 line = fn + " " + rest
1858
1859
1859 done = Set()
1860 done = Set()
1860 while 1:
1861 while 1:
1861 pre,fn,rest = prefilter.splitUserInput(line,
1862 pre,fn,rest = prefilter.splitUserInput(line,
1862 prefilter.shell_line_split)
1863 prefilter.shell_line_split)
1863 if fn in self.alias_table:
1864 if fn in self.alias_table:
1864 if fn in done:
1865 if fn in done:
1865 warn("Cyclic alias definition, repeated '%s'" % fn)
1866 warn("Cyclic alias definition, repeated '%s'" % fn)
1866 return ""
1867 return ""
1867 done.add(fn)
1868 done.add(fn)
1868
1869
1869 l2 = self.transform_alias(fn,rest)
1870 l2 = self.transform_alias(fn,rest)
1870 # dir -> dir
1871 # dir -> dir
1871 # print "alias",line, "->",l2 #dbg
1872 # print "alias",line, "->",l2 #dbg
1872 if l2 == line:
1873 if l2 == line:
1873 break
1874 break
1874 # ls -> ls -F should not recurse forever
1875 # ls -> ls -F should not recurse forever
1875 if l2.split(None,1)[0] == line.split(None,1)[0]:
1876 if l2.split(None,1)[0] == line.split(None,1)[0]:
1876 line = l2
1877 line = l2
1877 break
1878 break
1878
1879
1879 line=l2
1880 line=l2
1880
1881
1881
1882
1882 # print "al expand to",line #dbg
1883 # print "al expand to",line #dbg
1883 else:
1884 else:
1884 break
1885 break
1885
1886
1886 return line
1887 return line
1887
1888
1888 def transform_alias(self, alias,rest=''):
1889 def transform_alias(self, alias,rest=''):
1889 """ Transform alias to system command string.
1890 """ Transform alias to system command string.
1890 """
1891 """
1891 trg = self.alias_table[alias]
1892 trg = self.alias_table[alias]
1892
1893
1893 nargs,cmd = trg
1894 nargs,cmd = trg
1894 # print trg #dbg
1895 # print trg #dbg
1895 if ' ' in cmd and os.path.isfile(cmd):
1896 if ' ' in cmd and os.path.isfile(cmd):
1896 cmd = '"%s"' % cmd
1897 cmd = '"%s"' % cmd
1897
1898
1898 # Expand the %l special to be the user's input line
1899 # Expand the %l special to be the user's input line
1899 if cmd.find('%l') >= 0:
1900 if cmd.find('%l') >= 0:
1900 cmd = cmd.replace('%l',rest)
1901 cmd = cmd.replace('%l',rest)
1901 rest = ''
1902 rest = ''
1902 if nargs==0:
1903 if nargs==0:
1903 # Simple, argument-less aliases
1904 # Simple, argument-less aliases
1904 cmd = '%s %s' % (cmd,rest)
1905 cmd = '%s %s' % (cmd,rest)
1905 else:
1906 else:
1906 # Handle aliases with positional arguments
1907 # Handle aliases with positional arguments
1907 args = rest.split(None,nargs)
1908 args = rest.split(None,nargs)
1908 if len(args)< nargs:
1909 if len(args)< nargs:
1909 error('Alias <%s> requires %s arguments, %s given.' %
1910 error('Alias <%s> requires %s arguments, %s given.' %
1910 (alias,nargs,len(args)))
1911 (alias,nargs,len(args)))
1911 return None
1912 return None
1912 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1913 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1913 # Now call the macro, evaluating in the user's namespace
1914 # Now call the macro, evaluating in the user's namespace
1914 #print 'new command: <%r>' % cmd # dbg
1915 #print 'new command: <%r>' % cmd # dbg
1915 return cmd
1916 return cmd
1916
1917
1917 def call_alias(self,alias,rest=''):
1918 def call_alias(self,alias,rest=''):
1918 """Call an alias given its name and the rest of the line.
1919 """Call an alias given its name and the rest of the line.
1919
1920
1920 This is only used to provide backwards compatibility for users of
1921 This is only used to provide backwards compatibility for users of
1921 ipalias(), use of which is not recommended for anymore."""
1922 ipalias(), use of which is not recommended for anymore."""
1922
1923
1923 # Now call the macro, evaluating in the user's namespace
1924 # Now call the macro, evaluating in the user's namespace
1924 cmd = self.transform_alias(alias, rest)
1925 cmd = self.transform_alias(alias, rest)
1925 try:
1926 try:
1926 self.system(cmd)
1927 self.system(cmd)
1927 except:
1928 except:
1928 self.showtraceback()
1929 self.showtraceback()
1929
1930
1930 def indent_current_str(self):
1931 def indent_current_str(self):
1931 """return the current level of indentation as a string"""
1932 """return the current level of indentation as a string"""
1932 return self.indent_current_nsp * ' '
1933 return self.indent_current_nsp * ' '
1933
1934
1934 def autoindent_update(self,line):
1935 def autoindent_update(self,line):
1935 """Keep track of the indent level."""
1936 """Keep track of the indent level."""
1936
1937
1937 #debugx('line')
1938 #debugx('line')
1938 #debugx('self.indent_current_nsp')
1939 #debugx('self.indent_current_nsp')
1939 if self.autoindent:
1940 if self.autoindent:
1940 if line:
1941 if line:
1941 inisp = num_ini_spaces(line)
1942 inisp = num_ini_spaces(line)
1942 if inisp < self.indent_current_nsp:
1943 if inisp < self.indent_current_nsp:
1943 self.indent_current_nsp = inisp
1944 self.indent_current_nsp = inisp
1944
1945
1945 if line[-1] == ':':
1946 if line[-1] == ':':
1946 self.indent_current_nsp += 4
1947 self.indent_current_nsp += 4
1947 elif dedent_re.match(line):
1948 elif dedent_re.match(line):
1948 self.indent_current_nsp -= 4
1949 self.indent_current_nsp -= 4
1949 else:
1950 else:
1950 self.indent_current_nsp = 0
1951 self.indent_current_nsp = 0
1951
1952
1952 def runlines(self,lines):
1953 def runlines(self,lines):
1953 """Run a string of one or more lines of source.
1954 """Run a string of one or more lines of source.
1954
1955
1955 This method is capable of running a string containing multiple source
1956 This method is capable of running a string containing multiple source
1956 lines, as if they had been entered at the IPython prompt. Since it
1957 lines, as if they had been entered at the IPython prompt. Since it
1957 exposes IPython's processing machinery, the given strings can contain
1958 exposes IPython's processing machinery, the given strings can contain
1958 magic calls (%magic), special shell access (!cmd), etc."""
1959 magic calls (%magic), special shell access (!cmd), etc."""
1959
1960
1960 # We must start with a clean buffer, in case this is run from an
1961 # We must start with a clean buffer, in case this is run from an
1961 # interactive IPython session (via a magic, for example).
1962 # interactive IPython session (via a magic, for example).
1962 self.resetbuffer()
1963 self.resetbuffer()
1963 lines = lines.split('\n')
1964 lines = lines.split('\n')
1964 more = 0
1965 more = 0
1965
1966
1966 for line in lines:
1967 for line in lines:
1967 # skip blank lines so we don't mess up the prompt counter, but do
1968 # skip blank lines so we don't mess up the prompt counter, but do
1968 # NOT skip even a blank line if we are in a code block (more is
1969 # NOT skip even a blank line if we are in a code block (more is
1969 # true)
1970 # true)
1970
1971
1971
1972
1972 if line or more:
1973 if line or more:
1973 # push to raw history, so hist line numbers stay in sync
1974 # push to raw history, so hist line numbers stay in sync
1974 self.input_hist_raw.append("# " + line + "\n")
1975 self.input_hist_raw.append("# " + line + "\n")
1975 more = self.push(self.prefilter(line,more))
1976 more = self.push(self.prefilter(line,more))
1976 # IPython's runsource returns None if there was an error
1977 # IPython's runsource returns None if there was an error
1977 # compiling the code. This allows us to stop processing right
1978 # compiling the code. This allows us to stop processing right
1978 # away, so the user gets the error message at the right place.
1979 # away, so the user gets the error message at the right place.
1979 if more is None:
1980 if more is None:
1980 break
1981 break
1981 else:
1982 else:
1982 self.input_hist_raw.append("\n")
1983 self.input_hist_raw.append("\n")
1983 # final newline in case the input didn't have it, so that the code
1984 # final newline in case the input didn't have it, so that the code
1984 # actually does get executed
1985 # actually does get executed
1985 if more:
1986 if more:
1986 self.push('\n')
1987 self.push('\n')
1987
1988
1988 def runsource(self, source, filename='<input>', symbol='single'):
1989 def runsource(self, source, filename='<input>', symbol='single'):
1989 """Compile and run some source in the interpreter.
1990 """Compile and run some source in the interpreter.
1990
1991
1991 Arguments are as for compile_command().
1992 Arguments are as for compile_command().
1992
1993
1993 One several things can happen:
1994 One several things can happen:
1994
1995
1995 1) The input is incorrect; compile_command() raised an
1996 1) The input is incorrect; compile_command() raised an
1996 exception (SyntaxError or OverflowError). A syntax traceback
1997 exception (SyntaxError or OverflowError). A syntax traceback
1997 will be printed by calling the showsyntaxerror() method.
1998 will be printed by calling the showsyntaxerror() method.
1998
1999
1999 2) The input is incomplete, and more input is required;
2000 2) The input is incomplete, and more input is required;
2000 compile_command() returned None. Nothing happens.
2001 compile_command() returned None. Nothing happens.
2001
2002
2002 3) The input is complete; compile_command() returned a code
2003 3) The input is complete; compile_command() returned a code
2003 object. The code is executed by calling self.runcode() (which
2004 object. The code is executed by calling self.runcode() (which
2004 also handles run-time exceptions, except for SystemExit).
2005 also handles run-time exceptions, except for SystemExit).
2005
2006
2006 The return value is:
2007 The return value is:
2007
2008
2008 - True in case 2
2009 - True in case 2
2009
2010
2010 - False in the other cases, unless an exception is raised, where
2011 - False in the other cases, unless an exception is raised, where
2011 None is returned instead. This can be used by external callers to
2012 None is returned instead. This can be used by external callers to
2012 know whether to continue feeding input or not.
2013 know whether to continue feeding input or not.
2013
2014
2014 The return value can be used to decide whether to use sys.ps1 or
2015 The return value can be used to decide whether to use sys.ps1 or
2015 sys.ps2 to prompt the next line."""
2016 sys.ps2 to prompt the next line."""
2016
2017
2017 # if the source code has leading blanks, add 'if 1:\n' to it
2018 # if the source code has leading blanks, add 'if 1:\n' to it
2018 # this allows execution of indented pasted code. It is tempting
2019 # this allows execution of indented pasted code. It is tempting
2019 # to add '\n' at the end of source to run commands like ' a=1'
2020 # to add '\n' at the end of source to run commands like ' a=1'
2020 # directly, but this fails for more complicated scenarios
2021 # directly, but this fails for more complicated scenarios
2021 source=source.encode(self.stdin_encoding)
2022 source=source.encode(self.stdin_encoding)
2022 if source[:1] in [' ', '\t']:
2023 if source[:1] in [' ', '\t']:
2023 source = 'if 1:\n%s' % source
2024 source = 'if 1:\n%s' % source
2024
2025
2025 try:
2026 try:
2026 code = self.compile(source,filename,symbol)
2027 code = self.compile(source,filename,symbol)
2027 except (OverflowError, SyntaxError, ValueError, TypeError):
2028 except (OverflowError, SyntaxError, ValueError, TypeError):
2028 # Case 1
2029 # Case 1
2029 self.showsyntaxerror(filename)
2030 self.showsyntaxerror(filename)
2030 return None
2031 return None
2031
2032
2032 if code is None:
2033 if code is None:
2033 # Case 2
2034 # Case 2
2034 return True
2035 return True
2035
2036
2036 # Case 3
2037 # Case 3
2037 # We store the code object so that threaded shells and
2038 # We store the code object so that threaded shells and
2038 # custom exception handlers can access all this info if needed.
2039 # custom exception handlers can access all this info if needed.
2039 # The source corresponding to this can be obtained from the
2040 # The source corresponding to this can be obtained from the
2040 # buffer attribute as '\n'.join(self.buffer).
2041 # buffer attribute as '\n'.join(self.buffer).
2041 self.code_to_run = code
2042 self.code_to_run = code
2042 # now actually execute the code object
2043 # now actually execute the code object
2043 if self.runcode(code) == 0:
2044 if self.runcode(code) == 0:
2044 return False
2045 return False
2045 else:
2046 else:
2046 return None
2047 return None
2047
2048
2048 def runcode(self,code_obj):
2049 def runcode(self,code_obj):
2049 """Execute a code object.
2050 """Execute a code object.
2050
2051
2051 When an exception occurs, self.showtraceback() is called to display a
2052 When an exception occurs, self.showtraceback() is called to display a
2052 traceback.
2053 traceback.
2053
2054
2054 Return value: a flag indicating whether the code to be run completed
2055 Return value: a flag indicating whether the code to be run completed
2055 successfully:
2056 successfully:
2056
2057
2057 - 0: successful execution.
2058 - 0: successful execution.
2058 - 1: an error occurred.
2059 - 1: an error occurred.
2059 """
2060 """
2060
2061
2061 # Set our own excepthook in case the user code tries to call it
2062 # Set our own excepthook in case the user code tries to call it
2062 # directly, so that the IPython crash handler doesn't get triggered
2063 # directly, so that the IPython crash handler doesn't get triggered
2063 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2064 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2064
2065
2065 # we save the original sys.excepthook in the instance, in case config
2066 # we save the original sys.excepthook in the instance, in case config
2066 # code (such as magics) needs access to it.
2067 # code (such as magics) needs access to it.
2067 self.sys_excepthook = old_excepthook
2068 self.sys_excepthook = old_excepthook
2068 outflag = 1 # happens in more places, so it's easier as default
2069 outflag = 1 # happens in more places, so it's easier as default
2069 try:
2070 try:
2070 try:
2071 try:
2071 self.hooks.pre_runcode_hook()
2072 self.hooks.pre_runcode_hook()
2072 exec code_obj in self.user_global_ns, self.user_ns
2073 exec code_obj in self.user_global_ns, self.user_ns
2073 finally:
2074 finally:
2074 # Reset our crash handler in place
2075 # Reset our crash handler in place
2075 sys.excepthook = old_excepthook
2076 sys.excepthook = old_excepthook
2076 except SystemExit:
2077 except SystemExit:
2077 self.resetbuffer()
2078 self.resetbuffer()
2078 self.showtraceback()
2079 self.showtraceback()
2079 warn("Type %exit or %quit to exit IPython "
2080 warn("Type %exit or %quit to exit IPython "
2080 "(%Exit or %Quit do so unconditionally).",level=1)
2081 "(%Exit or %Quit do so unconditionally).",level=1)
2081 except self.custom_exceptions:
2082 except self.custom_exceptions:
2082 etype,value,tb = sys.exc_info()
2083 etype,value,tb = sys.exc_info()
2083 self.CustomTB(etype,value,tb)
2084 self.CustomTB(etype,value,tb)
2084 except:
2085 except:
2085 self.showtraceback()
2086 self.showtraceback()
2086 else:
2087 else:
2087 outflag = 0
2088 outflag = 0
2088 if softspace(sys.stdout, 0):
2089 if softspace(sys.stdout, 0):
2089 print
2090 print
2090 # Flush out code object which has been run (and source)
2091 # Flush out code object which has been run (and source)
2091 self.code_to_run = None
2092 self.code_to_run = None
2092 return outflag
2093 return outflag
2093
2094
2094 def push(self, line):
2095 def push(self, line):
2095 """Push a line to the interpreter.
2096 """Push a line to the interpreter.
2096
2097
2097 The line should not have a trailing newline; it may have
2098 The line should not have a trailing newline; it may have
2098 internal newlines. The line is appended to a buffer and the
2099 internal newlines. The line is appended to a buffer and the
2099 interpreter's runsource() method is called with the
2100 interpreter's runsource() method is called with the
2100 concatenated contents of the buffer as source. If this
2101 concatenated contents of the buffer as source. If this
2101 indicates that the command was executed or invalid, the buffer
2102 indicates that the command was executed or invalid, the buffer
2102 is reset; otherwise, the command is incomplete, and the buffer
2103 is reset; otherwise, the command is incomplete, and the buffer
2103 is left as it was after the line was appended. The return
2104 is left as it was after the line was appended. The return
2104 value is 1 if more input is required, 0 if the line was dealt
2105 value is 1 if more input is required, 0 if the line was dealt
2105 with in some way (this is the same as runsource()).
2106 with in some way (this is the same as runsource()).
2106 """
2107 """
2107
2108
2108 # autoindent management should be done here, and not in the
2109 # autoindent management should be done here, and not in the
2109 # interactive loop, since that one is only seen by keyboard input. We
2110 # interactive loop, since that one is only seen by keyboard input. We
2110 # need this done correctly even for code run via runlines (which uses
2111 # need this done correctly even for code run via runlines (which uses
2111 # push).
2112 # push).
2112
2113
2113 #print 'push line: <%s>' % line # dbg
2114 #print 'push line: <%s>' % line # dbg
2114 for subline in line.splitlines():
2115 for subline in line.splitlines():
2115 self.autoindent_update(subline)
2116 self.autoindent_update(subline)
2116 self.buffer.append(line)
2117 self.buffer.append(line)
2117 more = self.runsource('\n'.join(self.buffer), self.filename)
2118 more = self.runsource('\n'.join(self.buffer), self.filename)
2118 if not more:
2119 if not more:
2119 self.resetbuffer()
2120 self.resetbuffer()
2120 return more
2121 return more
2121
2122
2122 def split_user_input(self, line):
2123 def split_user_input(self, line):
2123 # This is really a hold-over to support ipapi and some extensions
2124 # This is really a hold-over to support ipapi and some extensions
2124 return prefilter.splitUserInput(line)
2125 return prefilter.splitUserInput(line)
2125
2126
2126 def resetbuffer(self):
2127 def resetbuffer(self):
2127 """Reset the input buffer."""
2128 """Reset the input buffer."""
2128 self.buffer[:] = []
2129 self.buffer[:] = []
2129
2130
2130 def raw_input(self,prompt='',continue_prompt=False):
2131 def raw_input(self,prompt='',continue_prompt=False):
2131 """Write a prompt and read a line.
2132 """Write a prompt and read a line.
2132
2133
2133 The returned line does not include the trailing newline.
2134 The returned line does not include the trailing newline.
2134 When the user enters the EOF key sequence, EOFError is raised.
2135 When the user enters the EOF key sequence, EOFError is raised.
2135
2136
2136 Optional inputs:
2137 Optional inputs:
2137
2138
2138 - prompt(''): a string to be printed to prompt the user.
2139 - prompt(''): a string to be printed to prompt the user.
2139
2140
2140 - continue_prompt(False): whether this line is the first one or a
2141 - continue_prompt(False): whether this line is the first one or a
2141 continuation in a sequence of inputs.
2142 continuation in a sequence of inputs.
2142 """
2143 """
2143
2144
2144 # Code run by the user may have modified the readline completer state.
2145 # Code run by the user may have modified the readline completer state.
2145 # We must ensure that our completer is back in place.
2146 # We must ensure that our completer is back in place.
2146 if self.has_readline:
2147 if self.has_readline:
2147 self.set_completer()
2148 self.set_completer()
2148
2149
2149 try:
2150 try:
2150 line = raw_input_original(prompt).decode(self.stdin_encoding)
2151 line = raw_input_original(prompt).decode(self.stdin_encoding)
2151 except ValueError:
2152 except ValueError:
2152 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2153 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2153 " or sys.stdout.close()!\nExiting IPython!")
2154 " or sys.stdout.close()!\nExiting IPython!")
2154 self.exit_now = True
2155 self.ask_exit()
2155 return ""
2156 return ""
2156
2157
2157 # Try to be reasonably smart about not re-indenting pasted input more
2158 # Try to be reasonably smart about not re-indenting pasted input more
2158 # than necessary. We do this by trimming out the auto-indent initial
2159 # than necessary. We do this by trimming out the auto-indent initial
2159 # spaces, if the user's actual input started itself with whitespace.
2160 # spaces, if the user's actual input started itself with whitespace.
2160 #debugx('self.buffer[-1]')
2161 #debugx('self.buffer[-1]')
2161
2162
2162 if self.autoindent:
2163 if self.autoindent:
2163 if num_ini_spaces(line) > self.indent_current_nsp:
2164 if num_ini_spaces(line) > self.indent_current_nsp:
2164 line = line[self.indent_current_nsp:]
2165 line = line[self.indent_current_nsp:]
2165 self.indent_current_nsp = 0
2166 self.indent_current_nsp = 0
2166
2167
2167 # store the unfiltered input before the user has any chance to modify
2168 # store the unfiltered input before the user has any chance to modify
2168 # it.
2169 # it.
2169 if line.strip():
2170 if line.strip():
2170 if continue_prompt:
2171 if continue_prompt:
2171 self.input_hist_raw[-1] += '%s\n' % line
2172 self.input_hist_raw[-1] += '%s\n' % line
2172 if self.has_readline: # and some config option is set?
2173 if self.has_readline: # and some config option is set?
2173 try:
2174 try:
2174 histlen = self.readline.get_current_history_length()
2175 histlen = self.readline.get_current_history_length()
2175 if histlen > 1:
2176 if histlen > 1:
2176 newhist = self.input_hist_raw[-1].rstrip()
2177 newhist = self.input_hist_raw[-1].rstrip()
2177 self.readline.remove_history_item(histlen-1)
2178 self.readline.remove_history_item(histlen-1)
2178 self.readline.replace_history_item(histlen-2,
2179 self.readline.replace_history_item(histlen-2,
2179 newhist.encode(self.stdin_encoding))
2180 newhist.encode(self.stdin_encoding))
2180 except AttributeError:
2181 except AttributeError:
2181 pass # re{move,place}_history_item are new in 2.4.
2182 pass # re{move,place}_history_item are new in 2.4.
2182 else:
2183 else:
2183 self.input_hist_raw.append('%s\n' % line)
2184 self.input_hist_raw.append('%s\n' % line)
2184 # only entries starting at first column go to shadow history
2185 # only entries starting at first column go to shadow history
2185 if line.lstrip() == line:
2186 if line.lstrip() == line:
2186 self.shadowhist.add(line.strip())
2187 self.shadowhist.add(line.strip())
2187 elif not continue_prompt:
2188 elif not continue_prompt:
2188 self.input_hist_raw.append('\n')
2189 self.input_hist_raw.append('\n')
2189 try:
2190 try:
2190 lineout = self.prefilter(line,continue_prompt)
2191 lineout = self.prefilter(line,continue_prompt)
2191 except:
2192 except:
2192 # blanket except, in case a user-defined prefilter crashes, so it
2193 # blanket except, in case a user-defined prefilter crashes, so it
2193 # can't take all of ipython with it.
2194 # can't take all of ipython with it.
2194 self.showtraceback()
2195 self.showtraceback()
2195 return ''
2196 return ''
2196 else:
2197 else:
2197 return lineout
2198 return lineout
2198
2199
2199 def _prefilter(self, line, continue_prompt):
2200 def _prefilter(self, line, continue_prompt):
2200 """Calls different preprocessors, depending on the form of line."""
2201 """Calls different preprocessors, depending on the form of line."""
2201
2202
2202 # All handlers *must* return a value, even if it's blank ('').
2203 # All handlers *must* return a value, even if it's blank ('').
2203
2204
2204 # Lines are NOT logged here. Handlers should process the line as
2205 # Lines are NOT logged here. Handlers should process the line as
2205 # needed, update the cache AND log it (so that the input cache array
2206 # needed, update the cache AND log it (so that the input cache array
2206 # stays synced).
2207 # stays synced).
2207
2208
2208 #.....................................................................
2209 #.....................................................................
2209 # Code begins
2210 # Code begins
2210
2211
2211 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2212 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2212
2213
2213 # save the line away in case we crash, so the post-mortem handler can
2214 # save the line away in case we crash, so the post-mortem handler can
2214 # record it
2215 # record it
2215 self._last_input_line = line
2216 self._last_input_line = line
2216
2217
2217 #print '***line: <%s>' % line # dbg
2218 #print '***line: <%s>' % line # dbg
2218
2219
2219 if not line:
2220 if not line:
2220 # Return immediately on purely empty lines, so that if the user
2221 # Return immediately on purely empty lines, so that if the user
2221 # previously typed some whitespace that started a continuation
2222 # previously typed some whitespace that started a continuation
2222 # prompt, he can break out of that loop with just an empty line.
2223 # prompt, he can break out of that loop with just an empty line.
2223 # This is how the default python prompt works.
2224 # This is how the default python prompt works.
2224
2225
2225 # Only return if the accumulated input buffer was just whitespace!
2226 # Only return if the accumulated input buffer was just whitespace!
2226 if ''.join(self.buffer).isspace():
2227 if ''.join(self.buffer).isspace():
2227 self.buffer[:] = []
2228 self.buffer[:] = []
2228 return ''
2229 return ''
2229
2230
2230 line_info = prefilter.LineInfo(line, continue_prompt)
2231 line_info = prefilter.LineInfo(line, continue_prompt)
2231
2232
2232 # the input history needs to track even empty lines
2233 # the input history needs to track even empty lines
2233 stripped = line.strip()
2234 stripped = line.strip()
2234
2235
2235 if not stripped:
2236 if not stripped:
2236 if not continue_prompt:
2237 if not continue_prompt:
2237 self.outputcache.prompt_count -= 1
2238 self.outputcache.prompt_count -= 1
2238 return self.handle_normal(line_info)
2239 return self.handle_normal(line_info)
2239
2240
2240 # print '***cont',continue_prompt # dbg
2241 # print '***cont',continue_prompt # dbg
2241 # special handlers are only allowed for single line statements
2242 # special handlers are only allowed for single line statements
2242 if continue_prompt and not self.rc.multi_line_specials:
2243 if continue_prompt and not self.rc.multi_line_specials:
2243 return self.handle_normal(line_info)
2244 return self.handle_normal(line_info)
2244
2245
2245
2246
2246 # See whether any pre-existing handler can take care of it
2247 # See whether any pre-existing handler can take care of it
2247 rewritten = self.hooks.input_prefilter(stripped)
2248 rewritten = self.hooks.input_prefilter(stripped)
2248 if rewritten != stripped: # ok, some prefilter did something
2249 if rewritten != stripped: # ok, some prefilter did something
2249 rewritten = line_info.pre + rewritten # add indentation
2250 rewritten = line_info.pre + rewritten # add indentation
2250 return self.handle_normal(prefilter.LineInfo(rewritten,
2251 return self.handle_normal(prefilter.LineInfo(rewritten,
2251 continue_prompt))
2252 continue_prompt))
2252
2253
2253 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2254 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2254
2255
2255 return prefilter.prefilter(line_info, self)
2256 return prefilter.prefilter(line_info, self)
2256
2257
2257
2258
2258 def _prefilter_dumb(self, line, continue_prompt):
2259 def _prefilter_dumb(self, line, continue_prompt):
2259 """simple prefilter function, for debugging"""
2260 """simple prefilter function, for debugging"""
2260 return self.handle_normal(line,continue_prompt)
2261 return self.handle_normal(line,continue_prompt)
2261
2262
2262
2263
2263 def multiline_prefilter(self, line, continue_prompt):
2264 def multiline_prefilter(self, line, continue_prompt):
2264 """ Run _prefilter for each line of input
2265 """ Run _prefilter for each line of input
2265
2266
2266 Covers cases where there are multiple lines in the user entry,
2267 Covers cases where there are multiple lines in the user entry,
2267 which is the case when the user goes back to a multiline history
2268 which is the case when the user goes back to a multiline history
2268 entry and presses enter.
2269 entry and presses enter.
2269
2270
2270 """
2271 """
2271 out = []
2272 out = []
2272 for l in line.rstrip('\n').split('\n'):
2273 for l in line.rstrip('\n').split('\n'):
2273 out.append(self._prefilter(l, continue_prompt))
2274 out.append(self._prefilter(l, continue_prompt))
2274 return '\n'.join(out)
2275 return '\n'.join(out)
2275
2276
2276 # Set the default prefilter() function (this can be user-overridden)
2277 # Set the default prefilter() function (this can be user-overridden)
2277 prefilter = multiline_prefilter
2278 prefilter = multiline_prefilter
2278
2279
2279 def handle_normal(self,line_info):
2280 def handle_normal(self,line_info):
2280 """Handle normal input lines. Use as a template for handlers."""
2281 """Handle normal input lines. Use as a template for handlers."""
2281
2282
2282 # With autoindent on, we need some way to exit the input loop, and I
2283 # With autoindent on, we need some way to exit the input loop, and I
2283 # don't want to force the user to have to backspace all the way to
2284 # don't want to force the user to have to backspace all the way to
2284 # clear the line. The rule will be in this case, that either two
2285 # clear the line. The rule will be in this case, that either two
2285 # lines of pure whitespace in a row, or a line of pure whitespace but
2286 # lines of pure whitespace in a row, or a line of pure whitespace but
2286 # of a size different to the indent level, will exit the input loop.
2287 # of a size different to the indent level, will exit the input loop.
2287 line = line_info.line
2288 line = line_info.line
2288 continue_prompt = line_info.continue_prompt
2289 continue_prompt = line_info.continue_prompt
2289
2290
2290 if (continue_prompt and self.autoindent and line.isspace() and
2291 if (continue_prompt and self.autoindent and line.isspace() and
2291 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2292 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2292 (self.buffer[-1]).isspace() )):
2293 (self.buffer[-1]).isspace() )):
2293 line = ''
2294 line = ''
2294
2295
2295 self.log(line,line,continue_prompt)
2296 self.log(line,line,continue_prompt)
2296 return line
2297 return line
2297
2298
2298 def handle_alias(self,line_info):
2299 def handle_alias(self,line_info):
2299 """Handle alias input lines. """
2300 """Handle alias input lines. """
2300 tgt = self.alias_table[line_info.iFun]
2301 tgt = self.alias_table[line_info.iFun]
2301 # print "=>",tgt #dbg
2302 # print "=>",tgt #dbg
2302 if callable(tgt):
2303 if callable(tgt):
2303 if '$' in line_info.line:
2304 if '$' in line_info.line:
2304 call_meth = '(_ip, _ip.itpl(%s))'
2305 call_meth = '(_ip, _ip.itpl(%s))'
2305 else:
2306 else:
2306 call_meth = '(_ip,%s)'
2307 call_meth = '(_ip,%s)'
2307 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2308 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2308 line_info.iFun,
2309 line_info.iFun,
2309 make_quoted_expr(line_info.line))
2310 make_quoted_expr(line_info.line))
2310 else:
2311 else:
2311 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2312 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2312
2313
2313 # pre is needed, because it carries the leading whitespace. Otherwise
2314 # pre is needed, because it carries the leading whitespace. Otherwise
2314 # aliases won't work in indented sections.
2315 # aliases won't work in indented sections.
2315 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2316 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2316 make_quoted_expr( transformed ))
2317 make_quoted_expr( transformed ))
2317
2318
2318 self.log(line_info.line,line_out,line_info.continue_prompt)
2319 self.log(line_info.line,line_out,line_info.continue_prompt)
2319 #print 'line out:',line_out # dbg
2320 #print 'line out:',line_out # dbg
2320 return line_out
2321 return line_out
2321
2322
2322 def handle_shell_escape(self, line_info):
2323 def handle_shell_escape(self, line_info):
2323 """Execute the line in a shell, empty return value"""
2324 """Execute the line in a shell, empty return value"""
2324 #print 'line in :', `line` # dbg
2325 #print 'line in :', `line` # dbg
2325 line = line_info.line
2326 line = line_info.line
2326 if line.lstrip().startswith('!!'):
2327 if line.lstrip().startswith('!!'):
2327 # rewrite LineInfo's line, iFun and theRest to properly hold the
2328 # rewrite LineInfo's line, iFun and theRest to properly hold the
2328 # call to %sx and the actual command to be executed, so
2329 # call to %sx and the actual command to be executed, so
2329 # handle_magic can work correctly. Note that this works even if
2330 # handle_magic can work correctly. Note that this works even if
2330 # the line is indented, so it handles multi_line_specials
2331 # the line is indented, so it handles multi_line_specials
2331 # properly.
2332 # properly.
2332 new_rest = line.lstrip()[2:]
2333 new_rest = line.lstrip()[2:]
2333 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2334 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2334 line_info.iFun = 'sx'
2335 line_info.iFun = 'sx'
2335 line_info.theRest = new_rest
2336 line_info.theRest = new_rest
2336 return self.handle_magic(line_info)
2337 return self.handle_magic(line_info)
2337 else:
2338 else:
2338 cmd = line.lstrip().lstrip('!')
2339 cmd = line.lstrip().lstrip('!')
2339 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2340 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2340 make_quoted_expr(cmd))
2341 make_quoted_expr(cmd))
2341 # update cache/log and return
2342 # update cache/log and return
2342 self.log(line,line_out,line_info.continue_prompt)
2343 self.log(line,line_out,line_info.continue_prompt)
2343 return line_out
2344 return line_out
2344
2345
2345 def handle_magic(self, line_info):
2346 def handle_magic(self, line_info):
2346 """Execute magic functions."""
2347 """Execute magic functions."""
2347 iFun = line_info.iFun
2348 iFun = line_info.iFun
2348 theRest = line_info.theRest
2349 theRest = line_info.theRest
2349 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2350 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2350 make_quoted_expr(iFun + " " + theRest))
2351 make_quoted_expr(iFun + " " + theRest))
2351 self.log(line_info.line,cmd,line_info.continue_prompt)
2352 self.log(line_info.line,cmd,line_info.continue_prompt)
2352 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2353 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2353 return cmd
2354 return cmd
2354
2355
2355 def handle_auto(self, line_info):
2356 def handle_auto(self, line_info):
2356 """Hande lines which can be auto-executed, quoting if requested."""
2357 """Hande lines which can be auto-executed, quoting if requested."""
2357
2358
2358 line = line_info.line
2359 line = line_info.line
2359 iFun = line_info.iFun
2360 iFun = line_info.iFun
2360 theRest = line_info.theRest
2361 theRest = line_info.theRest
2361 pre = line_info.pre
2362 pre = line_info.pre
2362 continue_prompt = line_info.continue_prompt
2363 continue_prompt = line_info.continue_prompt
2363 obj = line_info.ofind(self)['obj']
2364 obj = line_info.ofind(self)['obj']
2364
2365
2365 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2366 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2366
2367
2367 # This should only be active for single-line input!
2368 # This should only be active for single-line input!
2368 if continue_prompt:
2369 if continue_prompt:
2369 self.log(line,line,continue_prompt)
2370 self.log(line,line,continue_prompt)
2370 return line
2371 return line
2371
2372
2372 force_auto = isinstance(obj, IPython.ipapi.IPyAutocall)
2373 force_auto = isinstance(obj, IPython.ipapi.IPyAutocall)
2373 auto_rewrite = True
2374 auto_rewrite = True
2374
2375
2375 if pre == self.ESC_QUOTE:
2376 if pre == self.ESC_QUOTE:
2376 # Auto-quote splitting on whitespace
2377 # Auto-quote splitting on whitespace
2377 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2378 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2378 elif pre == self.ESC_QUOTE2:
2379 elif pre == self.ESC_QUOTE2:
2379 # Auto-quote whole string
2380 # Auto-quote whole string
2380 newcmd = '%s("%s")' % (iFun,theRest)
2381 newcmd = '%s("%s")' % (iFun,theRest)
2381 elif pre == self.ESC_PAREN:
2382 elif pre == self.ESC_PAREN:
2382 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2383 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2383 else:
2384 else:
2384 # Auto-paren.
2385 # Auto-paren.
2385 # We only apply it to argument-less calls if the autocall
2386 # We only apply it to argument-less calls if the autocall
2386 # parameter is set to 2. We only need to check that autocall is <
2387 # parameter is set to 2. We only need to check that autocall is <
2387 # 2, since this function isn't called unless it's at least 1.
2388 # 2, since this function isn't called unless it's at least 1.
2388 if not theRest and (self.rc.autocall < 2) and not force_auto:
2389 if not theRest and (self.rc.autocall < 2) and not force_auto:
2389 newcmd = '%s %s' % (iFun,theRest)
2390 newcmd = '%s %s' % (iFun,theRest)
2390 auto_rewrite = False
2391 auto_rewrite = False
2391 else:
2392 else:
2392 if not force_auto and theRest.startswith('['):
2393 if not force_auto and theRest.startswith('['):
2393 if hasattr(obj,'__getitem__'):
2394 if hasattr(obj,'__getitem__'):
2394 # Don't autocall in this case: item access for an object
2395 # Don't autocall in this case: item access for an object
2395 # which is BOTH callable and implements __getitem__.
2396 # which is BOTH callable and implements __getitem__.
2396 newcmd = '%s %s' % (iFun,theRest)
2397 newcmd = '%s %s' % (iFun,theRest)
2397 auto_rewrite = False
2398 auto_rewrite = False
2398 else:
2399 else:
2399 # if the object doesn't support [] access, go ahead and
2400 # if the object doesn't support [] access, go ahead and
2400 # autocall
2401 # autocall
2401 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2402 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2402 elif theRest.endswith(';'):
2403 elif theRest.endswith(';'):
2403 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2404 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2404 else:
2405 else:
2405 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2406 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2406
2407
2407 if auto_rewrite:
2408 if auto_rewrite:
2408 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2409 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2409
2410
2410 try:
2411 try:
2411 # plain ascii works better w/ pyreadline, on some machines, so
2412 # plain ascii works better w/ pyreadline, on some machines, so
2412 # we use it and only print uncolored rewrite if we have unicode
2413 # we use it and only print uncolored rewrite if we have unicode
2413 rw = str(rw)
2414 rw = str(rw)
2414 print >>Term.cout, rw
2415 print >>Term.cout, rw
2415 except UnicodeEncodeError:
2416 except UnicodeEncodeError:
2416 print "-------------->" + newcmd
2417 print "-------------->" + newcmd
2417
2418
2418 # log what is now valid Python, not the actual user input (without the
2419 # log what is now valid Python, not the actual user input (without the
2419 # final newline)
2420 # final newline)
2420 self.log(line,newcmd,continue_prompt)
2421 self.log(line,newcmd,continue_prompt)
2421 return newcmd
2422 return newcmd
2422
2423
2423 def handle_help(self, line_info):
2424 def handle_help(self, line_info):
2424 """Try to get some help for the object.
2425 """Try to get some help for the object.
2425
2426
2426 obj? or ?obj -> basic information.
2427 obj? or ?obj -> basic information.
2427 obj?? or ??obj -> more details.
2428 obj?? or ??obj -> more details.
2428 """
2429 """
2429
2430
2430 line = line_info.line
2431 line = line_info.line
2431 # We need to make sure that we don't process lines which would be
2432 # We need to make sure that we don't process lines which would be
2432 # otherwise valid python, such as "x=1 # what?"
2433 # otherwise valid python, such as "x=1 # what?"
2433 try:
2434 try:
2434 codeop.compile_command(line)
2435 codeop.compile_command(line)
2435 except SyntaxError:
2436 except SyntaxError:
2436 # We should only handle as help stuff which is NOT valid syntax
2437 # We should only handle as help stuff which is NOT valid syntax
2437 if line[0]==self.ESC_HELP:
2438 if line[0]==self.ESC_HELP:
2438 line = line[1:]
2439 line = line[1:]
2439 elif line[-1]==self.ESC_HELP:
2440 elif line[-1]==self.ESC_HELP:
2440 line = line[:-1]
2441 line = line[:-1]
2441 self.log(line,'#?'+line,line_info.continue_prompt)
2442 self.log(line,'#?'+line,line_info.continue_prompt)
2442 if line:
2443 if line:
2443 #print 'line:<%r>' % line # dbg
2444 #print 'line:<%r>' % line # dbg
2444 self.magic_pinfo(line)
2445 self.magic_pinfo(line)
2445 else:
2446 else:
2446 page(self.usage,screen_lines=self.rc.screen_length)
2447 page(self.usage,screen_lines=self.rc.screen_length)
2447 return '' # Empty string is needed here!
2448 return '' # Empty string is needed here!
2448 except:
2449 except:
2449 # Pass any other exceptions through to the normal handler
2450 # Pass any other exceptions through to the normal handler
2450 return self.handle_normal(line_info)
2451 return self.handle_normal(line_info)
2451 else:
2452 else:
2452 # If the code compiles ok, we should handle it normally
2453 # If the code compiles ok, we should handle it normally
2453 return self.handle_normal(line_info)
2454 return self.handle_normal(line_info)
2454
2455
2455 def getapi(self):
2456 def getapi(self):
2456 """ Get an IPApi object for this shell instance
2457 """ Get an IPApi object for this shell instance
2457
2458
2458 Getting an IPApi object is always preferable to accessing the shell
2459 Getting an IPApi object is always preferable to accessing the shell
2459 directly, but this holds true especially for extensions.
2460 directly, but this holds true especially for extensions.
2460
2461
2461 It should always be possible to implement an extension with IPApi
2462 It should always be possible to implement an extension with IPApi
2462 alone. If not, contact maintainer to request an addition.
2463 alone. If not, contact maintainer to request an addition.
2463
2464
2464 """
2465 """
2465 return self.api
2466 return self.api
2466
2467
2467 def handle_emacs(self, line_info):
2468 def handle_emacs(self, line_info):
2468 """Handle input lines marked by python-mode."""
2469 """Handle input lines marked by python-mode."""
2469
2470
2470 # Currently, nothing is done. Later more functionality can be added
2471 # Currently, nothing is done. Later more functionality can be added
2471 # here if needed.
2472 # here if needed.
2472
2473
2473 # The input cache shouldn't be updated
2474 # The input cache shouldn't be updated
2474 return line_info.line
2475 return line_info.line
2475
2476
2476
2477
2477 def mktempfile(self,data=None):
2478 def mktempfile(self,data=None):
2478 """Make a new tempfile and return its filename.
2479 """Make a new tempfile and return its filename.
2479
2480
2480 This makes a call to tempfile.mktemp, but it registers the created
2481 This makes a call to tempfile.mktemp, but it registers the created
2481 filename internally so ipython cleans it up at exit time.
2482 filename internally so ipython cleans it up at exit time.
2482
2483
2483 Optional inputs:
2484 Optional inputs:
2484
2485
2485 - data(None): if data is given, it gets written out to the temp file
2486 - data(None): if data is given, it gets written out to the temp file
2486 immediately, and the file is closed again."""
2487 immediately, and the file is closed again."""
2487
2488
2488 filename = tempfile.mktemp('.py','ipython_edit_')
2489 filename = tempfile.mktemp('.py','ipython_edit_')
2489 self.tempfiles.append(filename)
2490 self.tempfiles.append(filename)
2490
2491
2491 if data:
2492 if data:
2492 tmp_file = open(filename,'w')
2493 tmp_file = open(filename,'w')
2493 tmp_file.write(data)
2494 tmp_file.write(data)
2494 tmp_file.close()
2495 tmp_file.close()
2495 return filename
2496 return filename
2496
2497
2497 def write(self,data):
2498 def write(self,data):
2498 """Write a string to the default output"""
2499 """Write a string to the default output"""
2499 Term.cout.write(data)
2500 Term.cout.write(data)
2500
2501
2501 def write_err(self,data):
2502 def write_err(self,data):
2502 """Write a string to the default error output"""
2503 """Write a string to the default error output"""
2503 Term.cerr.write(data)
2504 Term.cerr.write(data)
2504
2505
2506 def ask_exit(self):
2507 """ Call for exiting. Can be overiden and used as a callback. """
2508 self.exit_now = True
2509
2505 def exit(self):
2510 def exit(self):
2506 """Handle interactive exit.
2511 """Handle interactive exit.
2507
2512
2508 This method sets the exit_now attribute."""
2513 This method calls the ask_exit callback."""
2509
2514
2510 if self.rc.confirm_exit:
2515 if self.rc.confirm_exit:
2511 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2516 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2512 self.exit_now = True
2517 self.ask_exit()
2513 else:
2518 else:
2514 self.exit_now = True
2519 self.ask_exit()
2515
2520
2516 def safe_execfile(self,fname,*where,**kw):
2521 def safe_execfile(self,fname,*where,**kw):
2517 """A safe version of the builtin execfile().
2522 """A safe version of the builtin execfile().
2518
2523
2519 This version will never throw an exception, and knows how to handle
2524 This version will never throw an exception, and knows how to handle
2520 ipython logs as well.
2525 ipython logs as well.
2521
2526
2522 :Parameters:
2527 :Parameters:
2523 fname : string
2528 fname : string
2524 Name of the file to be executed.
2529 Name of the file to be executed.
2525
2530
2526 where : tuple
2531 where : tuple
2527 One or two namespaces, passed to execfile() as (globals,locals).
2532 One or two namespaces, passed to execfile() as (globals,locals).
2528 If only one is given, it is passed as both.
2533 If only one is given, it is passed as both.
2529
2534
2530 :Keywords:
2535 :Keywords:
2531 islog : boolean (False)
2536 islog : boolean (False)
2532
2537
2533 quiet : boolean (True)
2538 quiet : boolean (True)
2534
2539
2535 exit_ignore : boolean (False)
2540 exit_ignore : boolean (False)
2536 """
2541 """
2537
2542
2538 def syspath_cleanup():
2543 def syspath_cleanup():
2539 """Internal cleanup routine for sys.path."""
2544 """Internal cleanup routine for sys.path."""
2540 if add_dname:
2545 if add_dname:
2541 try:
2546 try:
2542 sys.path.remove(dname)
2547 sys.path.remove(dname)
2543 except ValueError:
2548 except ValueError:
2544 # For some reason the user has already removed it, ignore.
2549 # For some reason the user has already removed it, ignore.
2545 pass
2550 pass
2546
2551
2547 fname = os.path.expanduser(fname)
2552 fname = os.path.expanduser(fname)
2548
2553
2549 # Find things also in current directory. This is needed to mimic the
2554 # Find things also in current directory. This is needed to mimic the
2550 # behavior of running a script from the system command line, where
2555 # behavior of running a script from the system command line, where
2551 # Python inserts the script's directory into sys.path
2556 # Python inserts the script's directory into sys.path
2552 dname = os.path.dirname(os.path.abspath(fname))
2557 dname = os.path.dirname(os.path.abspath(fname))
2553 add_dname = False
2558 add_dname = False
2554 if dname not in sys.path:
2559 if dname not in sys.path:
2555 sys.path.insert(0,dname)
2560 sys.path.insert(0,dname)
2556 add_dname = True
2561 add_dname = True
2557
2562
2558 try:
2563 try:
2559 xfile = open(fname)
2564 xfile = open(fname)
2560 except:
2565 except:
2561 print >> Term.cerr, \
2566 print >> Term.cerr, \
2562 'Could not open file <%s> for safe execution.' % fname
2567 'Could not open file <%s> for safe execution.' % fname
2563 syspath_cleanup()
2568 syspath_cleanup()
2564 return None
2569 return None
2565
2570
2566 kw.setdefault('islog',0)
2571 kw.setdefault('islog',0)
2567 kw.setdefault('quiet',1)
2572 kw.setdefault('quiet',1)
2568 kw.setdefault('exit_ignore',0)
2573 kw.setdefault('exit_ignore',0)
2569
2574
2570 first = xfile.readline()
2575 first = xfile.readline()
2571 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2576 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2572 xfile.close()
2577 xfile.close()
2573 # line by line execution
2578 # line by line execution
2574 if first.startswith(loghead) or kw['islog']:
2579 if first.startswith(loghead) or kw['islog']:
2575 print 'Loading log file <%s> one line at a time...' % fname
2580 print 'Loading log file <%s> one line at a time...' % fname
2576 if kw['quiet']:
2581 if kw['quiet']:
2577 stdout_save = sys.stdout
2582 stdout_save = sys.stdout
2578 sys.stdout = StringIO.StringIO()
2583 sys.stdout = StringIO.StringIO()
2579 try:
2584 try:
2580 globs,locs = where[0:2]
2585 globs,locs = where[0:2]
2581 except:
2586 except:
2582 try:
2587 try:
2583 globs = locs = where[0]
2588 globs = locs = where[0]
2584 except:
2589 except:
2585 globs = locs = globals()
2590 globs = locs = globals()
2586 badblocks = []
2591 badblocks = []
2587
2592
2588 # we also need to identify indented blocks of code when replaying
2593 # we also need to identify indented blocks of code when replaying
2589 # logs and put them together before passing them to an exec
2594 # logs and put them together before passing them to an exec
2590 # statement. This takes a bit of regexp and look-ahead work in the
2595 # statement. This takes a bit of regexp and look-ahead work in the
2591 # file. It's easiest if we swallow the whole thing in memory
2596 # file. It's easiest if we swallow the whole thing in memory
2592 # first, and manually walk through the lines list moving the
2597 # first, and manually walk through the lines list moving the
2593 # counter ourselves.
2598 # counter ourselves.
2594 indent_re = re.compile('\s+\S')
2599 indent_re = re.compile('\s+\S')
2595 xfile = open(fname)
2600 xfile = open(fname)
2596 filelines = xfile.readlines()
2601 filelines = xfile.readlines()
2597 xfile.close()
2602 xfile.close()
2598 nlines = len(filelines)
2603 nlines = len(filelines)
2599 lnum = 0
2604 lnum = 0
2600 while lnum < nlines:
2605 while lnum < nlines:
2601 line = filelines[lnum]
2606 line = filelines[lnum]
2602 lnum += 1
2607 lnum += 1
2603 # don't re-insert logger status info into cache
2608 # don't re-insert logger status info into cache
2604 if line.startswith('#log#'):
2609 if line.startswith('#log#'):
2605 continue
2610 continue
2606 else:
2611 else:
2607 # build a block of code (maybe a single line) for execution
2612 # build a block of code (maybe a single line) for execution
2608 block = line
2613 block = line
2609 try:
2614 try:
2610 next = filelines[lnum] # lnum has already incremented
2615 next = filelines[lnum] # lnum has already incremented
2611 except:
2616 except:
2612 next = None
2617 next = None
2613 while next and indent_re.match(next):
2618 while next and indent_re.match(next):
2614 block += next
2619 block += next
2615 lnum += 1
2620 lnum += 1
2616 try:
2621 try:
2617 next = filelines[lnum]
2622 next = filelines[lnum]
2618 except:
2623 except:
2619 next = None
2624 next = None
2620 # now execute the block of one or more lines
2625 # now execute the block of one or more lines
2621 try:
2626 try:
2622 exec block in globs,locs
2627 exec block in globs,locs
2623 except SystemExit:
2628 except SystemExit:
2624 pass
2629 pass
2625 except:
2630 except:
2626 badblocks.append(block.rstrip())
2631 badblocks.append(block.rstrip())
2627 if kw['quiet']: # restore stdout
2632 if kw['quiet']: # restore stdout
2628 sys.stdout.close()
2633 sys.stdout.close()
2629 sys.stdout = stdout_save
2634 sys.stdout = stdout_save
2630 print 'Finished replaying log file <%s>' % fname
2635 print 'Finished replaying log file <%s>' % fname
2631 if badblocks:
2636 if badblocks:
2632 print >> sys.stderr, ('\nThe following lines/blocks in file '
2637 print >> sys.stderr, ('\nThe following lines/blocks in file '
2633 '<%s> reported errors:' % fname)
2638 '<%s> reported errors:' % fname)
2634
2639
2635 for badline in badblocks:
2640 for badline in badblocks:
2636 print >> sys.stderr, badline
2641 print >> sys.stderr, badline
2637 else: # regular file execution
2642 else: # regular file execution
2638 try:
2643 try:
2639 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2644 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2640 # Work around a bug in Python for Windows. The bug was
2645 # Work around a bug in Python for Windows. The bug was
2641 # fixed in in Python 2.5 r54159 and 54158, but that's still
2646 # fixed in in Python 2.5 r54159 and 54158, but that's still
2642 # SVN Python as of March/07. For details, see:
2647 # SVN Python as of March/07. For details, see:
2643 # http://projects.scipy.org/ipython/ipython/ticket/123
2648 # http://projects.scipy.org/ipython/ipython/ticket/123
2644 try:
2649 try:
2645 globs,locs = where[0:2]
2650 globs,locs = where[0:2]
2646 except:
2651 except:
2647 try:
2652 try:
2648 globs = locs = where[0]
2653 globs = locs = where[0]
2649 except:
2654 except:
2650 globs = locs = globals()
2655 globs = locs = globals()
2651 exec file(fname) in globs,locs
2656 exec file(fname) in globs,locs
2652 else:
2657 else:
2653 execfile(fname,*where)
2658 execfile(fname,*where)
2654 except SyntaxError:
2659 except SyntaxError:
2655 self.showsyntaxerror()
2660 self.showsyntaxerror()
2656 warn('Failure executing file: <%s>' % fname)
2661 warn('Failure executing file: <%s>' % fname)
2657 except SystemExit,status:
2662 except SystemExit,status:
2658 # Code that correctly sets the exit status flag to success (0)
2663 # Code that correctly sets the exit status flag to success (0)
2659 # shouldn't be bothered with a traceback. Note that a plain
2664 # shouldn't be bothered with a traceback. Note that a plain
2660 # sys.exit() does NOT set the message to 0 (it's empty) so that
2665 # sys.exit() does NOT set the message to 0 (it's empty) so that
2661 # will still get a traceback. Note that the structure of the
2666 # will still get a traceback. Note that the structure of the
2662 # SystemExit exception changed between Python 2.4 and 2.5, so
2667 # SystemExit exception changed between Python 2.4 and 2.5, so
2663 # the checks must be done in a version-dependent way.
2668 # the checks must be done in a version-dependent way.
2664 show = False
2669 show = False
2665
2670
2666 if sys.version_info[:2] > (2,5):
2671 if sys.version_info[:2] > (2,5):
2667 if status.message!=0 and not kw['exit_ignore']:
2672 if status.message!=0 and not kw['exit_ignore']:
2668 show = True
2673 show = True
2669 else:
2674 else:
2670 if status.code and not kw['exit_ignore']:
2675 if status.code and not kw['exit_ignore']:
2671 show = True
2676 show = True
2672 if show:
2677 if show:
2673 self.showtraceback()
2678 self.showtraceback()
2674 warn('Failure executing file: <%s>' % fname)
2679 warn('Failure executing file: <%s>' % fname)
2675 except:
2680 except:
2676 self.showtraceback()
2681 self.showtraceback()
2677 warn('Failure executing file: <%s>' % fname)
2682 warn('Failure executing file: <%s>' % fname)
2678
2683
2679 syspath_cleanup()
2684 syspath_cleanup()
2680
2685
2681 #************************* end of file <iplib.py> *****************************
2686 #************************* end of file <iplib.py> *****************************
@@ -1,137 +1,137 b''
1 # encoding: utf-8
1 # encoding: utf-8
2
2
3 """ Manage the input and output history of the interpreter and the
3 """ Manage the input and output history of the interpreter and the
4 frontend.
4 frontend.
5
5
6 There are 2 different history objects, one that lives in the interpreter,
6 There are 2 different history objects, one that lives in the interpreter,
7 and one that lives in the frontend. They are synced with a diff at each
7 and one that lives in the frontend. They are synced with a diff at each
8 execution of a command, as the interpreter history is a real stack, its
8 execution of a command, as the interpreter history is a real stack, its
9 existing entries are not mutable.
9 existing entries are not mutable.
10 """
10 """
11
11
12 __docformat__ = "restructuredtext en"
12 __docformat__ = "restructuredtext en"
13
13
14 #-------------------------------------------------------------------------------
14 #-------------------------------------------------------------------------------
15 # Copyright (C) 2008 The IPython Development Team
15 # Copyright (C) 2008 The IPython Development Team
16 #
16 #
17 # Distributed under the terms of the BSD License. The full license is in
17 # Distributed under the terms of the BSD License. The full license is in
18 # the file COPYING, distributed as part of this software.
18 # the file COPYING, distributed as part of this software.
19 #-------------------------------------------------------------------------------
19 #-------------------------------------------------------------------------------
20
20
21 #-------------------------------------------------------------------------------
21 #-------------------------------------------------------------------------------
22 # Imports
22 # Imports
23 #-------------------------------------------------------------------------------
23 #-------------------------------------------------------------------------------
24
24
25 from copy import copy
25 from copy import copy
26
26
27 # Local imports.
27 # Local imports.
28 from util import InputList
28 from util import InputList
29
29
30
30
31 ##############################################################################
31 ##############################################################################
32 class History(object):
32 class History(object):
33 """ An object managing the input and output history.
33 """ An object managing the input and output history.
34 """
34 """
35
35
36 def __init__(self, input_cache=None, output_cache=None):
36 def __init__(self, input_cache=None, output_cache=None):
37
37
38 # Stuff that IPython adds to the namespace.
38 # Stuff that IPython adds to the namespace.
39 self.namespace_additions = dict(
39 self.namespace_additions = dict(
40 _ = None,
40 _ = None,
41 __ = None,
41 __ = None,
42 ___ = None,
42 ___ = None,
43 )
43 )
44
44
45 # A list to store input commands.
45 # A list to store input commands.
46 if input_cache is None:
46 if input_cache is None:
47 input_cache =InputList([])
47 input_cache =InputList([])
48 self.input_cache = input_cache
48 self.input_cache = input_cache
49
49
50 # A dictionary to store trapped output.
50 # A dictionary to store trapped output.
51 if output_cache is None:
51 if output_cache is None:
52 output_cache = {}
52 output_cache = {}
53 self.output_cache = output_cache
53 self.output_cache = output_cache
54
54
55 def get_history_item(self, index):
55 def get_history_item(self, index):
56 """ Returns the history string at index, where index is the
56 """ Returns the history string at index, where index is the
57 distance from the end (positive).
57 distance from the end (positive).
58 """
58 """
59 if index>0 and index<len(self.input_cache):
59 if index>=0 and index<len(self.input_cache):
60 return self.input_cache[index]
60 return self.input_cache[index]
61
61
62
62
63 ##############################################################################
63 ##############################################################################
64 class InterpreterHistory(History):
64 class InterpreterHistory(History):
65 """ An object managing the input and output history at the interpreter
65 """ An object managing the input and output history at the interpreter
66 level.
66 level.
67 """
67 """
68
68
69 def setup_namespace(self, namespace):
69 def setup_namespace(self, namespace):
70 """ Add the input and output caches into the interpreter's namespace
70 """ Add the input and output caches into the interpreter's namespace
71 with IPython-conventional names.
71 with IPython-conventional names.
72
72
73 Parameters
73 Parameters
74 ----------
74 ----------
75 namespace : dict
75 namespace : dict
76 """
76 """
77
77
78 namespace['In'] = self.input_cache
78 namespace['In'] = self.input_cache
79 namespace['_ih'] = self.input_cache
79 namespace['_ih'] = self.input_cache
80 namespace['Out'] = self.output_cache
80 namespace['Out'] = self.output_cache
81 namespace['_oh'] = self.output_cache
81 namespace['_oh'] = self.output_cache
82
82
83 def update_history(self, interpreter, python):
83 def update_history(self, interpreter, python):
84 """ Update the history objects that this object maintains and the
84 """ Update the history objects that this object maintains and the
85 interpreter's namespace.
85 interpreter's namespace.
86
86
87 Parameters
87 Parameters
88 ----------
88 ----------
89 interpreter : Interpreter
89 interpreter : Interpreter
90 python : str
90 python : str
91 The real Python code that was translated and actually executed.
91 The real Python code that was translated and actually executed.
92 """
92 """
93
93
94 number = interpreter.current_cell_number
94 number = interpreter.current_cell_number
95
95
96 new_obj = interpreter.display_trap.obj
96 new_obj = interpreter.display_trap.obj
97 if new_obj is not None:
97 if new_obj is not None:
98 self.namespace_additions['___'] = self.namespace_additions['__']
98 self.namespace_additions['___'] = self.namespace_additions['__']
99 self.namespace_additions['__'] = self.namespace_additions['_']
99 self.namespace_additions['__'] = self.namespace_additions['_']
100 self.namespace_additions['_'] = new_obj
100 self.namespace_additions['_'] = new_obj
101 self.output_cache[number] = new_obj
101 self.output_cache[number] = new_obj
102
102
103 interpreter.user_ns.update(self.namespace_additions)
103 interpreter.user_ns.update(self.namespace_additions)
104 self.input_cache.add(number, python)
104 self.input_cache.add(number, python)
105
105
106
106
107 def get_history_item(self, index):
107 def get_history_item(self, index):
108 """ Returns the history string at index, where index is the
108 """ Returns the history string at index, where index is the
109 distance from the end (positive).
109 distance from the end (positive).
110 """
110 """
111 if index>0 and index<(len(self.input_cache)-1):
111 if index>0 and index<(len(self.input_cache)-1):
112 return self.input_cache[-index]
112 return self.input_cache[-index]
113
113
114 def get_input_cache(self):
114 def get_input_cache(self):
115 return copy(self.input_cache)
115 return copy(self.input_cache)
116
116
117 def get_input_after(self, index):
117 def get_input_after(self, index):
118 """ Returns the list of the commands entered after index.
118 """ Returns the list of the commands entered after index.
119 """
119 """
120 # We need to call directly list.__getslice__, because this object
120 # We need to call directly list.__getslice__, because this object
121 # is not a real list.
121 # is not a real list.
122 return list.__getslice__(self.input_cache, index,
122 return list.__getslice__(self.input_cache, index,
123 len(self.input_cache))
123 len(self.input_cache))
124
124
125
125
126 ##############################################################################
126 ##############################################################################
127 class FrontEndHistory(History):
127 class FrontEndHistory(History):
128 """ An object managing the input and output history at the frontend.
128 """ An object managing the input and output history at the frontend.
129 It is used as a local cache to reduce network latency problems
129 It is used as a local cache to reduce network latency problems
130 and multiple users editing the same thing.
130 and multiple users editing the same thing.
131 """
131 """
132
132
133 def add_items(self, item_list):
133 def add_items(self, item_list):
134 """ Adds the given command list to the stack of executed
134 """ Adds the given command list to the stack of executed
135 commands.
135 commands.
136 """
136 """
137 self.input_cache.extend(item_list)
137 self.input_cache.extend(item_list)
@@ -1,749 +1,747 b''
1 # encoding: utf-8
1 # encoding: utf-8
2
2
3 """Central interpreter object for an IPython engine.
3 """Central interpreter object for an IPython engine.
4
4
5 The interpreter is the object whose job is to process lines of user input and
5 The interpreter is the object whose job is to process lines of user input and
6 actually execute them in the user's namespace.
6 actually execute them in the user's namespace.
7 """
7 """
8
8
9 __docformat__ = "restructuredtext en"
9 __docformat__ = "restructuredtext en"
10
10
11 #-------------------------------------------------------------------------------
11 #-------------------------------------------------------------------------------
12 # Copyright (C) 2008 The IPython Development Team
12 # Copyright (C) 2008 The IPython Development Team
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #-------------------------------------------------------------------------------
16 #-------------------------------------------------------------------------------
17
17
18 #-------------------------------------------------------------------------------
18 #-------------------------------------------------------------------------------
19 # Imports
19 # Imports
20 #-------------------------------------------------------------------------------
20 #-------------------------------------------------------------------------------
21
21
22 # Standard library imports.
22 # Standard library imports.
23 from compiler.ast import Discard
24 from types import FunctionType
23 from types import FunctionType
25
24
26 import __builtin__
25 import __builtin__
27 import codeop
26 import codeop
28 import compiler
27 import compiler
29 import pprint
30 import sys
28 import sys
31 import traceback
29 import traceback
32
30
33 # Local imports.
31 # Local imports.
34 from IPython.kernel.core import ultraTB
32 from IPython.kernel.core import ultraTB
35 from IPython.kernel.core.display_trap import DisplayTrap
33 from IPython.kernel.core.display_trap import DisplayTrap
36 from IPython.kernel.core.macro import Macro
34 from IPython.kernel.core.macro import Macro
37 from IPython.kernel.core.prompts import CachedOutput
35 from IPython.kernel.core.prompts import CachedOutput
38 from IPython.kernel.core.traceback_trap import TracebackTrap
36 from IPython.kernel.core.traceback_trap import TracebackTrap
39 from IPython.kernel.core.util import Bunch, system_shell
37 from IPython.kernel.core.util import Bunch, system_shell
40 from IPython.external.Itpl import ItplNS
38 from IPython.external.Itpl import ItplNS
41
39
42 # Global constants
40 # Global constants
43 COMPILER_ERROR = 'error'
41 COMPILER_ERROR = 'error'
44 INCOMPLETE_INPUT = 'incomplete'
42 INCOMPLETE_INPUT = 'incomplete'
45 COMPLETE_INPUT = 'complete'
43 COMPLETE_INPUT = 'complete'
46
44
47 ##############################################################################
45 ##############################################################################
48 # TEMPORARY!!! fake configuration, while we decide whether to use tconfig or
46 # TEMPORARY!!! fake configuration, while we decide whether to use tconfig or
49 # not
47 # not
50
48
51 rc = Bunch()
49 rc = Bunch()
52 rc.cache_size = 100
50 rc.cache_size = 100
53 rc.pprint = True
51 rc.pprint = True
54 rc.separate_in = '\n'
52 rc.separate_in = '\n'
55 rc.separate_out = '\n'
53 rc.separate_out = '\n'
56 rc.separate_out2 = ''
54 rc.separate_out2 = ''
57 rc.prompt_in1 = r'In [\#]: '
55 rc.prompt_in1 = r'In [\#]: '
58 rc.prompt_in2 = r' .\\D.: '
56 rc.prompt_in2 = r' .\\D.: '
59 rc.prompt_out = ''
57 rc.prompt_out = ''
60 rc.prompts_pad_left = False
58 rc.prompts_pad_left = False
61
59
62 ##############################################################################
60 ##############################################################################
63
61
64 # Top-level utilities
62 # Top-level utilities
65 def default_display_formatters():
63 def default_display_formatters():
66 """ Return a list of default display formatters.
64 """ Return a list of default display formatters.
67 """
65 """
68
66
69 from display_formatter import PPrintDisplayFormatter, ReprDisplayFormatter
67 from display_formatter import PPrintDisplayFormatter, ReprDisplayFormatter
70 return [PPrintDisplayFormatter(), ReprDisplayFormatter()]
68 return [PPrintDisplayFormatter(), ReprDisplayFormatter()]
71
69
72 def default_traceback_formatters():
70 def default_traceback_formatters():
73 """ Return a list of default traceback formatters.
71 """ Return a list of default traceback formatters.
74 """
72 """
75
73
76 from traceback_formatter import PlainTracebackFormatter
74 from traceback_formatter import PlainTracebackFormatter
77 return [PlainTracebackFormatter()]
75 return [PlainTracebackFormatter()]
78
76
79 # Top-level classes
77 # Top-level classes
80 class NotDefined(object): pass
78 class NotDefined(object): pass
81
79
82 class Interpreter(object):
80 class Interpreter(object):
83 """ An interpreter object.
81 """ An interpreter object.
84
82
85 fixme: needs to negotiate available formatters with frontends.
83 fixme: needs to negotiate available formatters with frontends.
86
84
87 Important: the interpeter should be built so that it exposes a method
85 Important: the interpeter should be built so that it exposes a method
88 for each attribute/method of its sub-object. This way it can be
86 for each attribute/method of its sub-object. This way it can be
89 replaced by a network adapter.
87 replaced by a network adapter.
90 """
88 """
91
89
92 def __init__(self, user_ns=None, global_ns=None,translator=None,
90 def __init__(self, user_ns=None, global_ns=None,translator=None,
93 magic=None, display_formatters=None,
91 magic=None, display_formatters=None,
94 traceback_formatters=None, output_trap=None, history=None,
92 traceback_formatters=None, output_trap=None, history=None,
95 message_cache=None, filename='<string>', config=None):
93 message_cache=None, filename='<string>', config=None):
96
94
97 # The local/global namespaces for code execution
95 # The local/global namespaces for code execution
98 local_ns = user_ns # compatibility name
96 local_ns = user_ns # compatibility name
99 if local_ns is None:
97 if local_ns is None:
100 local_ns = {}
98 local_ns = {}
101 self.user_ns = local_ns
99 self.user_ns = local_ns
102 # The local namespace
100 # The local namespace
103 if global_ns is None:
101 if global_ns is None:
104 global_ns = {}
102 global_ns = {}
105 self.user_global_ns = global_ns
103 self.user_global_ns = global_ns
106
104
107 # An object that will translate commands into executable Python.
105 # An object that will translate commands into executable Python.
108 # The current translator does not work properly so for now we are going
106 # The current translator does not work properly so for now we are going
109 # without!
107 # without!
110 # if translator is None:
108 # if translator is None:
111 # from IPython.kernel.core.translator import IPythonTranslator
109 # from IPython.kernel.core.translator import IPythonTranslator
112 # translator = IPythonTranslator()
110 # translator = IPythonTranslator()
113 self.translator = translator
111 self.translator = translator
114
112
115 # An object that maintains magic commands.
113 # An object that maintains magic commands.
116 if magic is None:
114 if magic is None:
117 from IPython.kernel.core.magic import Magic
115 from IPython.kernel.core.magic import Magic
118 magic = Magic(self)
116 magic = Magic(self)
119 self.magic = magic
117 self.magic = magic
120
118
121 # A list of formatters for the displayhook.
119 # A list of formatters for the displayhook.
122 if display_formatters is None:
120 if display_formatters is None:
123 display_formatters = default_display_formatters()
121 display_formatters = default_display_formatters()
124 self.display_formatters = display_formatters
122 self.display_formatters = display_formatters
125
123
126 # A list of formatters for tracebacks.
124 # A list of formatters for tracebacks.
127 if traceback_formatters is None:
125 if traceback_formatters is None:
128 traceback_formatters = default_traceback_formatters()
126 traceback_formatters = default_traceback_formatters()
129 self.traceback_formatters = traceback_formatters
127 self.traceback_formatters = traceback_formatters
130
128
131 # The object trapping stdout/stderr.
129 # The object trapping stdout/stderr.
132 if output_trap is None:
130 if output_trap is None:
133 from IPython.kernel.core.output_trap import OutputTrap
131 from IPython.kernel.core.output_trap import OutputTrap
134 output_trap = OutputTrap()
132 output_trap = OutputTrap()
135 self.output_trap = output_trap
133 self.output_trap = output_trap
136
134
137 # An object that manages the history.
135 # An object that manages the history.
138 if history is None:
136 if history is None:
139 from IPython.kernel.core.history import InterpreterHistory
137 from IPython.kernel.core.history import InterpreterHistory
140 history = InterpreterHistory()
138 history = InterpreterHistory()
141 self.history = history
139 self.history = history
142 self.get_history_item = history.get_history_item
140 self.get_history_item = history.get_history_item
143 self.get_history_input_cache = history.get_input_cache
141 self.get_history_input_cache = history.get_input_cache
144 self.get_history_input_after = history.get_input_after
142 self.get_history_input_after = history.get_input_after
145
143
146 # An object that caches all of the return messages.
144 # An object that caches all of the return messages.
147 if message_cache is None:
145 if message_cache is None:
148 from IPython.kernel.core.message_cache import SimpleMessageCache
146 from IPython.kernel.core.message_cache import SimpleMessageCache
149 message_cache = SimpleMessageCache()
147 message_cache = SimpleMessageCache()
150 self.message_cache = message_cache
148 self.message_cache = message_cache
151
149
152 # The "filename" of the code that is executed in this interpreter.
150 # The "filename" of the code that is executed in this interpreter.
153 self.filename = filename
151 self.filename = filename
154
152
155 # An object that contains much configuration information.
153 # An object that contains much configuration information.
156 if config is None:
154 if config is None:
157 # fixme: Move this constant elsewhere!
155 # fixme: Move this constant elsewhere!
158 config = Bunch(ESC_MAGIC='%')
156 config = Bunch(ESC_MAGIC='%')
159 self.config = config
157 self.config = config
160
158
161 # Hook managers.
159 # Hook managers.
162 # fixme: make the display callbacks configurable. In the meantime,
160 # fixme: make the display callbacks configurable. In the meantime,
163 # enable macros.
161 # enable macros.
164 self.display_trap = DisplayTrap(
162 self.display_trap = DisplayTrap(
165 formatters=self.display_formatters,
163 formatters=self.display_formatters,
166 callbacks=[self._possible_macro],
164 callbacks=[self._possible_macro],
167 )
165 )
168 self.traceback_trap = TracebackTrap(
166 self.traceback_trap = TracebackTrap(
169 formatters=self.traceback_formatters)
167 formatters=self.traceback_formatters)
170
168
171 # This is used temporarily for reformating exceptions in certain
169 # This is used temporarily for reformating exceptions in certain
172 # cases. It will go away once the ultraTB stuff is ported
170 # cases. It will go away once the ultraTB stuff is ported
173 # to ipython1
171 # to ipython1
174 self.tbHandler = ultraTB.FormattedTB(color_scheme='NoColor',
172 self.tbHandler = ultraTB.FormattedTB(color_scheme='NoColor',
175 mode='Context',
173 mode='Context',
176 tb_offset=2)
174 tb_offset=2)
177
175
178 # An object that can compile commands and remember __future__
176 # An object that can compile commands and remember __future__
179 # statements.
177 # statements.
180 self.command_compiler = codeop.CommandCompiler()
178 self.command_compiler = codeop.CommandCompiler()
181
179
182 # A replacement for the raw_input() and input() builtins. Change these
180 # A replacement for the raw_input() and input() builtins. Change these
183 # attributes later to configure them.
181 # attributes later to configure them.
184 self.raw_input_builtin = raw_input
182 self.raw_input_builtin = raw_input
185 self.input_builtin = input
183 self.input_builtin = input
186
184
187 # The number of the current cell.
185 # The number of the current cell.
188 self.current_cell_number = 1
186 self.current_cell_number = 1
189
187
190 # Initialize cache, set in/out prompts and printing system
188 # Initialize cache, set in/out prompts and printing system
191 self.outputcache = CachedOutput(self,
189 self.outputcache = CachedOutput(self,
192 rc.cache_size,
190 rc.cache_size,
193 rc.pprint,
191 rc.pprint,
194 input_sep = rc.separate_in,
192 input_sep = rc.separate_in,
195 output_sep = rc.separate_out,
193 output_sep = rc.separate_out,
196 output_sep2 = rc.separate_out2,
194 output_sep2 = rc.separate_out2,
197 ps1 = rc.prompt_in1,
195 ps1 = rc.prompt_in1,
198 ps2 = rc.prompt_in2,
196 ps2 = rc.prompt_in2,
199 ps_out = rc.prompt_out,
197 ps_out = rc.prompt_out,
200 pad_left = rc.prompts_pad_left)
198 pad_left = rc.prompts_pad_left)
201
199
202 # Need to decide later if this is the right approach, but clients
200 # Need to decide later if this is the right approach, but clients
203 # commonly use sys.ps1/2, so it may be best to just set them here
201 # commonly use sys.ps1/2, so it may be best to just set them here
204 sys.ps1 = self.outputcache.prompt1.p_str
202 sys.ps1 = self.outputcache.prompt1.p_str
205 sys.ps2 = self.outputcache.prompt2.p_str
203 sys.ps2 = self.outputcache.prompt2.p_str
206
204
207 # This is the message dictionary assigned temporarily when running the
205 # This is the message dictionary assigned temporarily when running the
208 # code.
206 # code.
209 self.message = None
207 self.message = None
210
208
211 self.setup_namespace()
209 self.setup_namespace()
212
210
213
211
214 #### Public 'Interpreter' interface ########################################
212 #### Public 'Interpreter' interface ########################################
215
213
216 def formatTraceback(self, et, ev, tb, message=''):
214 def formatTraceback(self, et, ev, tb, message=''):
217 """Put a formatted version of the traceback into value and reraise.
215 """Put a formatted version of the traceback into value and reraise.
218
216
219 When exceptions have to be sent over the network, the traceback
217 When exceptions have to be sent over the network, the traceback
220 needs to be put into the value of the exception in a nicely
218 needs to be put into the value of the exception in a nicely
221 formatted way. The method takes the type, value and tb of an
219 formatted way. The method takes the type, value and tb of an
222 exception and puts a string representation of the tb into the
220 exception and puts a string representation of the tb into the
223 value of the exception and reraises it.
221 value of the exception and reraises it.
224
222
225 Currently this method uses the ultraTb formatter from IPython trunk.
223 Currently this method uses the ultraTb formatter from IPython trunk.
226 Eventually it should simply use the traceback formatters in core
224 Eventually it should simply use the traceback formatters in core
227 that are loaded into self.tracback_trap.formatters.
225 that are loaded into self.tracback_trap.formatters.
228 """
226 """
229 tbinfo = self.tbHandler.text(et,ev,tb)
227 tbinfo = self.tbHandler.text(et,ev,tb)
230 ev._ipython_traceback_text = tbinfo
228 ev._ipython_traceback_text = tbinfo
231 return et, ev, tb
229 return et, ev, tb
232
230
233 def execute(self, commands, raiseException=True):
231 def execute(self, commands, raiseException=True):
234 """ Execute some IPython commands.
232 """ Execute some IPython commands.
235
233
236 1. Translate them into Python.
234 1. Translate them into Python.
237 2. Run them.
235 2. Run them.
238 3. Trap stdout/stderr.
236 3. Trap stdout/stderr.
239 4. Trap sys.displayhook().
237 4. Trap sys.displayhook().
240 5. Trap exceptions.
238 5. Trap exceptions.
241 6. Return a message object.
239 6. Return a message object.
242
240
243 Parameters
241 Parameters
244 ----------
242 ----------
245 commands : str
243 commands : str
246 The raw commands that the user typed into the prompt.
244 The raw commands that the user typed into the prompt.
247
245
248 Returns
246 Returns
249 -------
247 -------
250 message : dict
248 message : dict
251 The dictionary of responses. See the README.txt in this directory
249 The dictionary of responses. See the README.txt in this directory
252 for an explanation of the format.
250 for an explanation of the format.
253 """
251 """
254
252
255 # Create a message dictionary with all of the information we will be
253 # Create a message dictionary with all of the information we will be
256 # returning to the frontend and other listeners.
254 # returning to the frontend and other listeners.
257 message = self.setup_message()
255 message = self.setup_message()
258
256
259 # Massage the input and store the raw and translated commands into
257 # Massage the input and store the raw and translated commands into
260 # a dict.
258 # a dict.
261 user_input = dict(raw=commands)
259 user_input = dict(raw=commands)
262 if self.translator is not None:
260 if self.translator is not None:
263 python = self.translator(commands, message)
261 python = self.translator(commands, message)
264 if python is None:
262 if python is None:
265 # Something went wrong with the translation. The translator
263 # Something went wrong with the translation. The translator
266 # should have added an appropriate entry to the message object.
264 # should have added an appropriate entry to the message object.
267 return message
265 return message
268 else:
266 else:
269 python = commands
267 python = commands
270 user_input['translated'] = python
268 user_input['translated'] = python
271 message['input'] = user_input
269 message['input'] = user_input
272
270
273 # Set the message object so that any magics executed in the code have
271 # Set the message object so that any magics executed in the code have
274 # access.
272 # access.
275 self.message = message
273 self.message = message
276
274
277 # Set all of the output/exception traps.
275 # Set all of the output/exception traps.
278 self.set_traps()
276 self.set_traps()
279
277
280 # Actually execute the Python code.
278 # Actually execute the Python code.
281 status = self.execute_python(python)
279 status = self.execute_python(python)
282
280
283 # Unset all of the traps.
281 # Unset all of the traps.
284 self.unset_traps()
282 self.unset_traps()
285
283
286 # Unset the message object.
284 # Unset the message object.
287 self.message = None
285 self.message = None
288
286
289 # Update the history variables in the namespace.
287 # Update the history variables in the namespace.
290 # E.g. In, Out, _, __, ___
288 # E.g. In, Out, _, __, ___
291 if self.history is not None:
289 if self.history is not None:
292 self.history.update_history(self, python)
290 self.history.update_history(self, python)
293
291
294 # Let all of the traps contribute to the message and then clear their
292 # Let all of the traps contribute to the message and then clear their
295 # stored information.
293 # stored information.
296 self.output_trap.add_to_message(message)
294 self.output_trap.add_to_message(message)
297 self.output_trap.clear()
295 self.output_trap.clear()
298 self.display_trap.add_to_message(message)
296 self.display_trap.add_to_message(message)
299 self.display_trap.clear()
297 self.display_trap.clear()
300 self.traceback_trap.add_to_message(message)
298 self.traceback_trap.add_to_message(message)
301 # Pull out the type, value and tb of the current exception
299 # Pull out the type, value and tb of the current exception
302 # before clearing it.
300 # before clearing it.
303 einfo = self.traceback_trap.args
301 einfo = self.traceback_trap.args
304 self.traceback_trap.clear()
302 self.traceback_trap.clear()
305
303
306 # Cache the message.
304 # Cache the message.
307 self.message_cache.add_message(self.current_cell_number, message)
305 self.message_cache.add_message(self.current_cell_number, message)
308
306
309 # Bump the number.
307 # Bump the number.
310 self.current_cell_number += 1
308 self.current_cell_number += 1
311
309
312 # This conditional lets the execute method either raise any
310 # This conditional lets the execute method either raise any
313 # exception that has occured in user code OR return the message
311 # exception that has occured in user code OR return the message
314 # dict containing the traceback and other useful info.
312 # dict containing the traceback and other useful info.
315 if raiseException and einfo:
313 if raiseException and einfo:
316 raise einfo[0],einfo[1],einfo[2]
314 raise einfo[0],einfo[1],einfo[2]
317 else:
315 else:
318 return message
316 return message
319
317
320 def generate_prompt(self, is_continuation):
318 def generate_prompt(self, is_continuation):
321 """Calculate and return a string with the prompt to display.
319 """Calculate and return a string with the prompt to display.
322
320
323 :Parameters:
321 :Parameters:
324 is_continuation : bool
322 is_continuation : bool
325 Whether the input line is continuing multiline input or not, so
323 Whether the input line is continuing multiline input or not, so
326 that a proper continuation prompt can be computed."""
324 that a proper continuation prompt can be computed."""
327
325
328 if is_continuation:
326 if is_continuation:
329 return str(self.outputcache.prompt2)
327 return str(self.outputcache.prompt2)
330 else:
328 else:
331 return str(self.outputcache.prompt1)
329 return str(self.outputcache.prompt1)
332
330
333 def execute_python(self, python):
331 def execute_python(self, python):
334 """ Actually run the Python code in the namespace.
332 """ Actually run the Python code in the namespace.
335
333
336 :Parameters:
334 :Parameters:
337
335
338 python : str
336 python : str
339 Pure, exec'able Python code. Special IPython commands should have
337 Pure, exec'able Python code. Special IPython commands should have
340 already been translated into pure Python.
338 already been translated into pure Python.
341 """
339 """
342
340
343 # We use a CommandCompiler instance to compile the code so as to keep
341 # We use a CommandCompiler instance to compile the code so as to keep
344 # track of __future__ imports.
342 # track of __future__ imports.
345 try:
343 try:
346 commands = self.split_commands(python)
344 commands = self.split_commands(python)
347 except (SyntaxError, IndentationError), e:
345 except (SyntaxError, IndentationError), e:
348 # Save the exc_info so compilation related exceptions can be
346 # Save the exc_info so compilation related exceptions can be
349 # reraised
347 # reraised
350 self.traceback_trap.args = sys.exc_info()
348 self.traceback_trap.args = sys.exc_info()
351 self.pack_exception(self.message,e)
349 self.pack_exception(self.message,e)
352 return None
350 return None
353
351
354 for cmd in commands:
352 for cmd in commands:
355 try:
353 try:
356 code = self.command_compiler(cmd, self.filename, 'single')
354 code = self.command_compiler(cmd, self.filename, 'single')
357 except (SyntaxError, OverflowError, ValueError), e:
355 except (SyntaxError, OverflowError, ValueError), e:
358 self.traceback_trap.args = sys.exc_info()
356 self.traceback_trap.args = sys.exc_info()
359 self.pack_exception(self.message,e)
357 self.pack_exception(self.message,e)
360 # No point in continuing if one block raised
358 # No point in continuing if one block raised
361 return None
359 return None
362 else:
360 else:
363 self.execute_block(code)
361 self.execute_block(code)
364
362
365 def execute_block(self,code):
363 def execute_block(self,code):
366 """Execute a single block of code in the user namespace.
364 """Execute a single block of code in the user namespace.
367
365
368 Return value: a flag indicating whether the code to be run completed
366 Return value: a flag indicating whether the code to be run completed
369 successfully:
367 successfully:
370
368
371 - 0: successful execution.
369 - 0: successful execution.
372 - 1: an error occurred.
370 - 1: an error occurred.
373 """
371 """
374
372
375 outflag = 1 # start by assuming error, success will reset it
373 outflag = 1 # start by assuming error, success will reset it
376 try:
374 try:
377 exec code in self.user_ns
375 exec code in self.user_ns
378 outflag = 0
376 outflag = 0
379 except SystemExit:
377 except SystemExit:
380 self.resetbuffer()
378 self.resetbuffer()
381 self.traceback_trap.args = sys.exc_info()
379 self.traceback_trap.args = sys.exc_info()
382 except:
380 except:
383 self.traceback_trap.args = sys.exc_info()
381 self.traceback_trap.args = sys.exc_info()
384
382
385 return outflag
383 return outflag
386
384
387 def execute_macro(self, macro):
385 def execute_macro(self, macro):
388 """ Execute the value of a macro.
386 """ Execute the value of a macro.
389
387
390 Parameters
388 Parameters
391 ----------
389 ----------
392 macro : Macro
390 macro : Macro
393 """
391 """
394
392
395 python = macro.value
393 python = macro.value
396 if self.translator is not None:
394 if self.translator is not None:
397 python = self.translator(python)
395 python = self.translator(python)
398 self.execute_python(python)
396 self.execute_python(python)
399
397
400 def getCommand(self, i=None):
398 def getCommand(self, i=None):
401 """Gets the ith message in the message_cache.
399 """Gets the ith message in the message_cache.
402
400
403 This is implemented here for compatibility with the old ipython1 shell
401 This is implemented here for compatibility with the old ipython1 shell
404 I am not sure we need this though. I even seem to remember that we
402 I am not sure we need this though. I even seem to remember that we
405 were going to get rid of it.
403 were going to get rid of it.
406 """
404 """
407 return self.message_cache.get_message(i)
405 return self.message_cache.get_message(i)
408
406
409 def reset(self):
407 def reset(self):
410 """Reset the interpreter.
408 """Reset the interpreter.
411
409
412 Currently this only resets the users variables in the namespace.
410 Currently this only resets the users variables in the namespace.
413 In the future we might want to also reset the other stateful
411 In the future we might want to also reset the other stateful
414 things like that the Interpreter has, like In, Out, etc.
412 things like that the Interpreter has, like In, Out, etc.
415 """
413 """
416 self.user_ns.clear()
414 self.user_ns.clear()
417 self.setup_namespace()
415 self.setup_namespace()
418
416
419 def complete(self,line,text=None, pos=None):
417 def complete(self,line,text=None, pos=None):
420 """Complete the given text.
418 """Complete the given text.
421
419
422 :Parameters:
420 :Parameters:
423
421
424 text : str
422 text : str
425 Text fragment to be completed on. Typically this is
423 Text fragment to be completed on. Typically this is
426 """
424 """
427 # fixme: implement
425 # fixme: implement
428 raise NotImplementedError
426 raise NotImplementedError
429
427
430 def push(self, ns):
428 def push(self, ns):
431 """ Put value into the namespace with name key.
429 """ Put value into the namespace with name key.
432
430
433 Parameters
431 Parameters
434 ----------
432 ----------
435 **kwds
433 **kwds
436 """
434 """
437
435
438 self.user_ns.update(ns)
436 self.user_ns.update(ns)
439
437
440 def push_function(self, ns):
438 def push_function(self, ns):
441 # First set the func_globals for all functions to self.user_ns
439 # First set the func_globals for all functions to self.user_ns
442 new_kwds = {}
440 new_kwds = {}
443 for k, v in ns.iteritems():
441 for k, v in ns.iteritems():
444 if not isinstance(v, FunctionType):
442 if not isinstance(v, FunctionType):
445 raise TypeError("function object expected")
443 raise TypeError("function object expected")
446 new_kwds[k] = FunctionType(v.func_code, self.user_ns)
444 new_kwds[k] = FunctionType(v.func_code, self.user_ns)
447 self.user_ns.update(new_kwds)
445 self.user_ns.update(new_kwds)
448
446
449 def pack_exception(self,message,exc):
447 def pack_exception(self,message,exc):
450 message['exception'] = exc.__class__
448 message['exception'] = exc.__class__
451 message['exception_value'] = \
449 message['exception_value'] = \
452 traceback.format_exception_only(exc.__class__, exc)
450 traceback.format_exception_only(exc.__class__, exc)
453
451
454 def feed_block(self, source, filename='<input>', symbol='single'):
452 def feed_block(self, source, filename='<input>', symbol='single'):
455 """Compile some source in the interpreter.
453 """Compile some source in the interpreter.
456
454
457 One several things can happen:
455 One several things can happen:
458
456
459 1) The input is incorrect; compile_command() raised an
457 1) The input is incorrect; compile_command() raised an
460 exception (SyntaxError or OverflowError).
458 exception (SyntaxError or OverflowError).
461
459
462 2) The input is incomplete, and more input is required;
460 2) The input is incomplete, and more input is required;
463 compile_command() returned None. Nothing happens.
461 compile_command() returned None. Nothing happens.
464
462
465 3) The input is complete; compile_command() returned a code
463 3) The input is complete; compile_command() returned a code
466 object. The code is executed by calling self.runcode() (which
464 object. The code is executed by calling self.runcode() (which
467 also handles run-time exceptions, except for SystemExit).
465 also handles run-time exceptions, except for SystemExit).
468
466
469 The return value is:
467 The return value is:
470
468
471 - True in case 2
469 - True in case 2
472
470
473 - False in the other cases, unless an exception is raised, where
471 - False in the other cases, unless an exception is raised, where
474 None is returned instead. This can be used by external callers to
472 None is returned instead. This can be used by external callers to
475 know whether to continue feeding input or not.
473 know whether to continue feeding input or not.
476
474
477 The return value can be used to decide whether to use sys.ps1 or
475 The return value can be used to decide whether to use sys.ps1 or
478 sys.ps2 to prompt the next line."""
476 sys.ps2 to prompt the next line."""
479
477
480 self.message = self.setup_message()
478 self.message = self.setup_message()
481
479
482 try:
480 try:
483 code = self.command_compiler(source,filename,symbol)
481 code = self.command_compiler(source,filename,symbol)
484 except (OverflowError, SyntaxError, IndentationError, ValueError ), e:
482 except (OverflowError, SyntaxError, IndentationError, ValueError ), e:
485 # Case 1
483 # Case 1
486 self.traceback_trap.args = sys.exc_info()
484 self.traceback_trap.args = sys.exc_info()
487 self.pack_exception(self.message,e)
485 self.pack_exception(self.message,e)
488 return COMPILER_ERROR,False
486 return COMPILER_ERROR,False
489
487
490 if code is None:
488 if code is None:
491 # Case 2: incomplete input. This means that the input can span
489 # Case 2: incomplete input. This means that the input can span
492 # multiple lines. But we still need to decide when to actually
490 # multiple lines. But we still need to decide when to actually
493 # stop taking user input. Later we'll add auto-indentation support
491 # stop taking user input. Later we'll add auto-indentation support
494 # somehow. In the meantime, we'll just stop if there are two lines
492 # somehow. In the meantime, we'll just stop if there are two lines
495 # of pure whitespace at the end.
493 # of pure whitespace at the end.
496 last_two = source.rsplit('\n',2)[-2:]
494 last_two = source.rsplit('\n',2)[-2:]
497 print 'last two:',last_two # dbg
495 print 'last two:',last_two # dbg
498 if len(last_two)==2 and all(s.isspace() for s in last_two):
496 if len(last_two)==2 and all(s.isspace() for s in last_two):
499 return COMPLETE_INPUT,False
497 return COMPLETE_INPUT,False
500 else:
498 else:
501 return INCOMPLETE_INPUT, True
499 return INCOMPLETE_INPUT, True
502 else:
500 else:
503 # Case 3
501 # Case 3
504 return COMPLETE_INPUT, False
502 return COMPLETE_INPUT, False
505
503
506 def pull(self, keys):
504 def pull(self, keys):
507 """ Get an item out of the namespace by key.
505 """ Get an item out of the namespace by key.
508
506
509 Parameters
507 Parameters
510 ----------
508 ----------
511 key : str
509 key : str
512
510
513 Returns
511 Returns
514 -------
512 -------
515 value : object
513 value : object
516
514
517 Raises
515 Raises
518 ------
516 ------
519 TypeError if the key is not a string.
517 TypeError if the key is not a string.
520 NameError if the object doesn't exist.
518 NameError if the object doesn't exist.
521 """
519 """
522
520
523 if isinstance(keys, str):
521 if isinstance(keys, str):
524 result = self.user_ns.get(keys, NotDefined())
522 result = self.user_ns.get(keys, NotDefined())
525 if isinstance(result, NotDefined):
523 if isinstance(result, NotDefined):
526 raise NameError('name %s is not defined' % keys)
524 raise NameError('name %s is not defined' % keys)
527 elif isinstance(keys, (list, tuple)):
525 elif isinstance(keys, (list, tuple)):
528 result = []
526 result = []
529 for key in keys:
527 for key in keys:
530 if not isinstance(key, str):
528 if not isinstance(key, str):
531 raise TypeError("objects must be keyed by strings.")
529 raise TypeError("objects must be keyed by strings.")
532 else:
530 else:
533 r = self.user_ns.get(key, NotDefined())
531 r = self.user_ns.get(key, NotDefined())
534 if isinstance(r, NotDefined):
532 if isinstance(r, NotDefined):
535 raise NameError('name %s is not defined' % key)
533 raise NameError('name %s is not defined' % key)
536 else:
534 else:
537 result.append(r)
535 result.append(r)
538 if len(keys)==1:
536 if len(keys)==1:
539 result = result[0]
537 result = result[0]
540 else:
538 else:
541 raise TypeError("keys must be a strong or a list/tuple of strings")
539 raise TypeError("keys must be a strong or a list/tuple of strings")
542 return result
540 return result
543
541
544 def pull_function(self, keys):
542 def pull_function(self, keys):
545 return self.pull(keys)
543 return self.pull(keys)
546
544
547 #### Interactive user API ##################################################
545 #### Interactive user API ##################################################
548
546
549 def ipsystem(self, command):
547 def ipsystem(self, command):
550 """ Execute a command in a system shell while expanding variables in the
548 """ Execute a command in a system shell while expanding variables in the
551 current namespace.
549 current namespace.
552
550
553 Parameters
551 Parameters
554 ----------
552 ----------
555 command : str
553 command : str
556 """
554 """
557
555
558 # Expand $variables.
556 # Expand $variables.
559 command = self.var_expand(command)
557 command = self.var_expand(command)
560
558
561 system_shell(command,
559 system_shell(command,
562 header='IPython system call: ',
560 header='IPython system call: ',
563 verbose=self.rc.system_verbose,
561 verbose=self.rc.system_verbose,
564 )
562 )
565
563
566 def ipmagic(self, arg_string):
564 def ipmagic(self, arg_string):
567 """ Call a magic function by name.
565 """ Call a magic function by name.
568
566
569 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
567 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
570 prompt:
568 prompt:
571
569
572 In[1]: %name -opt foo bar
570 In[1]: %name -opt foo bar
573
571
574 To call a magic without arguments, simply use ipmagic('name').
572 To call a magic without arguments, simply use ipmagic('name').
575
573
576 This provides a proper Python function to call IPython's magics in any
574 This provides a proper Python function to call IPython's magics in any
577 valid Python code you can type at the interpreter, including loops and
575 valid Python code you can type at the interpreter, including loops and
578 compound statements. It is added by IPython to the Python builtin
576 compound statements. It is added by IPython to the Python builtin
579 namespace upon initialization.
577 namespace upon initialization.
580
578
581 Parameters
579 Parameters
582 ----------
580 ----------
583 arg_string : str
581 arg_string : str
584 A string containing the name of the magic function to call and any
582 A string containing the name of the magic function to call and any
585 additional arguments to be passed to the magic.
583 additional arguments to be passed to the magic.
586
584
587 Returns
585 Returns
588 -------
586 -------
589 something : object
587 something : object
590 The return value of the actual object.
588 The return value of the actual object.
591 """
589 """
592
590
593 # Taken from IPython.
591 # Taken from IPython.
594 raise NotImplementedError('Not ported yet')
592 raise NotImplementedError('Not ported yet')
595
593
596 args = arg_string.split(' ', 1)
594 args = arg_string.split(' ', 1)
597 magic_name = args[0]
595 magic_name = args[0]
598 magic_name = magic_name.lstrip(self.config.ESC_MAGIC)
596 magic_name = magic_name.lstrip(self.config.ESC_MAGIC)
599
597
600 try:
598 try:
601 magic_args = args[1]
599 magic_args = args[1]
602 except IndexError:
600 except IndexError:
603 magic_args = ''
601 magic_args = ''
604 fn = getattr(self.magic, 'magic_'+magic_name, None)
602 fn = getattr(self.magic, 'magic_'+magic_name, None)
605 if fn is None:
603 if fn is None:
606 self.error("Magic function `%s` not found." % magic_name)
604 self.error("Magic function `%s` not found." % magic_name)
607 else:
605 else:
608 magic_args = self.var_expand(magic_args)
606 magic_args = self.var_expand(magic_args)
609 return fn(magic_args)
607 return fn(magic_args)
610
608
611
609
612 #### Private 'Interpreter' interface #######################################
610 #### Private 'Interpreter' interface #######################################
613
611
614 def setup_message(self):
612 def setup_message(self):
615 """Return a message object.
613 """Return a message object.
616
614
617 This method prepares and returns a message dictionary. This dict
615 This method prepares and returns a message dictionary. This dict
618 contains the various fields that are used to transfer information about
616 contains the various fields that are used to transfer information about
619 execution, results, tracebacks, etc, to clients (either in or out of
617 execution, results, tracebacks, etc, to clients (either in or out of
620 process ones). Because of the need to work with possibly out of
618 process ones). Because of the need to work with possibly out of
621 process clients, this dict MUST contain strictly pickle-safe values.
619 process clients, this dict MUST contain strictly pickle-safe values.
622 """
620 """
623
621
624 return dict(number=self.current_cell_number)
622 return dict(number=self.current_cell_number)
625
623
626 def setup_namespace(self):
624 def setup_namespace(self):
627 """ Add things to the namespace.
625 """ Add things to the namespace.
628 """
626 """
629
627
630 self.user_ns.setdefault('__name__', '__main__')
628 self.user_ns.setdefault('__name__', '__main__')
631 self.user_ns.setdefault('__builtins__', __builtin__)
629 self.user_ns.setdefault('__builtins__', __builtin__)
632 self.user_ns['__IP'] = self
630 self.user_ns['__IP'] = self
633 if self.raw_input_builtin is not None:
631 if self.raw_input_builtin is not None:
634 self.user_ns['raw_input'] = self.raw_input_builtin
632 self.user_ns['raw_input'] = self.raw_input_builtin
635 if self.input_builtin is not None:
633 if self.input_builtin is not None:
636 self.user_ns['input'] = self.input_builtin
634 self.user_ns['input'] = self.input_builtin
637
635
638 builtin_additions = dict(
636 builtin_additions = dict(
639 ipmagic=self.ipmagic,
637 ipmagic=self.ipmagic,
640 )
638 )
641 __builtin__.__dict__.update(builtin_additions)
639 __builtin__.__dict__.update(builtin_additions)
642
640
643 if self.history is not None:
641 if self.history is not None:
644 self.history.setup_namespace(self.user_ns)
642 self.history.setup_namespace(self.user_ns)
645
643
646 def set_traps(self):
644 def set_traps(self):
647 """ Set all of the output, display, and traceback traps.
645 """ Set all of the output, display, and traceback traps.
648 """
646 """
649
647
650 self.output_trap.set()
648 self.output_trap.set()
651 self.display_trap.set()
649 self.display_trap.set()
652 self.traceback_trap.set()
650 self.traceback_trap.set()
653
651
654 def unset_traps(self):
652 def unset_traps(self):
655 """ Unset all of the output, display, and traceback traps.
653 """ Unset all of the output, display, and traceback traps.
656 """
654 """
657
655
658 self.output_trap.unset()
656 self.output_trap.unset()
659 self.display_trap.unset()
657 self.display_trap.unset()
660 self.traceback_trap.unset()
658 self.traceback_trap.unset()
661
659
662 def split_commands(self, python):
660 def split_commands(self, python):
663 """ Split multiple lines of code into discrete commands that can be
661 """ Split multiple lines of code into discrete commands that can be
664 executed singly.
662 executed singly.
665
663
666 Parameters
664 Parameters
667 ----------
665 ----------
668 python : str
666 python : str
669 Pure, exec'able Python code.
667 Pure, exec'able Python code.
670
668
671 Returns
669 Returns
672 -------
670 -------
673 commands : list of str
671 commands : list of str
674 Separate commands that can be exec'ed independently.
672 Separate commands that can be exec'ed independently.
675 """
673 """
676
674
677 # compiler.parse treats trailing spaces after a newline as a
675 # compiler.parse treats trailing spaces after a newline as a
678 # SyntaxError. This is different than codeop.CommandCompiler, which
676 # SyntaxError. This is different than codeop.CommandCompiler, which
679 # will compile the trailng spaces just fine. We simply strip any
677 # will compile the trailng spaces just fine. We simply strip any
680 # trailing whitespace off. Passing a string with trailing whitespace
678 # trailing whitespace off. Passing a string with trailing whitespace
681 # to exec will fail however. There seems to be some inconsistency in
679 # to exec will fail however. There seems to be some inconsistency in
682 # how trailing whitespace is handled, but this seems to work.
680 # how trailing whitespace is handled, but this seems to work.
683 python = python.strip()
681 python = python.strip()
684
682
685 # The compiler module will parse the code into an abstract syntax tree.
683 # The compiler module will parse the code into an abstract syntax tree.
686 ast = compiler.parse(python)
684 ast = compiler.parse(python)
687
685
688 # Uncomment to help debug the ast tree
686 # Uncomment to help debug the ast tree
689 # for n in ast.node:
687 # for n in ast.node:
690 # print n.lineno,'->',n
688 # print n.lineno,'->',n
691
689
692 # Each separate command is available by iterating over ast.node. The
690 # Each separate command is available by iterating over ast.node. The
693 # lineno attribute is the line number (1-indexed) beginning the commands
691 # lineno attribute is the line number (1-indexed) beginning the commands
694 # suite.
692 # suite.
695 # lines ending with ";" yield a Discard Node that doesn't have a lineno
693 # lines ending with ";" yield a Discard Node that doesn't have a lineno
696 # attribute. These nodes can and should be discarded. But there are
694 # attribute. These nodes can and should be discarded. But there are
697 # other situations that cause Discard nodes that shouldn't be discarded.
695 # other situations that cause Discard nodes that shouldn't be discarded.
698 # We might eventually discover other cases where lineno is None and have
696 # We might eventually discover other cases where lineno is None and have
699 # to put in a more sophisticated test.
697 # to put in a more sophisticated test.
700 linenos = [x.lineno-1 for x in ast.node if x.lineno is not None]
698 linenos = [x.lineno-1 for x in ast.node if x.lineno is not None]
701
699
702 # When we finally get the slices, we will need to slice all the way to
700 # When we finally get the slices, we will need to slice all the way to
703 # the end even though we don't have a line number for it. Fortunately,
701 # the end even though we don't have a line number for it. Fortunately,
704 # None does the job nicely.
702 # None does the job nicely.
705 linenos.append(None)
703 linenos.append(None)
706 lines = python.splitlines()
704 lines = python.splitlines()
707
705
708 # Create a list of atomic commands.
706 # Create a list of atomic commands.
709 cmds = []
707 cmds = []
710 for i, j in zip(linenos[:-1], linenos[1:]):
708 for i, j in zip(linenos[:-1], linenos[1:]):
711 cmd = lines[i:j]
709 cmd = lines[i:j]
712 if cmd:
710 if cmd:
713 cmds.append('\n'.join(cmd)+'\n')
711 cmds.append('\n'.join(cmd)+'\n')
714
712
715 return cmds
713 return cmds
716
714
717 def error(self, text):
715 def error(self, text):
718 """ Pass an error message back to the shell.
716 """ Pass an error message back to the shell.
719
717
720 Preconditions
718 Preconditions
721 -------------
719 -------------
722 This should only be called when self.message is set. In other words,
720 This should only be called when self.message is set. In other words,
723 when code is being executed.
721 when code is being executed.
724
722
725 Parameters
723 Parameters
726 ----------
724 ----------
727 text : str
725 text : str
728 """
726 """
729
727
730 errors = self.message.get('IPYTHON_ERROR', [])
728 errors = self.message.get('IPYTHON_ERROR', [])
731 errors.append(text)
729 errors.append(text)
732
730
733 def var_expand(self, template):
731 def var_expand(self, template):
734 """ Expand $variables in the current namespace using Itpl.
732 """ Expand $variables in the current namespace using Itpl.
735
733
736 Parameters
734 Parameters
737 ----------
735 ----------
738 template : str
736 template : str
739 """
737 """
740
738
741 return str(ItplNS(template, self.user_ns))
739 return str(ItplNS(template, self.user_ns))
742
740
743 def _possible_macro(self, obj):
741 def _possible_macro(self, obj):
744 """ If the object is a macro, execute it.
742 """ If the object is a macro, execute it.
745 """
743 """
746
744
747 if isinstance(obj, Macro):
745 if isinstance(obj, Macro):
748 self.execute_macro(obj)
746 self.execute_macro(obj)
749
747
@@ -1,99 +1,107 b''
1 # encoding: utf-8
1 # encoding: utf-8
2
2
3 """ Trap stdout/stderr."""
3 """ Trap stdout/stderr."""
4
4
5 __docformat__ = "restructuredtext en"
5 __docformat__ = "restructuredtext en"
6
6
7 #-------------------------------------------------------------------------------
7 #-------------------------------------------------------------------------------
8 # Copyright (C) 2008 The IPython Development Team
8 # Copyright (C) 2008 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 sys
18 import sys
19 from cStringIO import StringIO
19 from cStringIO import StringIO
20
20
21
21
22 class OutputTrap(object):
22 class OutputTrap(object):
23 """ Object which can trap text sent to stdout and stderr.
23 """ Object which can trap text sent to stdout and stderr.
24 """
24 """
25
25
26 def __init__(self):
26 def __init__(self, out=None, err=None):
27 # Filelike objects to store stdout/stderr text.
27 # Filelike objects to store stdout/stderr text.
28 self.out = StringIO()
28 if out is None:
29 self.err = StringIO()
29 self.out = StringIO()
30 else:
31 self.out = out
32 if err is None:
33 self.err = StringIO()
34 else:
35 self.err = err
30
36
31 # Boolean to check if the stdout/stderr hook is set.
37 # Boolean to check if the stdout/stderr hook is set.
32 self.out_set = False
38 self.out_set = False
33 self.err_set = False
39 self.err_set = False
34
40
35 @property
41 @property
36 def out_text(self):
42 def out_text(self):
37 """ Return the text currently in the stdout buffer.
43 """ Return the text currently in the stdout buffer.
38 """
44 """
39 return self.out.getvalue()
45 return self.out.getvalue()
40
46
41 @property
47 @property
42 def err_text(self):
48 def err_text(self):
43 """ Return the text currently in the stderr buffer.
49 """ Return the text currently in the stderr buffer.
44 """
50 """
45 return self.err.getvalue()
51 return self.err.getvalue()
46
52
47 def set(self):
53 def set(self):
48 """ Set the hooks.
54 """ Set the hooks.
49 """
55 """
50
56
51 if sys.stdout is not self.out:
57 if sys.stdout is not self.out:
52 self._out_save = sys.stdout
58 self._out_save = sys.stdout
53 sys.stdout = self.out
59 sys.stdout = self.out
54 self.out_set = True
60 self.out_set = True
55
61
56 if sys.stderr is not self.err:
62 if sys.stderr is not self.err:
57 self._err_save = sys.stderr
63 self._err_save = sys.stderr
58 sys.stderr = self.err
64 sys.stderr = self.err
59 self.err_set = True
65 self.err_set = True
60
66
61 def unset(self):
67 def unset(self):
62 """ Remove the hooks.
68 """ Remove the hooks.
63 """
69 """
64
70
65 sys.stdout = self._out_save
71 if self.out_set:
72 sys.stdout = self._out_save
66 self.out_set = False
73 self.out_set = False
67
74
68 sys.stderr = self._err_save
75 if self.err_set:
76 sys.stderr = self._err_save
69 self.err_set = False
77 self.err_set = False
70
78
71 def clear(self):
79 def clear(self):
72 """ Clear out the buffers.
80 """ Clear out the buffers.
73 """
81 """
74
82
75 self.out.close()
83 self.out.reset()
76 self.out = StringIO()
84 self.out.truncate()
77
85
78 self.err.close()
86 self.err.reset()
79 self.err = StringIO()
87 self.err.truncate()
80
88
81 def add_to_message(self, message):
89 def add_to_message(self, message):
82 """ Add the text from stdout and stderr to the message from the
90 """ Add the text from stdout and stderr to the message from the
83 interpreter to its listeners.
91 interpreter to its listeners.
84
92
85 Parameters
93 Parameters
86 ----------
94 ----------
87 message : dict
95 message : dict
88 """
96 """
89
97
90 out_text = self.out_text
98 out_text = self.out_text
91 if out_text:
99 if out_text:
92 message['stdout'] = out_text
100 message['stdout'] = out_text
93
101
94 err_text = self.err_text
102 err_text = self.err_text
95 if err_text:
103 if err_text:
96 message['stderr'] = err_text
104 message['stderr'] = err_text
97
105
98
106
99
107
@@ -1,83 +1,85 b''
1 # encoding: utf-8
1 # encoding: utf-8
2
2
3 """Object to manage sys.excepthook()."""
3 """Object to manage sys.excepthook()."""
4
4
5 __docformat__ = "restructuredtext en"
5 __docformat__ = "restructuredtext en"
6
6
7 #-------------------------------------------------------------------------------
7 #-------------------------------------------------------------------------------
8 # Copyright (C) 2008 The IPython Development Team
8 # Copyright (C) 2008 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
18 import sys
17 import sys
19
18 from traceback import format_list
20
19
21 class TracebackTrap(object):
20 class TracebackTrap(object):
22 """ Object to trap and format tracebacks.
21 """ Object to trap and format tracebacks.
23 """
22 """
24
23
25 def __init__(self, formatters=None):
24 def __init__(self, formatters=None):
26 # A list of formatters to apply.
25 # A list of formatters to apply.
27 if formatters is None:
26 if formatters is None:
28 formatters = []
27 formatters = []
29 self.formatters = formatters
28 self.formatters = formatters
30
29
31 # All of the traceback information provided to sys.excepthook().
30 # All of the traceback information provided to sys.excepthook().
32 self.args = None
31 self.args = None
33
32
34 # The previous hook before we replace it.
33 # The previous hook before we replace it.
35 self.old_hook = None
34 self.old_hook = None
36
35
37
36
38 def hook(self, *args):
37 def hook(self, *args):
39 """ This method actually implements the hook.
38 """ This method actually implements the hook.
40 """
39 """
41
42 self.args = args
40 self.args = args
43
41
44 def set(self):
42 def set(self):
45 """ Set the hook.
43 """ Set the hook.
46 """
44 """
47
45
48 if sys.excepthook is not self.hook:
46 if sys.excepthook is not self.hook:
49 self.old_hook = sys.excepthook
47 self.old_hook = sys.excepthook
50 sys.excepthook = self.hook
48 sys.excepthook = self.hook
51
49
52 def unset(self):
50 def unset(self):
53 """ Unset the hook.
51 """ Unset the hook.
54 """
52 """
55
53
56 sys.excepthook = self.old_hook
54 sys.excepthook = self.old_hook
57
55
58 def clear(self):
56 def clear(self):
59 """ Remove the stored traceback.
57 """ Remove the stored traceback.
60 """
58 """
61
59
62 self.args = None
60 self.args = None
63
61
64 def add_to_message(self, message):
62 def add_to_message(self, message):
65 """ Add the formatted display of the traceback to the message dictionary
63 """ Add the formatted display of the traceback to the message dictionary
66 being returned from the interpreter to its listeners.
64 being returned from the interpreter to its listeners.
67
65
68 Parameters
66 Parameters
69 ----------
67 ----------
70 message : dict
68 message : dict
71 """
69 """
72
70
73 # If there was no traceback, then don't add anything.
71 # If there was no traceback, then don't add anything.
74 if self.args is None:
72 if self.args is None:
75 return
73 return
76
74
77 # Go through the list of formatters and let them add their formatting.
75 # Go through the list of formatters and let them add their formatting.
78 traceback = {}
76 traceback = {}
79 for formatter in self.formatters:
77 try:
80 traceback[formatter.identifier] = formatter(*self.args)
78 for formatter in self.formatters:
81
79 traceback[formatter.identifier] = formatter(*self.args)
80 except:
81 # This works always, including with string exceptions.
82 traceback['fallback'] = repr(self.args)
83
82 message['traceback'] = traceback
84 message['traceback'] = traceback
83
85
@@ -1,133 +1,135 b''
1 """Decorators for labeling test objects.
1 """Decorators for labeling test objects.
2
2
3 Decorators that merely return a modified version of the original
3 Decorators that merely return a modified version of the original
4 function object are straightforward. Decorators that return a new
4 function object are straightforward. Decorators that return a new
5 function object need to use
5 function object need to use
6 nose.tools.make_decorator(original_function)(decorator) in returning
6 nose.tools.make_decorator(original_function)(decorator) in returning
7 the decorator, in order to preserve metadata such as function name,
7 the decorator, in order to preserve metadata such as function name,
8 setup and teardown functions and so on - see nose.tools for more
8 setup and teardown functions and so on - see nose.tools for more
9 information.
9 information.
10
10
11 NOTE: This file contains IPython-specific decorators and imports the
11 NOTE: This file contains IPython-specific decorators and imports the
12 numpy.testing.decorators file, which we've copied verbatim. Any of our own
12 numpy.testing.decorators file, which we've copied verbatim. Any of our own
13 code will be added at the bottom if we end up extending this.
13 code will be added at the bottom if we end up extending this.
14 """
14 """
15
15
16 # Stdlib imports
16 # Stdlib imports
17 import inspect
17 import inspect
18
18
19 # Third-party imports
19 # Third-party imports
20
20
21 # This is Michele Simionato's decorator module, also kept verbatim.
21 # This is Michele Simionato's decorator module, also kept verbatim.
22 from decorator_msim import decorator, update_wrapper
22 from decorator_msim import decorator, update_wrapper
23
23
24 # Grab the numpy-specific decorators which we keep in a file that we
24 # Grab the numpy-specific decorators which we keep in a file that we
25 # occasionally update from upstream: decorators_numpy.py is an IDENTICAL copy
25 # occasionally update from upstream: decorators_numpy.py is an IDENTICAL copy
26 # of numpy.testing.decorators.
26 # of numpy.testing.decorators.
27 from decorators_numpy import *
27 from decorators_numpy import *
28
28
29 ##############################################################################
29 ##############################################################################
30 # Local code begins
30 # Local code begins
31
31
32 # Utility functions
32 # Utility functions
33
33
34 def apply_wrapper(wrapper,func):
34 def apply_wrapper(wrapper,func):
35 """Apply a wrapper to a function for decoration.
35 """Apply a wrapper to a function for decoration.
36
36
37 This mixes Michele Simionato's decorator tool with nose's make_decorator,
37 This mixes Michele Simionato's decorator tool with nose's make_decorator,
38 to apply a wrapper in a decorator so that all nose attributes, as well as
38 to apply a wrapper in a decorator so that all nose attributes, as well as
39 function signature and other properties, survive the decoration cleanly.
39 function signature and other properties, survive the decoration cleanly.
40 This will ensure that wrapped functions can still be well introspected via
40 This will ensure that wrapped functions can still be well introspected via
41 IPython, for example.
41 IPython, for example.
42 """
42 """
43 import nose.tools
43 import nose.tools
44
44
45 return decorator(wrapper,nose.tools.make_decorator(func)(wrapper))
45 return decorator(wrapper,nose.tools.make_decorator(func)(wrapper))
46
46
47
47
48 def make_label_dec(label,ds=None):
48 def make_label_dec(label,ds=None):
49 """Factory function to create a decorator that applies one or more labels.
49 """Factory function to create a decorator that applies one or more labels.
50
50
51 :Parameters:
51 :Parameters:
52 label : string or sequence
52 label : string or sequence
53 One or more labels that will be applied by the decorator to the functions
53 One or more labels that will be applied by the decorator to the functions
54 it decorates. Labels are attributes of the decorated function with their
54 it decorates. Labels are attributes of the decorated function with their
55 value set to True.
55 value set to True.
56
56
57 :Keywords:
57 :Keywords:
58 ds : string
58 ds : string
59 An optional docstring for the resulting decorator. If not given, a
59 An optional docstring for the resulting decorator. If not given, a
60 default docstring is auto-generated.
60 default docstring is auto-generated.
61
61
62 :Returns:
62 :Returns:
63 A decorator.
63 A decorator.
64
64
65 :Examples:
65 :Examples:
66
66
67 A simple labeling decorator:
67 A simple labeling decorator:
68 >>> slow = make_label_dec('slow')
68 >>> slow = make_label_dec('slow')
69 >>> print slow.__doc__
69 >>> print slow.__doc__
70 Labels a test as 'slow'.
70 Labels a test as 'slow'.
71
71
72 And one that uses multiple labels and a custom docstring:
72 And one that uses multiple labels and a custom docstring:
73 >>> rare = make_label_dec(['slow','hard'],
73 >>> rare = make_label_dec(['slow','hard'],
74 ... "Mix labels 'slow' and 'hard' for rare tests.")
74 ... "Mix labels 'slow' and 'hard' for rare tests.")
75 >>> print rare.__doc__
75 >>> print rare.__doc__
76 Mix labels 'slow' and 'hard' for rare tests.
76 Mix labels 'slow' and 'hard' for rare tests.
77
77
78 Now, let's test using this one:
78 Now, let's test using this one:
79 >>> @rare
79 >>> @rare
80 ... def f(): pass
80 ... def f(): pass
81 ...
81 ...
82 >>>
82 >>>
83 >>> f.slow
83 >>> f.slow
84 True
84 True
85 >>> f.hard
85 >>> f.hard
86 True
86 True
87 """
87 """
88
88
89 if isinstance(label,basestring):
89 if isinstance(label,basestring):
90 labels = [label]
90 labels = [label]
91 else:
91 else:
92 labels = label
92 labels = label
93
93
94 # Validate that the given label(s) are OK for use in setattr() by doing a
94 # Validate that the given label(s) are OK for use in setattr() by doing a
95 # dry run on a dummy function.
95 # dry run on a dummy function.
96 tmp = lambda : None
96 tmp = lambda : None
97 for label in labels:
97 for label in labels:
98 setattr(tmp,label,True)
98 setattr(tmp,label,True)
99
99
100 # This is the actual decorator we'll return
100 # This is the actual decorator we'll return
101 def decor(f):
101 def decor(f):
102 for label in labels:
102 for label in labels:
103 setattr(f,label,True)
103 setattr(f,label,True)
104 return f
104 return f
105
105
106 # Apply the user's docstring, or autogenerate a basic one
106 # Apply the user's docstring, or autogenerate a basic one
107 if ds is None:
107 if ds is None:
108 ds = "Labels a test as %r." % label
108 ds = "Labels a test as %r." % label
109 decor.__doc__ = ds
109 decor.__doc__ = ds
110
110
111 return decor
111 return decor
112
112
113 #-----------------------------------------------------------------------------
113 #-----------------------------------------------------------------------------
114 # Decorators for public use
114 # Decorators for public use
115
115
116 skip_doctest = make_label_dec('skip_doctest',
116 skip_doctest = make_label_dec('skip_doctest',
117 """Decorator - mark a function or method for skipping its doctest.
117 """Decorator - mark a function or method for skipping its doctest.
118
118
119 This decorator allows you to mark a function whose docstring you wish to
119 This decorator allows you to mark a function whose docstring you wish to
120 omit from testing, while preserving the docstring for introspection, help,
120 omit from testing, while preserving the docstring for introspection, help,
121 etc.""")
121 etc.""")
122
122
123
123
124 def skip(func):
124 def skip(func):
125 """Decorator - mark a test function for skipping from test suite."""
125 """Decorator - mark a test function for skipping from test suite."""
126
126
127 import nose
127 import nose
128
128
129 def wrapper(*a,**k):
129 def wrapper(*a,**k):
130 raise nose.SkipTest("Skipping test for function: %s" %
130 raise nose.SkipTest("Skipping test for function: %s" %
131 func.__name__)
131 func.__name__)
132
132
133 return apply_wrapper(wrapper,func)
133 return apply_wrapper(wrapper,func)
134
135
@@ -1,66 +1,66 b''
1 # Set this prefix to where you want to install the plugin
1 # Set this prefix to where you want to install the plugin
2 PREFIX=~/usr/local
2 PREFIX=~/usr/local
3 PREFIX=~/tmp/local
3 PREFIX=~/tmp/local
4
4
5 NOSE0=nosetests -vs --with-doctest --doctest-tests
5 NOSE0=nosetests -vs --with-doctest --doctest-tests --detailed-errors
6 NOSE=nosetests -vvs --with-ipdoctest --doctest-tests --doctest-extension=txt
6 NOSE=nosetests -vvs --with-ipdoctest --doctest-tests --doctest-extension=txt --detailed-errors
7
7
8 SRC=ipdoctest.py setup.py ../decorators.py
8 SRC=ipdoctest.py setup.py ../decorators.py
9
9
10 # Default target for clean 'make'
10 # Default target for clean 'make'
11 default: iplib
11 default: iplib
12
12
13 # The actual plugin installation
13 # The actual plugin installation
14 plugin: IPython_doctest_plugin.egg-info
14 plugin: IPython_doctest_plugin.egg-info
15
15
16 # Simple targets that test one thing
16 # Simple targets that test one thing
17 simple: plugin simple.py
17 simple: plugin simple.py
18 $(NOSE) simple.py
18 $(NOSE) simple.py
19
19
20 dtest: plugin dtexample.py
20 dtest: plugin dtexample.py
21 $(NOSE) dtexample.py
21 $(NOSE) dtexample.py
22
22
23 rtest: plugin test_refs.py
23 rtest: plugin test_refs.py
24 $(NOSE) test_refs.py
24 $(NOSE) test_refs.py
25
25
26 test: plugin dtexample.py
26 test: plugin dtexample.py
27 $(NOSE) dtexample.py test*.py test*.txt
27 $(NOSE) dtexample.py test*.py test*.txt
28
28
29 deb: plugin dtexample.py
29 deb: plugin dtexample.py
30 $(NOSE) test_combo.txt
30 $(NOSE) test_combo.txt
31
31
32 # IPython tests
32 # IPython tests
33 deco:
33 deco:
34 $(NOSE0) -x IPython.testing.decorators
34 $(NOSE0) -x IPython.testing.decorators
35
35
36 magic: plugin
36 magic: plugin
37 $(NOSE) -x IPython.Magic
37 $(NOSE) -x IPython.Magic
38
38
39 ipipe: plugin
39 ipipe: plugin
40 $(NOSE) -x IPython.Extensions.ipipe
40 $(NOSE) -x IPython.Extensions.ipipe
41
41
42 iplib: plugin
42 iplib: plugin
43 $(NOSE) -x IPython.iplib
43 $(NOSE) -x IPython.iplib
44
44
45 strd: plugin
45 strd: plugin
46 nosetests -vs --with-doctest --doctest-tests IPython.strdispatch
46 nosetests -vs --with-doctest --doctest-tests IPython.strdispatch
47 $(NOSE) IPython.strdispatch
47 $(NOSE) IPython.strdispatch
48
48
49 # All of ipython itself
49 # All of ipython itself
50 ipython: plugin
50 ipython: plugin
51 $(NOSE) IPython
51 $(NOSE) IPython
52
52
53 # Combined targets
53 # Combined targets
54 sr: rtest strd
54 sr: rtest strd
55
55
56 base: dtest rtest test strd deco
56 base: dtest rtest test strd deco
57
57
58 all: base ipython
58 all: base ipython
59
59
60 # Main plugin and cleanup
60 # Main plugin and cleanup
61 IPython_doctest_plugin.egg-info: $(SRC)
61 IPython_doctest_plugin.egg-info: $(SRC)
62 python setup.py install --prefix=$(PREFIX)
62 python setup.py install --prefix=$(PREFIX)
63 touch $@
63 touch $@
64
64
65 clean:
65 clean:
66 rm -rf IPython_doctest_plugin.egg-info *~ *pyc build/ dist/
66 rm -rf IPython_doctest_plugin.egg-info *~ *pyc build/ dist/
@@ -1,174 +1,175 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
2 # -*- coding: utf-8 -*-
3 """Setup script for IPython.
3 """Setup script for IPython.
4
4
5 Under Posix environments it works like a typical setup.py script.
5 Under Posix environments it works like a typical setup.py script.
6 Under Windows, the command sdist is not supported, since IPython
6 Under Windows, the command sdist is not supported, since IPython
7 requires utilities which are not available under Windows."""
7 requires utilities which are not available under Windows."""
8
8
9 #-------------------------------------------------------------------------------
9 #-------------------------------------------------------------------------------
10 # Copyright (C) 2008 The IPython Development Team
10 # Copyright (C) 2008 The IPython Development Team
11 #
11 #
12 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
14 #-------------------------------------------------------------------------------
14 #-------------------------------------------------------------------------------
15
15
16 #-------------------------------------------------------------------------------
16 #-------------------------------------------------------------------------------
17 # Imports
17 # Imports
18 #-------------------------------------------------------------------------------
18 #-------------------------------------------------------------------------------
19
19
20 # Stdlib imports
20 # Stdlib imports
21 import os
21 import os
22 import sys
22 import sys
23
23
24 from glob import glob
24 from glob import glob
25
25
26 # BEFORE importing distutils, remove MANIFEST. distutils doesn't properly
26 # BEFORE importing distutils, remove MANIFEST. distutils doesn't properly
27 # update it when the contents of directories change.
27 # update it when the contents of directories change.
28 if os.path.exists('MANIFEST'): os.remove('MANIFEST')
28 if os.path.exists('MANIFEST'): os.remove('MANIFEST')
29
29
30 from distutils.core import setup
30 from distutils.core import setup
31
31
32 # Local imports
32 # Local imports
33 from IPython.genutils import target_update
33 from IPython.genutils import target_update
34
34
35 from setupbase import (
35 from setupbase import (
36 setup_args,
36 setup_args,
37 find_packages,
37 find_packages,
38 find_package_data,
38 find_package_data,
39 find_scripts,
39 find_scripts,
40 find_data_files,
40 find_data_files,
41 check_for_dependencies
41 check_for_dependencies
42 )
42 )
43
43
44 isfile = os.path.isfile
44 isfile = os.path.isfile
45
45
46 #-------------------------------------------------------------------------------
46 #-------------------------------------------------------------------------------
47 # Handle OS specific things
47 # Handle OS specific things
48 #-------------------------------------------------------------------------------
48 #-------------------------------------------------------------------------------
49
49
50 if os.name == 'posix':
50 if os.name == 'posix':
51 os_name = 'posix'
51 os_name = 'posix'
52 elif os.name in ['nt','dos']:
52 elif os.name in ['nt','dos']:
53 os_name = 'windows'
53 os_name = 'windows'
54 else:
54 else:
55 print 'Unsupported operating system:',os.name
55 print 'Unsupported operating system:',os.name
56 sys.exit(1)
56 sys.exit(1)
57
57
58 # Under Windows, 'sdist' has not been supported. Now that the docs build with
58 # Under Windows, 'sdist' has not been supported. Now that the docs build with
59 # Sphinx it might work, but let's not turn it on until someone confirms that it
59 # Sphinx it might work, but let's not turn it on until someone confirms that it
60 # actually works.
60 # actually works.
61 if os_name == 'windows' and 'sdist' in sys.argv:
61 if os_name == 'windows' and 'sdist' in sys.argv:
62 print 'The sdist command is not available under Windows. Exiting.'
62 print 'The sdist command is not available under Windows. Exiting.'
63 sys.exit(1)
63 sys.exit(1)
64
64
65 #-------------------------------------------------------------------------------
65 #-------------------------------------------------------------------------------
66 # Things related to the IPython documentation
66 # Things related to the IPython documentation
67 #-------------------------------------------------------------------------------
67 #-------------------------------------------------------------------------------
68
68
69 # update the manuals when building a source dist
69 # update the manuals when building a source dist
70 if len(sys.argv) >= 2 and sys.argv[1] in ('sdist','bdist_rpm'):
70 if len(sys.argv) >= 2 and sys.argv[1] in ('sdist','bdist_rpm'):
71 import textwrap
71 import textwrap
72
72
73 # List of things to be updated. Each entry is a triplet of args for
73 # List of things to be updated. Each entry is a triplet of args for
74 # target_update()
74 # target_update()
75 to_update = [
75 to_update = [
76 # FIXME - Disabled for now: we need to redo an automatic way
76 # FIXME - Disabled for now: we need to redo an automatic way
77 # of generating the magic info inside the rst.
77 # of generating the magic info inside the rst.
78 #('doc/magic.tex',
78 #('doc/magic.tex',
79 #['IPython/Magic.py'],
79 #['IPython/Magic.py'],
80 #"cd doc && ./update_magic.sh" ),
80 #"cd doc && ./update_magic.sh" ),
81
81
82 ('doc/ipython.1.gz',
82 ('doc/ipython.1.gz',
83 ['doc/ipython.1'],
83 ['doc/ipython.1'],
84 "cd doc && gzip -9c ipython.1 > ipython.1.gz"),
84 "cd doc && gzip -9c ipython.1 > ipython.1.gz"),
85
85
86 ('doc/pycolor.1.gz',
86 ('doc/pycolor.1.gz',
87 ['doc/pycolor.1'],
87 ['doc/pycolor.1'],
88 "cd doc && gzip -9c pycolor.1 > pycolor.1.gz"),
88 "cd doc && gzip -9c pycolor.1 > pycolor.1.gz"),
89 ]
89 ]
90
90
91 # Only build the docs is sphinx is present
91 # Only build the docs is sphinx is present
92 try:
92 try:
93 import sphinx
93 import sphinx
94 except ImportError:
94 except ImportError:
95 pass
95 pass
96 else:
96 else:
97 pass
97 pass
98 # BEG: This is disabled as I am not sure what to depend on.
98 # BEG: This is disabled as I am not sure what to depend on.
99 # I actually don't think we should be automatically building
99 # I actually don't think we should be automatically building
100 # the docs for people.
100 # the docs for people.
101 # The do_sphinx scripts builds html and pdf, so just one
101 # The do_sphinx scripts builds html and pdf, so just one
102 # target is enough to cover all manual generation
102 # target is enough to cover all manual generation
103 # to_update.append(
103 # to_update.append(
104 # ('doc/manual/ipython.pdf',
104 # ('doc/manual/ipython.pdf',
105 # ['IPython/Release.py','doc/source/ipython.rst'],
105 # ['IPython/Release.py','doc/source/ipython.rst'],
106 # "cd docs && python do_sphinx.py")
106 # "cd docs && python do_sphinx.py")
107 # )
107 # )
108 [ target_update(*t) for t in to_update ]
108 [ target_update(*t) for t in to_update ]
109
109
110 #---------------------------------------------------------------------------
110 #---------------------------------------------------------------------------
111 # Find all the packages, package data, scripts and data_files
111 # Find all the packages, package data, scripts and data_files
112 #---------------------------------------------------------------------------
112 #---------------------------------------------------------------------------
113
113
114 packages = find_packages()
114 packages = find_packages()
115 package_data = find_package_data()
115 package_data = find_package_data()
116 scripts = find_scripts()
116 scripts = find_scripts()
117 data_files = find_data_files()
117 data_files = find_data_files()
118
118
119 #---------------------------------------------------------------------------
119 #---------------------------------------------------------------------------
120 # Handle dependencies and setuptools specific things
120 # Handle dependencies and setuptools specific things
121 #---------------------------------------------------------------------------
121 #---------------------------------------------------------------------------
122
122
123 # This dict is used for passing extra arguments that are setuptools
123 # This dict is used for passing extra arguments that are setuptools
124 # specific to setup
124 # specific to setup
125 setuptools_extra_args = {}
125 setuptools_extra_args = {}
126
126
127 if 'setuptools' in sys.modules:
127 if 'setuptools' in sys.modules:
128 setuptools_extra_args['zip_safe'] = False
128 setuptools_extra_args['zip_safe'] = False
129 setuptools_extra_args['entry_points'] = {
129 setuptools_extra_args['entry_points'] = {
130 'console_scripts': [
130 'console_scripts': [
131 'ipython = IPython.ipapi:launch_new_instance',
131 'ipython = IPython.ipapi:launch_new_instance',
132 'pycolor = IPython.PyColorize:main',
132 'pycolor = IPython.PyColorize:main',
133 'ipcontroller = IPython.kernel.scripts.ipcontroller:main',
133 'ipcontroller = IPython.kernel.scripts.ipcontroller:main',
134 'ipengine = IPython.kernel.scripts.ipengine:main',
134 'ipengine = IPython.kernel.scripts.ipengine:main',
135 'ipcluster = IPython.kernel.scripts.ipcluster:main'
135 'ipcluster = IPython.kernel.scripts.ipcluster:main',
136 'ipythonx = IPython.frontend.wx.ipythonx:main'
136 ]
137 ]
137 }
138 }
138 setup_args["extras_require"] = dict(
139 setup_args["extras_require"] = dict(
139 kernel = [
140 kernel = [
140 "zope.interface>=3.4.1",
141 "zope.interface>=3.4.1",
141 "Twisted>=8.0.1",
142 "Twisted>=8.0.1",
142 "foolscap>=0.2.6"
143 "foolscap>=0.2.6"
143 ],
144 ],
144 doc=['Sphinx>=0.3','pygments'],
145 doc=['Sphinx>=0.3','pygments'],
145 test='nose>=0.10.1',
146 test='nose>=0.10.1',
146 security=["pyOpenSSL>=0.6"]
147 security=["pyOpenSSL>=0.6"]
147 )
148 )
148 # Allow setuptools to handle the scripts
149 # Allow setuptools to handle the scripts
149 scripts = []
150 scripts = []
150 # eggs will lack docs, examples
151 # eggs will lack docs, examples
151 data_files = []
152 data_files = []
152 else:
153 else:
153 # package_data of setuptools was introduced to distutils in 2.4
154 # package_data of setuptools was introduced to distutils in 2.4
154 cfgfiles = filter(isfile, glob('IPython/UserConfig/*'))
155 cfgfiles = filter(isfile, glob('IPython/UserConfig/*'))
155 if sys.version_info < (2,4):
156 if sys.version_info < (2,4):
156 data_files.append(('lib', 'IPython/UserConfig', cfgfiles))
157 data_files.append(('lib', 'IPython/UserConfig', cfgfiles))
157 # If we are running without setuptools, call this function which will
158 # If we are running without setuptools, call this function which will
158 # check for dependencies an inform the user what is needed. This is
159 # check for dependencies an inform the user what is needed. This is
159 # just to make life easy for users.
160 # just to make life easy for users.
160 check_for_dependencies()
161 check_for_dependencies()
161
162
162
163
163 #---------------------------------------------------------------------------
164 #---------------------------------------------------------------------------
164 # Do the actual setup now
165 # Do the actual setup now
165 #---------------------------------------------------------------------------
166 #---------------------------------------------------------------------------
166
167
167 setup_args['packages'] = packages
168 setup_args['packages'] = packages
168 setup_args['package_data'] = package_data
169 setup_args['package_data'] = package_data
169 setup_args['scripts'] = scripts
170 setup_args['scripts'] = scripts
170 setup_args['data_files'] = data_files
171 setup_args['data_files'] = data_files
171 setup_args.update(setuptools_extra_args)
172 setup_args.update(setuptools_extra_args)
172
173
173 if __name__ == '__main__':
174 if __name__ == '__main__':
174 setup(**setup_args)
175 setup(**setup_args)
@@ -1,232 +1,237 b''
1 # encoding: utf-8
1 # encoding: utf-8
2
2
3 """
3 """
4 This module defines the things that are used in setup.py for building IPython
4 This module defines the things that are used in setup.py for building IPython
5
5
6 This includes:
6 This includes:
7
7
8 * The basic arguments to setup
8 * The basic arguments to setup
9 * Functions for finding things like packages, package data, etc.
9 * Functions for finding things like packages, package data, etc.
10 * A function for checking dependencies.
10 * A function for checking dependencies.
11 """
11 """
12
12
13 __docformat__ = "restructuredtext en"
13 __docformat__ = "restructuredtext en"
14
14
15 #-------------------------------------------------------------------------------
15 #-------------------------------------------------------------------------------
16 # Copyright (C) 2008 The IPython Development Team
16 # Copyright (C) 2008 The IPython Development Team
17 #
17 #
18 # Distributed under the terms of the BSD License. The full license is in
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
19 # the file COPYING, distributed as part of this software.
20 #-------------------------------------------------------------------------------
20 #-------------------------------------------------------------------------------
21
21
22 #-------------------------------------------------------------------------------
22 #-------------------------------------------------------------------------------
23 # Imports
23 # Imports
24 #-------------------------------------------------------------------------------
24 #-------------------------------------------------------------------------------
25
25
26 import os, sys
26 import os, sys
27
27
28 from glob import glob
28 from glob import glob
29
29
30 from setupext import install_data_ext
30 from setupext import install_data_ext
31
31
32 #-------------------------------------------------------------------------------
32 #-------------------------------------------------------------------------------
33 # Useful globals and utility functions
33 # Useful globals and utility functions
34 #-------------------------------------------------------------------------------
34 #-------------------------------------------------------------------------------
35
35
36 # A few handy globals
36 # A few handy globals
37 isfile = os.path.isfile
37 isfile = os.path.isfile
38 pjoin = os.path.join
38 pjoin = os.path.join
39
39
40 def oscmd(s):
40 def oscmd(s):
41 print ">", s
41 print ">", s
42 os.system(s)
42 os.system(s)
43
43
44 # A little utility we'll need below, since glob() does NOT allow you to do
44 # A little utility we'll need below, since glob() does NOT allow you to do
45 # exclusion on multiple endings!
45 # exclusion on multiple endings!
46 def file_doesnt_endwith(test,endings):
46 def file_doesnt_endwith(test,endings):
47 """Return true if test is a file and its name does NOT end with any
47 """Return true if test is a file and its name does NOT end with any
48 of the strings listed in endings."""
48 of the strings listed in endings."""
49 if not isfile(test):
49 if not isfile(test):
50 return False
50 return False
51 for e in endings:
51 for e in endings:
52 if test.endswith(e):
52 if test.endswith(e):
53 return False
53 return False
54 return True
54 return True
55
55
56 #---------------------------------------------------------------------------
56 #---------------------------------------------------------------------------
57 # Basic project information
57 # Basic project information
58 #---------------------------------------------------------------------------
58 #---------------------------------------------------------------------------
59
59
60 # Release.py contains version, authors, license, url, keywords, etc.
60 # Release.py contains version, authors, license, url, keywords, etc.
61 execfile(pjoin('IPython','Release.py'))
61 execfile(pjoin('IPython','Release.py'))
62
62
63 # Create a dict with the basic information
63 # Create a dict with the basic information
64 # This dict is eventually passed to setup after additional keys are added.
64 # This dict is eventually passed to setup after additional keys are added.
65 setup_args = dict(
65 setup_args = dict(
66 name = name,
66 name = name,
67 version = version,
67 version = version,
68 description = description,
68 description = description,
69 long_description = long_description,
69 long_description = long_description,
70 author = author,
70 author = author,
71 author_email = author_email,
71 author_email = author_email,
72 url = url,
72 url = url,
73 download_url = download_url,
73 download_url = download_url,
74 license = license,
74 license = license,
75 platforms = platforms,
75 platforms = platforms,
76 keywords = keywords,
76 keywords = keywords,
77 cmdclass = {'install_data': install_data_ext},
77 cmdclass = {'install_data': install_data_ext},
78 )
78 )
79
79
80
80
81 #---------------------------------------------------------------------------
81 #---------------------------------------------------------------------------
82 # Find packages
82 # Find packages
83 #---------------------------------------------------------------------------
83 #---------------------------------------------------------------------------
84
84
85 def add_package(packages, pname, config=False, tests=False, scripts=False, others=None):
85 def add_package(packages, pname, config=False, tests=False, scripts=False, others=None):
86 """
86 """
87 Add a package to the list of packages, including certain subpackages.
87 Add a package to the list of packages, including certain subpackages.
88 """
88 """
89 packages.append('.'.join(['IPython',pname]))
89 packages.append('.'.join(['IPython',pname]))
90 if config:
90 if config:
91 packages.append('.'.join(['IPython',pname,'config']))
91 packages.append('.'.join(['IPython',pname,'config']))
92 if tests:
92 if tests:
93 packages.append('.'.join(['IPython',pname,'tests']))
93 packages.append('.'.join(['IPython',pname,'tests']))
94 if scripts:
94 if scripts:
95 packages.append('.'.join(['IPython',pname,'scripts']))
95 packages.append('.'.join(['IPython',pname,'scripts']))
96 if others is not None:
96 if others is not None:
97 for o in others:
97 for o in others:
98 packages.append('.'.join(['IPython',pname,o]))
98 packages.append('.'.join(['IPython',pname,o]))
99
99
100 def find_packages():
100 def find_packages():
101 """
101 """
102 Find all of IPython's packages.
102 Find all of IPython's packages.
103 """
103 """
104 packages = ['IPython']
104 packages = ['IPython']
105 add_package(packages, 'config', tests=True)
105 add_package(packages, 'config', tests=True)
106 add_package(packages , 'Extensions')
106 add_package(packages , 'Extensions')
107 add_package(packages, 'external')
107 add_package(packages, 'external')
108 add_package(packages, 'gui')
108 add_package(packages, 'gui')
109 add_package(packages, 'gui.wx')
109 add_package(packages, 'gui.wx')
110 add_package(packages, 'frontend', tests=True)
111 add_package(packages, 'frontend._process')
112 add_package(packages, 'frontend.wx')
113 add_package(packages, 'frontend.cocoa', tests=True)
110 add_package(packages, 'kernel', config=True, tests=True, scripts=True)
114 add_package(packages, 'kernel', config=True, tests=True, scripts=True)
111 add_package(packages, 'kernel.core', config=True, tests=True)
115 add_package(packages, 'kernel.core', config=True, tests=True)
112 add_package(packages, 'testing', tests=True)
116 add_package(packages, 'testing', tests=True)
113 add_package(packages, 'tools', tests=True)
117 add_package(packages, 'tools', tests=True)
114 add_package(packages, 'UserConfig')
118 add_package(packages, 'UserConfig')
115 return packages
119 return packages
116
120
117 #---------------------------------------------------------------------------
121 #---------------------------------------------------------------------------
118 # Find package data
122 # Find package data
119 #---------------------------------------------------------------------------
123 #---------------------------------------------------------------------------
120
124
121 def find_package_data():
125 def find_package_data():
122 """
126 """
123 Find IPython's package_data.
127 Find IPython's package_data.
124 """
128 """
125 # This is not enough for these things to appear in an sdist.
129 # This is not enough for these things to appear in an sdist.
126 # We need to muck with the MANIFEST to get this to work
130 # We need to muck with the MANIFEST to get this to work
127 package_data = {
131 package_data = {
128 'IPython.UserConfig' : ['*'],
132 'IPython.UserConfig' : ['*'],
129 'IPython.tools.tests' : ['*.txt'],
133 'IPython.tools.tests' : ['*.txt'],
130 'IPython.testing' : ['*.txt']
134 'IPython.testing' : ['*.txt']
131 }
135 }
132 return package_data
136 return package_data
133
137
134
138
135 #---------------------------------------------------------------------------
139 #---------------------------------------------------------------------------
136 # Find data files
140 # Find data files
137 #---------------------------------------------------------------------------
141 #---------------------------------------------------------------------------
138
142
139 def find_data_files():
143 def find_data_files():
140 """
144 """
141 Find IPython's data_files.
145 Find IPython's data_files.
142 """
146 """
143
147
144 # I can't find how to make distutils create a nested dir. structure, so
148 # I can't find how to make distutils create a nested dir. structure, so
145 # in the meantime do it manually. Butt ugly.
149 # in the meantime do it manually. Butt ugly.
146 # Note that http://www.redbrick.dcu.ie/~noel/distutils.html, ex. 2/3, contain
150 # Note that http://www.redbrick.dcu.ie/~noel/distutils.html, ex. 2/3, contain
147 # information on how to do this more cleanly once python 2.4 can be assumed.
151 # information on how to do this more cleanly once python 2.4 can be assumed.
148 # Thanks to Noel for the tip.
152 # Thanks to Noel for the tip.
149 docdirbase = 'share/doc/ipython'
153 docdirbase = 'share/doc/ipython'
150 manpagebase = 'share/man/man1'
154 manpagebase = 'share/man/man1'
151
155
152 # We only need to exclude from this things NOT already excluded in the
156 # We only need to exclude from this things NOT already excluded in the
153 # MANIFEST.in file.
157 # MANIFEST.in file.
154 exclude = ('.sh','.1.gz')
158 exclude = ('.sh','.1.gz')
155 # We need to figure out how we want to package all of our rst docs?
159 # We need to figure out how we want to package all of our rst docs?
156 # docfiles = filter(lambda f:file_doesnt_endwith(f,exclude),glob('docs/*'))
160 # docfiles = filter(lambda f:file_doesnt_endwith(f,exclude),glob('docs/*'))
157 examfiles = filter(isfile, glob('docs/examples/core/*.py'))
161 examfiles = filter(isfile, glob('docs/examples/core/*.py'))
158 examfiles.append(filter(isfile, glob('docs/examples/kernel/*.py')))
162 examfiles.append(filter(isfile, glob('docs/examples/kernel/*.py')))
159 manpages = filter(isfile, glob('docs/man/*.1.gz'))
163 manpages = filter(isfile, glob('docs/man/*.1.gz'))
160 igridhelpfiles = filter(isfile, glob('IPython/Extensions/igrid_help.*'))
164 igridhelpfiles = filter(isfile, glob('IPython/Extensions/igrid_help.*'))
161
165
162 data_files = [#('data', docdirbase, docfiles),
166 data_files = [#('data', docdirbase, docfiles),
163 ('data', pjoin(docdirbase, 'examples'),examfiles),
167 ('data', pjoin(docdirbase, 'examples'),examfiles),
164 ('data', manpagebase, manpages),
168 ('data', manpagebase, manpages),
165 ('data',pjoin(docdirbase, 'extensions'),igridhelpfiles),
169 ('data',pjoin(docdirbase, 'extensions'),igridhelpfiles),
166 ]
170 ]
167 # import pprint
171 # import pprint
168 # pprint.pprint(data_files)
172 # pprint.pprint(data_files)
169 return []
173 return []
170
174
171 #---------------------------------------------------------------------------
175 #---------------------------------------------------------------------------
172 # Find scripts
176 # Find scripts
173 #---------------------------------------------------------------------------
177 #---------------------------------------------------------------------------
174
178
175 def find_scripts():
179 def find_scripts():
176 """
180 """
177 Find IPython's scripts.
181 Find IPython's scripts.
178 """
182 """
179 scripts = []
183 scripts = []
180 scripts.append('IPython/kernel/scripts/ipengine')
184 scripts.append('IPython/kernel/scripts/ipengine')
181 scripts.append('IPython/kernel/scripts/ipcontroller')
185 scripts.append('IPython/kernel/scripts/ipcontroller')
182 scripts.append('IPython/kernel/scripts/ipcluster')
186 scripts.append('IPython/kernel/scripts/ipcluster')
183 scripts.append('scripts/ipython')
187 scripts.append('scripts/ipython')
188 scripts.append('scripts/ipythonx')
184 scripts.append('scripts/pycolor')
189 scripts.append('scripts/pycolor')
185 scripts.append('scripts/irunner')
190 scripts.append('scripts/irunner')
186
191
187 # Script to be run by the windows binary installer after the default setup
192 # Script to be run by the windows binary installer after the default setup
188 # routine, to add shortcuts and similar windows-only things. Windows
193 # routine, to add shortcuts and similar windows-only things. Windows
189 # post-install scripts MUST reside in the scripts/ dir, otherwise distutils
194 # post-install scripts MUST reside in the scripts/ dir, otherwise distutils
190 # doesn't find them.
195 # doesn't find them.
191 if 'bdist_wininst' in sys.argv:
196 if 'bdist_wininst' in sys.argv:
192 if len(sys.argv) > 2 and ('sdist' in sys.argv or 'bdist_rpm' in sys.argv):
197 if len(sys.argv) > 2 and ('sdist' in sys.argv or 'bdist_rpm' in sys.argv):
193 print >> sys.stderr,"ERROR: bdist_wininst must be run alone. Exiting."
198 print >> sys.stderr,"ERROR: bdist_wininst must be run alone. Exiting."
194 sys.exit(1)
199 sys.exit(1)
195 scripts.append('scripts/ipython_win_post_install.py')
200 scripts.append('scripts/ipython_win_post_install.py')
196
201
197 return scripts
202 return scripts
198
203
199 #---------------------------------------------------------------------------
204 #---------------------------------------------------------------------------
200 # Find scripts
205 # Find scripts
201 #---------------------------------------------------------------------------
206 #---------------------------------------------------------------------------
202
207
203 def check_for_dependencies():
208 def check_for_dependencies():
204 """Check for IPython's dependencies.
209 """Check for IPython's dependencies.
205
210
206 This function should NOT be called if running under setuptools!
211 This function should NOT be called if running under setuptools!
207 """
212 """
208 from setupext.setupext import (
213 from setupext.setupext import (
209 print_line, print_raw, print_status, print_message,
214 print_line, print_raw, print_status, print_message,
210 check_for_zopeinterface, check_for_twisted,
215 check_for_zopeinterface, check_for_twisted,
211 check_for_foolscap, check_for_pyopenssl,
216 check_for_foolscap, check_for_pyopenssl,
212 check_for_sphinx, check_for_pygments,
217 check_for_sphinx, check_for_pygments,
213 check_for_nose, check_for_pexpect
218 check_for_nose, check_for_pexpect
214 )
219 )
215 print_line()
220 print_line()
216 print_raw("BUILDING IPYTHON")
221 print_raw("BUILDING IPYTHON")
217 print_status('python', sys.version)
222 print_status('python', sys.version)
218 print_status('platform', sys.platform)
223 print_status('platform', sys.platform)
219 if sys.platform == 'win32':
224 if sys.platform == 'win32':
220 print_status('Windows version', sys.getwindowsversion())
225 print_status('Windows version', sys.getwindowsversion())
221
226
222 print_raw("")
227 print_raw("")
223 print_raw("OPTIONAL DEPENDENCIES")
228 print_raw("OPTIONAL DEPENDENCIES")
224
229
225 check_for_zopeinterface()
230 check_for_zopeinterface()
226 check_for_twisted()
231 check_for_twisted()
227 check_for_foolscap()
232 check_for_foolscap()
228 check_for_pyopenssl()
233 check_for_pyopenssl()
229 check_for_sphinx()
234 check_for_sphinx()
230 check_for_pygments()
235 check_for_pygments()
231 check_for_nose()
236 check_for_nose()
232 check_for_pexpect() No newline at end of file
237 check_for_pexpect()
General Comments 0
You need to be logged in to leave comments. Login now