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 |
@@ -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 | 1 | """ Legacy stuff |
|
2 | 2 | |
|
3 | 3 | Various stuff that are there for historical / familiarity reasons. |
|
4 | 4 | |
|
5 | 5 | This is automatically imported by default profile, though not other profiles |
|
6 | 6 | (e.g. 'sh' profile). |
|
7 | 7 | |
|
8 | 8 | Stuff that is considered obsolete / redundant is gradually moved here. |
|
9 | 9 | |
|
10 | 10 | """ |
|
11 | 11 | |
|
12 | 12 | import IPython.ipapi |
|
13 | 13 | ip = IPython.ipapi.get() |
|
14 | 14 | |
|
15 | 15 | import os,sys |
|
16 | 16 | |
|
17 | 17 | from IPython.genutils import * |
|
18 | 18 | |
|
19 | 19 | # use rehashx |
|
20 | 20 | |
|
21 | 21 | def magic_rehash(self, parameter_s = ''): |
|
22 | 22 | """Update the alias table with all entries in $PATH. |
|
23 | 23 | |
|
24 | 24 | This version does no checks on execute permissions or whether the |
|
25 | 25 | contents of $PATH are truly files (instead of directories or something |
|
26 | 26 | else). For such a safer (but slower) version, use %rehashx.""" |
|
27 | 27 | |
|
28 | 28 | # This function (and rehashx) manipulate the alias_table directly |
|
29 | 29 | # rather than calling magic_alias, for speed reasons. A rehash on a |
|
30 | 30 | # typical Linux box involves several thousand entries, so efficiency |
|
31 | 31 | # here is a top concern. |
|
32 | 32 | |
|
33 | 33 | path = filter(os.path.isdir,os.environ.get('PATH','').split(os.pathsep)) |
|
34 | 34 | alias_table = self.shell.alias_table |
|
35 | 35 | for pdir in path: |
|
36 | 36 | for ff in os.listdir(pdir): |
|
37 | 37 | # each entry in the alias table must be (N,name), where |
|
38 | 38 | # N is the number of positional arguments of the alias. |
|
39 | 39 | alias_table[ff] = (0,ff) |
|
40 | 40 | # Make sure the alias table doesn't contain keywords or builtins |
|
41 | 41 | self.shell.alias_table_validate() |
|
42 | 42 | # Call again init_auto_alias() so we get 'rm -i' and other modified |
|
43 | 43 | # aliases since %rehash will probably clobber them |
|
44 | 44 | self.shell.init_auto_alias() |
|
45 | 45 | |
|
46 | 46 | ip.expose_magic("rehash", magic_rehash) |
|
47 | 47 | |
|
48 | 48 | # Exit |
|
49 | 49 | def magic_Quit(self, parameter_s=''): |
|
50 | 50 | """Exit IPython without confirmation (like %Exit).""" |
|
51 | 51 | |
|
52 |
self.shell. |
|
|
52 | self.shell.ask_exit() | |
|
53 | 53 | |
|
54 | 54 | ip.expose_magic("Quit", magic_Quit) |
|
55 | 55 | |
|
56 | 56 | |
|
57 | 57 | # make it autocallable fn if you really need it |
|
58 | 58 | def magic_p(self, parameter_s=''): |
|
59 | 59 | """Just a short alias for Python's 'print'.""" |
|
60 | 60 | exec 'print ' + parameter_s in self.shell.user_ns |
|
61 | 61 | |
|
62 | 62 | ip.expose_magic("p", magic_p) |
@@ -1,3350 +1,3350 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Magic functions for InteractiveShell. |
|
3 | 3 | |
|
4 | 4 | $Id: Magic.py 2996 2008-01-30 06:31:39Z fperez $""" |
|
5 | 5 | |
|
6 | 6 | #***************************************************************************** |
|
7 | 7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
8 | 8 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> |
|
9 | 9 | # |
|
10 | 10 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | 11 | # the file COPYING, distributed as part of this software. |
|
12 | 12 | #***************************************************************************** |
|
13 | 13 | |
|
14 | 14 | #**************************************************************************** |
|
15 | 15 | # Modules and globals |
|
16 | 16 | |
|
17 | 17 | from IPython import Release |
|
18 | 18 | __author__ = '%s <%s>\n%s <%s>' % \ |
|
19 | 19 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) |
|
20 | 20 | __license__ = Release.license |
|
21 | 21 | |
|
22 | 22 | # Python standard modules |
|
23 | 23 | import __builtin__ |
|
24 | 24 | import bdb |
|
25 | 25 | import inspect |
|
26 | 26 | import os |
|
27 | 27 | import pdb |
|
28 | 28 | import pydoc |
|
29 | 29 | import sys |
|
30 | 30 | import re |
|
31 | 31 | import tempfile |
|
32 | 32 | import time |
|
33 | 33 | import cPickle as pickle |
|
34 | 34 | import textwrap |
|
35 | 35 | from cStringIO import StringIO |
|
36 | 36 | from getopt import getopt,GetoptError |
|
37 | 37 | from pprint import pprint, pformat |
|
38 | 38 | from sets import Set |
|
39 | 39 | |
|
40 | 40 | # cProfile was added in Python2.5 |
|
41 | 41 | try: |
|
42 | 42 | import cProfile as profile |
|
43 | 43 | import pstats |
|
44 | 44 | except ImportError: |
|
45 | 45 | # profile isn't bundled by default in Debian for license reasons |
|
46 | 46 | try: |
|
47 | 47 | import profile,pstats |
|
48 | 48 | except ImportError: |
|
49 | 49 | profile = pstats = None |
|
50 | 50 | |
|
51 | 51 | # Homebrewed |
|
52 | 52 | import IPython |
|
53 | 53 | from IPython import Debugger, OInspect, wildcard |
|
54 | 54 | from IPython.FakeModule import FakeModule |
|
55 | 55 | from IPython.Itpl import Itpl, itpl, printpl,itplns |
|
56 | 56 | from IPython.PyColorize import Parser |
|
57 | 57 | from IPython.ipstruct import Struct |
|
58 | 58 | from IPython.macro import Macro |
|
59 | 59 | from IPython.genutils import * |
|
60 | 60 | from IPython import platutils |
|
61 | 61 | import IPython.generics |
|
62 | 62 | import IPython.ipapi |
|
63 | 63 | from IPython.ipapi import UsageError |
|
64 | 64 | from IPython.testing import decorators as testdec |
|
65 | 65 | |
|
66 | 66 | #*************************************************************************** |
|
67 | 67 | # Utility functions |
|
68 | 68 | def on_off(tag): |
|
69 | 69 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
70 | 70 | return ['OFF','ON'][tag] |
|
71 | 71 | |
|
72 | 72 | class Bunch: pass |
|
73 | 73 | |
|
74 | 74 | def compress_dhist(dh): |
|
75 | 75 | head, tail = dh[:-10], dh[-10:] |
|
76 | 76 | |
|
77 | 77 | newhead = [] |
|
78 | 78 | done = Set() |
|
79 | 79 | for h in head: |
|
80 | 80 | if h in done: |
|
81 | 81 | continue |
|
82 | 82 | newhead.append(h) |
|
83 | 83 | done.add(h) |
|
84 | 84 | |
|
85 | 85 | return newhead + tail |
|
86 | 86 | |
|
87 | 87 | |
|
88 | 88 | #*************************************************************************** |
|
89 | 89 | # Main class implementing Magic functionality |
|
90 | 90 | class Magic: |
|
91 | 91 | """Magic functions for InteractiveShell. |
|
92 | 92 | |
|
93 | 93 | Shell functions which can be reached as %function_name. All magic |
|
94 | 94 | functions should accept a string, which they can parse for their own |
|
95 | 95 | needs. This can make some functions easier to type, eg `%cd ../` |
|
96 | 96 | vs. `%cd("../")` |
|
97 | 97 | |
|
98 | 98 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
99 | 99 | at the command line, but it is is needed in the definition. """ |
|
100 | 100 | |
|
101 | 101 | # class globals |
|
102 | 102 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
103 | 103 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
104 | 104 | |
|
105 | 105 | #...................................................................... |
|
106 | 106 | # some utility functions |
|
107 | 107 | |
|
108 | 108 | def __init__(self,shell): |
|
109 | 109 | |
|
110 | 110 | self.options_table = {} |
|
111 | 111 | if profile is None: |
|
112 | 112 | self.magic_prun = self.profile_missing_notice |
|
113 | 113 | self.shell = shell |
|
114 | 114 | |
|
115 | 115 | # namespace for holding state we may need |
|
116 | 116 | self._magic_state = Bunch() |
|
117 | 117 | |
|
118 | 118 | def profile_missing_notice(self, *args, **kwargs): |
|
119 | 119 | error("""\ |
|
120 | 120 | The profile module could not be found. It has been removed from the standard |
|
121 | 121 | python packages because of its non-free license. To use profiling, install the |
|
122 | 122 | python-profiler package from non-free.""") |
|
123 | 123 | |
|
124 | 124 | def default_option(self,fn,optstr): |
|
125 | 125 | """Make an entry in the options_table for fn, with value optstr""" |
|
126 | 126 | |
|
127 | 127 | if fn not in self.lsmagic(): |
|
128 | 128 | error("%s is not a magic function" % fn) |
|
129 | 129 | self.options_table[fn] = optstr |
|
130 | 130 | |
|
131 | 131 | def lsmagic(self): |
|
132 | 132 | """Return a list of currently available magic functions. |
|
133 | 133 | |
|
134 | 134 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
135 | 135 | ['magic_ls','magic_cd',...]""" |
|
136 | 136 | |
|
137 | 137 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
138 | 138 | |
|
139 | 139 | # magics in class definition |
|
140 | 140 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
141 | 141 | callable(Magic.__dict__[fn]) |
|
142 | 142 | # in instance namespace (run-time user additions) |
|
143 | 143 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
144 | 144 | callable(self.__dict__[fn]) |
|
145 | 145 | # and bound magics by user (so they can access self): |
|
146 | 146 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
147 | 147 | callable(self.__class__.__dict__[fn]) |
|
148 | 148 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
149 | 149 | filter(inst_magic,self.__dict__.keys()) + \ |
|
150 | 150 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
151 | 151 | out = [] |
|
152 | 152 | for fn in Set(magics): |
|
153 | 153 | out.append(fn.replace('magic_','',1)) |
|
154 | 154 | out.sort() |
|
155 | 155 | return out |
|
156 | 156 | |
|
157 | 157 | def extract_input_slices(self,slices,raw=False): |
|
158 | 158 | """Return as a string a set of input history slices. |
|
159 | 159 | |
|
160 | 160 | Inputs: |
|
161 | 161 | |
|
162 | 162 | - slices: the set of slices is given as a list of strings (like |
|
163 | 163 | ['1','4:8','9'], since this function is for use by magic functions |
|
164 | 164 | which get their arguments as strings. |
|
165 | 165 | |
|
166 | 166 | Optional inputs: |
|
167 | 167 | |
|
168 | 168 | - raw(False): by default, the processed input is used. If this is |
|
169 | 169 | true, the raw input history is used instead. |
|
170 | 170 | |
|
171 | 171 | Note that slices can be called with two notations: |
|
172 | 172 | |
|
173 | 173 | N:M -> standard python form, means including items N...(M-1). |
|
174 | 174 | |
|
175 | 175 | N-M -> include items N..M (closed endpoint).""" |
|
176 | 176 | |
|
177 | 177 | if raw: |
|
178 | 178 | hist = self.shell.input_hist_raw |
|
179 | 179 | else: |
|
180 | 180 | hist = self.shell.input_hist |
|
181 | 181 | |
|
182 | 182 | cmds = [] |
|
183 | 183 | for chunk in slices: |
|
184 | 184 | if ':' in chunk: |
|
185 | 185 | ini,fin = map(int,chunk.split(':')) |
|
186 | 186 | elif '-' in chunk: |
|
187 | 187 | ini,fin = map(int,chunk.split('-')) |
|
188 | 188 | fin += 1 |
|
189 | 189 | else: |
|
190 | 190 | ini = int(chunk) |
|
191 | 191 | fin = ini+1 |
|
192 | 192 | cmds.append(hist[ini:fin]) |
|
193 | 193 | return cmds |
|
194 | 194 | |
|
195 | 195 | def _ofind(self, oname, namespaces=None): |
|
196 | 196 | """Find an object in the available namespaces. |
|
197 | 197 | |
|
198 | 198 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
199 | 199 | |
|
200 | 200 | Has special code to detect magic functions. |
|
201 | 201 | """ |
|
202 | 202 | |
|
203 | 203 | oname = oname.strip() |
|
204 | 204 | |
|
205 | 205 | alias_ns = None |
|
206 | 206 | if namespaces is None: |
|
207 | 207 | # Namespaces to search in: |
|
208 | 208 | # Put them in a list. The order is important so that we |
|
209 | 209 | # find things in the same order that Python finds them. |
|
210 | 210 | namespaces = [ ('Interactive', self.shell.user_ns), |
|
211 | 211 | ('IPython internal', self.shell.internal_ns), |
|
212 | 212 | ('Python builtin', __builtin__.__dict__), |
|
213 | 213 | ('Alias', self.shell.alias_table), |
|
214 | 214 | ] |
|
215 | 215 | alias_ns = self.shell.alias_table |
|
216 | 216 | |
|
217 | 217 | # initialize results to 'null' |
|
218 | 218 | found = 0; obj = None; ospace = None; ds = None; |
|
219 | 219 | ismagic = 0; isalias = 0; parent = None |
|
220 | 220 | |
|
221 | 221 | # Look for the given name by splitting it in parts. If the head is |
|
222 | 222 | # found, then we look for all the remaining parts as members, and only |
|
223 | 223 | # declare success if we can find them all. |
|
224 | 224 | oname_parts = oname.split('.') |
|
225 | 225 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
226 | 226 | for nsname,ns in namespaces: |
|
227 | 227 | try: |
|
228 | 228 | obj = ns[oname_head] |
|
229 | 229 | except KeyError: |
|
230 | 230 | continue |
|
231 | 231 | else: |
|
232 | 232 | #print 'oname_rest:', oname_rest # dbg |
|
233 | 233 | for part in oname_rest: |
|
234 | 234 | try: |
|
235 | 235 | parent = obj |
|
236 | 236 | obj = getattr(obj,part) |
|
237 | 237 | except: |
|
238 | 238 | # Blanket except b/c some badly implemented objects |
|
239 | 239 | # allow __getattr__ to raise exceptions other than |
|
240 | 240 | # AttributeError, which then crashes IPython. |
|
241 | 241 | break |
|
242 | 242 | else: |
|
243 | 243 | # If we finish the for loop (no break), we got all members |
|
244 | 244 | found = 1 |
|
245 | 245 | ospace = nsname |
|
246 | 246 | if ns == alias_ns: |
|
247 | 247 | isalias = 1 |
|
248 | 248 | break # namespace loop |
|
249 | 249 | |
|
250 | 250 | # Try to see if it's magic |
|
251 | 251 | if not found: |
|
252 | 252 | if oname.startswith(self.shell.ESC_MAGIC): |
|
253 | 253 | oname = oname[1:] |
|
254 | 254 | obj = getattr(self,'magic_'+oname,None) |
|
255 | 255 | if obj is not None: |
|
256 | 256 | found = 1 |
|
257 | 257 | ospace = 'IPython internal' |
|
258 | 258 | ismagic = 1 |
|
259 | 259 | |
|
260 | 260 | # Last try: special-case some literals like '', [], {}, etc: |
|
261 | 261 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
262 | 262 | obj = eval(oname_head) |
|
263 | 263 | found = 1 |
|
264 | 264 | ospace = 'Interactive' |
|
265 | 265 | |
|
266 | 266 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
267 | 267 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
268 | 268 | |
|
269 | 269 | def arg_err(self,func): |
|
270 | 270 | """Print docstring if incorrect arguments were passed""" |
|
271 | 271 | print 'Error in arguments:' |
|
272 | 272 | print OInspect.getdoc(func) |
|
273 | 273 | |
|
274 | 274 | def format_latex(self,strng): |
|
275 | 275 | """Format a string for latex inclusion.""" |
|
276 | 276 | |
|
277 | 277 | # Characters that need to be escaped for latex: |
|
278 | 278 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
279 | 279 | # Magic command names as headers: |
|
280 | 280 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, |
|
281 | 281 | re.MULTILINE) |
|
282 | 282 | # Magic commands |
|
283 | 283 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, |
|
284 | 284 | re.MULTILINE) |
|
285 | 285 | # Paragraph continue |
|
286 | 286 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
287 | 287 | |
|
288 | 288 | # The "\n" symbol |
|
289 | 289 | newline_re = re.compile(r'\\n') |
|
290 | 290 | |
|
291 | 291 | # Now build the string for output: |
|
292 | 292 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
293 | 293 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
294 | 294 | strng) |
|
295 | 295 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
296 | 296 | strng = par_re.sub(r'\\\\',strng) |
|
297 | 297 | strng = escape_re.sub(r'\\\1',strng) |
|
298 | 298 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
299 | 299 | return strng |
|
300 | 300 | |
|
301 | 301 | def format_screen(self,strng): |
|
302 | 302 | """Format a string for screen printing. |
|
303 | 303 | |
|
304 | 304 | This removes some latex-type format codes.""" |
|
305 | 305 | # Paragraph continue |
|
306 | 306 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
307 | 307 | strng = par_re.sub('',strng) |
|
308 | 308 | return strng |
|
309 | 309 | |
|
310 | 310 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
311 | 311 | """Parse options passed to an argument string. |
|
312 | 312 | |
|
313 | 313 | The interface is similar to that of getopt(), but it returns back a |
|
314 | 314 | Struct with the options as keys and the stripped argument string still |
|
315 | 315 | as a string. |
|
316 | 316 | |
|
317 | 317 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
318 | 318 | This allows us to easily expand variables, glob files, quote |
|
319 | 319 | arguments, etc. |
|
320 | 320 | |
|
321 | 321 | Options: |
|
322 | 322 | -mode: default 'string'. If given as 'list', the argument string is |
|
323 | 323 | returned as a list (split on whitespace) instead of a string. |
|
324 | 324 | |
|
325 | 325 | -list_all: put all option values in lists. Normally only options |
|
326 | 326 | appearing more than once are put in a list. |
|
327 | 327 | |
|
328 | 328 | -posix (True): whether to split the input line in POSIX mode or not, |
|
329 | 329 | as per the conventions outlined in the shlex module from the |
|
330 | 330 | standard library.""" |
|
331 | 331 | |
|
332 | 332 | # inject default options at the beginning of the input line |
|
333 | 333 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
334 | 334 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
335 | 335 | |
|
336 | 336 | mode = kw.get('mode','string') |
|
337 | 337 | if mode not in ['string','list']: |
|
338 | 338 | raise ValueError,'incorrect mode given: %s' % mode |
|
339 | 339 | # Get options |
|
340 | 340 | list_all = kw.get('list_all',0) |
|
341 | 341 | posix = kw.get('posix',True) |
|
342 | 342 | |
|
343 | 343 | # Check if we have more than one argument to warrant extra processing: |
|
344 | 344 | odict = {} # Dictionary with options |
|
345 | 345 | args = arg_str.split() |
|
346 | 346 | if len(args) >= 1: |
|
347 | 347 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
348 | 348 | # need to look for options |
|
349 | 349 | argv = arg_split(arg_str,posix) |
|
350 | 350 | # Do regular option processing |
|
351 | 351 | try: |
|
352 | 352 | opts,args = getopt(argv,opt_str,*long_opts) |
|
353 | 353 | except GetoptError,e: |
|
354 | 354 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
355 | 355 | " ".join(long_opts))) |
|
356 | 356 | for o,a in opts: |
|
357 | 357 | if o.startswith('--'): |
|
358 | 358 | o = o[2:] |
|
359 | 359 | else: |
|
360 | 360 | o = o[1:] |
|
361 | 361 | try: |
|
362 | 362 | odict[o].append(a) |
|
363 | 363 | except AttributeError: |
|
364 | 364 | odict[o] = [odict[o],a] |
|
365 | 365 | except KeyError: |
|
366 | 366 | if list_all: |
|
367 | 367 | odict[o] = [a] |
|
368 | 368 | else: |
|
369 | 369 | odict[o] = a |
|
370 | 370 | |
|
371 | 371 | # Prepare opts,args for return |
|
372 | 372 | opts = Struct(odict) |
|
373 | 373 | if mode == 'string': |
|
374 | 374 | args = ' '.join(args) |
|
375 | 375 | |
|
376 | 376 | return opts,args |
|
377 | 377 | |
|
378 | 378 | #...................................................................... |
|
379 | 379 | # And now the actual magic functions |
|
380 | 380 | |
|
381 | 381 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
382 | 382 | def magic_lsmagic(self, parameter_s = ''): |
|
383 | 383 | """List currently available magic functions.""" |
|
384 | 384 | mesc = self.shell.ESC_MAGIC |
|
385 | 385 | print 'Available magic functions:\n'+mesc+\ |
|
386 | 386 | (' '+mesc).join(self.lsmagic()) |
|
387 | 387 | print '\n' + Magic.auto_status[self.shell.rc.automagic] |
|
388 | 388 | return None |
|
389 | 389 | |
|
390 | 390 | def magic_magic(self, parameter_s = ''): |
|
391 | 391 | """Print information about the magic function system. |
|
392 | 392 | |
|
393 | 393 | Supported formats: -latex, -brief, -rest |
|
394 | 394 | """ |
|
395 | 395 | |
|
396 | 396 | mode = '' |
|
397 | 397 | try: |
|
398 | 398 | if parameter_s.split()[0] == '-latex': |
|
399 | 399 | mode = 'latex' |
|
400 | 400 | if parameter_s.split()[0] == '-brief': |
|
401 | 401 | mode = 'brief' |
|
402 | 402 | if parameter_s.split()[0] == '-rest': |
|
403 | 403 | mode = 'rest' |
|
404 | 404 | rest_docs = [] |
|
405 | 405 | except: |
|
406 | 406 | pass |
|
407 | 407 | |
|
408 | 408 | magic_docs = [] |
|
409 | 409 | for fname in self.lsmagic(): |
|
410 | 410 | mname = 'magic_' + fname |
|
411 | 411 | for space in (Magic,self,self.__class__): |
|
412 | 412 | try: |
|
413 | 413 | fn = space.__dict__[mname] |
|
414 | 414 | except KeyError: |
|
415 | 415 | pass |
|
416 | 416 | else: |
|
417 | 417 | break |
|
418 | 418 | if mode == 'brief': |
|
419 | 419 | # only first line |
|
420 | 420 | if fn.__doc__: |
|
421 | 421 | fndoc = fn.__doc__.split('\n',1)[0] |
|
422 | 422 | else: |
|
423 | 423 | fndoc = 'No documentation' |
|
424 | 424 | else: |
|
425 | 425 | fndoc = fn.__doc__.rstrip() |
|
426 | 426 | |
|
427 | 427 | if mode == 'rest': |
|
428 | 428 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC, |
|
429 | 429 | fname,fndoc)) |
|
430 | 430 | |
|
431 | 431 | else: |
|
432 | 432 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, |
|
433 | 433 | fname,fndoc)) |
|
434 | 434 | |
|
435 | 435 | magic_docs = ''.join(magic_docs) |
|
436 | 436 | |
|
437 | 437 | if mode == 'rest': |
|
438 | 438 | return "".join(rest_docs) |
|
439 | 439 | |
|
440 | 440 | if mode == 'latex': |
|
441 | 441 | print self.format_latex(magic_docs) |
|
442 | 442 | return |
|
443 | 443 | else: |
|
444 | 444 | magic_docs = self.format_screen(magic_docs) |
|
445 | 445 | if mode == 'brief': |
|
446 | 446 | return magic_docs |
|
447 | 447 | |
|
448 | 448 | outmsg = """ |
|
449 | 449 | IPython's 'magic' functions |
|
450 | 450 | =========================== |
|
451 | 451 | |
|
452 | 452 | The magic function system provides a series of functions which allow you to |
|
453 | 453 | control the behavior of IPython itself, plus a lot of system-type |
|
454 | 454 | features. All these functions are prefixed with a % character, but parameters |
|
455 | 455 | are given without parentheses or quotes. |
|
456 | 456 | |
|
457 | 457 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
458 | 458 | %automagic function), you don't need to type in the % explicitly. By default, |
|
459 | 459 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
460 | 460 | |
|
461 | 461 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
462 | 462 | to 'mydir', if it exists. |
|
463 | 463 | |
|
464 | 464 | You can define your own magic functions to extend the system. See the supplied |
|
465 | 465 | ipythonrc and example-magic.py files for details (in your ipython |
|
466 | 466 | configuration directory, typically $HOME/.ipython/). |
|
467 | 467 | |
|
468 | 468 | You can also define your own aliased names for magic functions. In your |
|
469 | 469 | ipythonrc file, placing a line like: |
|
470 | 470 | |
|
471 | 471 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
472 | 472 | |
|
473 | 473 | will define %pf as a new name for %profile. |
|
474 | 474 | |
|
475 | 475 | You can also call magics in code using the ipmagic() function, which IPython |
|
476 | 476 | automatically adds to the builtin namespace. Type 'ipmagic?' for details. |
|
477 | 477 | |
|
478 | 478 | For a list of the available magic functions, use %lsmagic. For a description |
|
479 | 479 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
480 | 480 | |
|
481 | 481 | Currently the magic system has the following functions:\n""" |
|
482 | 482 | |
|
483 | 483 | mesc = self.shell.ESC_MAGIC |
|
484 | 484 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
485 | 485 | "\n\n%s%s\n\n%s" % (outmsg, |
|
486 | 486 | magic_docs,mesc,mesc, |
|
487 | 487 | (' '+mesc).join(self.lsmagic()), |
|
488 | 488 | Magic.auto_status[self.shell.rc.automagic] ) ) |
|
489 | 489 | |
|
490 | 490 | page(outmsg,screen_lines=self.shell.rc.screen_length) |
|
491 | 491 | |
|
492 | 492 | |
|
493 | 493 | def magic_autoindent(self, parameter_s = ''): |
|
494 | 494 | """Toggle autoindent on/off (if available).""" |
|
495 | 495 | |
|
496 | 496 | self.shell.set_autoindent() |
|
497 | 497 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
498 | 498 | |
|
499 | 499 | |
|
500 | 500 | def magic_automagic(self, parameter_s = ''): |
|
501 | 501 | """Make magic functions callable without having to type the initial %. |
|
502 | 502 | |
|
503 | 503 | Without argumentsl toggles on/off (when off, you must call it as |
|
504 | 504 | %automagic, of course). With arguments it sets the value, and you can |
|
505 | 505 | use any of (case insensitive): |
|
506 | 506 | |
|
507 | 507 | - on,1,True: to activate |
|
508 | 508 | |
|
509 | 509 | - off,0,False: to deactivate. |
|
510 | 510 | |
|
511 | 511 | Note that magic functions have lowest priority, so if there's a |
|
512 | 512 | variable whose name collides with that of a magic fn, automagic won't |
|
513 | 513 | work for that function (you get the variable instead). However, if you |
|
514 | 514 | delete the variable (del var), the previously shadowed magic function |
|
515 | 515 | becomes visible to automagic again.""" |
|
516 | 516 | |
|
517 | 517 | rc = self.shell.rc |
|
518 | 518 | arg = parameter_s.lower() |
|
519 | 519 | if parameter_s in ('on','1','true'): |
|
520 | 520 | rc.automagic = True |
|
521 | 521 | elif parameter_s in ('off','0','false'): |
|
522 | 522 | rc.automagic = False |
|
523 | 523 | else: |
|
524 | 524 | rc.automagic = not rc.automagic |
|
525 | 525 | print '\n' + Magic.auto_status[rc.automagic] |
|
526 | 526 | |
|
527 | 527 | @testdec.skip_doctest |
|
528 | 528 | def magic_autocall(self, parameter_s = ''): |
|
529 | 529 | """Make functions callable without having to type parentheses. |
|
530 | 530 | |
|
531 | 531 | Usage: |
|
532 | 532 | |
|
533 | 533 | %autocall [mode] |
|
534 | 534 | |
|
535 | 535 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
536 | 536 | value is toggled on and off (remembering the previous state). |
|
537 | 537 | |
|
538 | 538 | In more detail, these values mean: |
|
539 | 539 | |
|
540 | 540 | 0 -> fully disabled |
|
541 | 541 | |
|
542 | 542 | 1 -> active, but do not apply if there are no arguments on the line. |
|
543 | 543 | |
|
544 | 544 | In this mode, you get: |
|
545 | 545 | |
|
546 | 546 | In [1]: callable |
|
547 | 547 | Out[1]: <built-in function callable> |
|
548 | 548 | |
|
549 | 549 | In [2]: callable 'hello' |
|
550 | 550 | ------> callable('hello') |
|
551 | 551 | Out[2]: False |
|
552 | 552 | |
|
553 | 553 | 2 -> Active always. Even if no arguments are present, the callable |
|
554 | 554 | object is called: |
|
555 | 555 | |
|
556 | 556 | In [2]: float |
|
557 | 557 | ------> float() |
|
558 | 558 | Out[2]: 0.0 |
|
559 | 559 | |
|
560 | 560 | Note that even with autocall off, you can still use '/' at the start of |
|
561 | 561 | a line to treat the first argument on the command line as a function |
|
562 | 562 | and add parentheses to it: |
|
563 | 563 | |
|
564 | 564 | In [8]: /str 43 |
|
565 | 565 | ------> str(43) |
|
566 | 566 | Out[8]: '43' |
|
567 | 567 | |
|
568 | 568 | # all-random (note for auto-testing) |
|
569 | 569 | """ |
|
570 | 570 | |
|
571 | 571 | rc = self.shell.rc |
|
572 | 572 | |
|
573 | 573 | if parameter_s: |
|
574 | 574 | arg = int(parameter_s) |
|
575 | 575 | else: |
|
576 | 576 | arg = 'toggle' |
|
577 | 577 | |
|
578 | 578 | if not arg in (0,1,2,'toggle'): |
|
579 | 579 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
580 | 580 | return |
|
581 | 581 | |
|
582 | 582 | if arg in (0,1,2): |
|
583 | 583 | rc.autocall = arg |
|
584 | 584 | else: # toggle |
|
585 | 585 | if rc.autocall: |
|
586 | 586 | self._magic_state.autocall_save = rc.autocall |
|
587 | 587 | rc.autocall = 0 |
|
588 | 588 | else: |
|
589 | 589 | try: |
|
590 | 590 | rc.autocall = self._magic_state.autocall_save |
|
591 | 591 | except AttributeError: |
|
592 | 592 | rc.autocall = self._magic_state.autocall_save = 1 |
|
593 | 593 | |
|
594 | 594 | print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall] |
|
595 | 595 | |
|
596 | 596 | def magic_system_verbose(self, parameter_s = ''): |
|
597 | 597 | """Set verbose printing of system calls. |
|
598 | 598 | |
|
599 | 599 | If called without an argument, act as a toggle""" |
|
600 | 600 | |
|
601 | 601 | if parameter_s: |
|
602 | 602 | val = bool(eval(parameter_s)) |
|
603 | 603 | else: |
|
604 | 604 | val = None |
|
605 | 605 | |
|
606 | 606 | self.shell.rc_set_toggle('system_verbose',val) |
|
607 | 607 | print "System verbose printing is:",\ |
|
608 | 608 | ['OFF','ON'][self.shell.rc.system_verbose] |
|
609 | 609 | |
|
610 | 610 | |
|
611 | 611 | def magic_page(self, parameter_s=''): |
|
612 | 612 | """Pretty print the object and display it through a pager. |
|
613 | 613 | |
|
614 | 614 | %page [options] OBJECT |
|
615 | 615 | |
|
616 | 616 | If no object is given, use _ (last output). |
|
617 | 617 | |
|
618 | 618 | Options: |
|
619 | 619 | |
|
620 | 620 | -r: page str(object), don't pretty-print it.""" |
|
621 | 621 | |
|
622 | 622 | # After a function contributed by Olivier Aubert, slightly modified. |
|
623 | 623 | |
|
624 | 624 | # Process options/args |
|
625 | 625 | opts,args = self.parse_options(parameter_s,'r') |
|
626 | 626 | raw = 'r' in opts |
|
627 | 627 | |
|
628 | 628 | oname = args and args or '_' |
|
629 | 629 | info = self._ofind(oname) |
|
630 | 630 | if info['found']: |
|
631 | 631 | txt = (raw and str or pformat)( info['obj'] ) |
|
632 | 632 | page(txt) |
|
633 | 633 | else: |
|
634 | 634 | print 'Object `%s` not found' % oname |
|
635 | 635 | |
|
636 | 636 | def magic_profile(self, parameter_s=''): |
|
637 | 637 | """Print your currently active IPyhton profile.""" |
|
638 | 638 | if self.shell.rc.profile: |
|
639 | 639 | printpl('Current IPython profile: $self.shell.rc.profile.') |
|
640 | 640 | else: |
|
641 | 641 | print 'No profile active.' |
|
642 | 642 | |
|
643 | 643 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
644 | 644 | """Provide detailed information about an object. |
|
645 | 645 | |
|
646 | 646 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
647 | 647 | |
|
648 | 648 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
649 | 649 | |
|
650 | 650 | |
|
651 | 651 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
652 | 652 | detail_level = 0 |
|
653 | 653 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
654 | 654 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
655 | 655 | pinfo,qmark1,oname,qmark2 = \ |
|
656 | 656 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
657 | 657 | if pinfo or qmark1 or qmark2: |
|
658 | 658 | detail_level = 1 |
|
659 | 659 | if "*" in oname: |
|
660 | 660 | self.magic_psearch(oname) |
|
661 | 661 | else: |
|
662 | 662 | self._inspect('pinfo', oname, detail_level=detail_level, |
|
663 | 663 | namespaces=namespaces) |
|
664 | 664 | |
|
665 | 665 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
666 | 666 | """Print the definition header for any callable object. |
|
667 | 667 | |
|
668 | 668 | If the object is a class, print the constructor information.""" |
|
669 | 669 | self._inspect('pdef',parameter_s, namespaces) |
|
670 | 670 | |
|
671 | 671 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
672 | 672 | """Print the docstring for an object. |
|
673 | 673 | |
|
674 | 674 | If the given object is a class, it will print both the class and the |
|
675 | 675 | constructor docstrings.""" |
|
676 | 676 | self._inspect('pdoc',parameter_s, namespaces) |
|
677 | 677 | |
|
678 | 678 | def magic_psource(self, parameter_s='', namespaces=None): |
|
679 | 679 | """Print (or run through pager) the source code for an object.""" |
|
680 | 680 | self._inspect('psource',parameter_s, namespaces) |
|
681 | 681 | |
|
682 | 682 | def magic_pfile(self, parameter_s=''): |
|
683 | 683 | """Print (or run through pager) the file where an object is defined. |
|
684 | 684 | |
|
685 | 685 | The file opens at the line where the object definition begins. IPython |
|
686 | 686 | will honor the environment variable PAGER if set, and otherwise will |
|
687 | 687 | do its best to print the file in a convenient form. |
|
688 | 688 | |
|
689 | 689 | If the given argument is not an object currently defined, IPython will |
|
690 | 690 | try to interpret it as a filename (automatically adding a .py extension |
|
691 | 691 | if needed). You can thus use %pfile as a syntax highlighting code |
|
692 | 692 | viewer.""" |
|
693 | 693 | |
|
694 | 694 | # first interpret argument as an object name |
|
695 | 695 | out = self._inspect('pfile',parameter_s) |
|
696 | 696 | # if not, try the input as a filename |
|
697 | 697 | if out == 'not found': |
|
698 | 698 | try: |
|
699 | 699 | filename = get_py_filename(parameter_s) |
|
700 | 700 | except IOError,msg: |
|
701 | 701 | print msg |
|
702 | 702 | return |
|
703 | 703 | page(self.shell.inspector.format(file(filename).read())) |
|
704 | 704 | |
|
705 | 705 | def _inspect(self,meth,oname,namespaces=None,**kw): |
|
706 | 706 | """Generic interface to the inspector system. |
|
707 | 707 | |
|
708 | 708 | This function is meant to be called by pdef, pdoc & friends.""" |
|
709 | 709 | |
|
710 | 710 | #oname = oname.strip() |
|
711 | 711 | #print '1- oname: <%r>' % oname # dbg |
|
712 | 712 | try: |
|
713 | 713 | oname = oname.strip().encode('ascii') |
|
714 | 714 | #print '2- oname: <%r>' % oname # dbg |
|
715 | 715 | except UnicodeEncodeError: |
|
716 | 716 | print 'Python identifiers can only contain ascii characters.' |
|
717 | 717 | return 'not found' |
|
718 | 718 | |
|
719 | 719 | info = Struct(self._ofind(oname, namespaces)) |
|
720 | 720 | |
|
721 | 721 | if info.found: |
|
722 | 722 | try: |
|
723 | 723 | IPython.generics.inspect_object(info.obj) |
|
724 | 724 | return |
|
725 | 725 | except IPython.ipapi.TryNext: |
|
726 | 726 | pass |
|
727 | 727 | # Get the docstring of the class property if it exists. |
|
728 | 728 | path = oname.split('.') |
|
729 | 729 | root = '.'.join(path[:-1]) |
|
730 | 730 | if info.parent is not None: |
|
731 | 731 | try: |
|
732 | 732 | target = getattr(info.parent, '__class__') |
|
733 | 733 | # The object belongs to a class instance. |
|
734 | 734 | try: |
|
735 | 735 | target = getattr(target, path[-1]) |
|
736 | 736 | # The class defines the object. |
|
737 | 737 | if isinstance(target, property): |
|
738 | 738 | oname = root + '.__class__.' + path[-1] |
|
739 | 739 | info = Struct(self._ofind(oname)) |
|
740 | 740 | except AttributeError: pass |
|
741 | 741 | except AttributeError: pass |
|
742 | 742 | |
|
743 | 743 | pmethod = getattr(self.shell.inspector,meth) |
|
744 | 744 | formatter = info.ismagic and self.format_screen or None |
|
745 | 745 | if meth == 'pdoc': |
|
746 | 746 | pmethod(info.obj,oname,formatter) |
|
747 | 747 | elif meth == 'pinfo': |
|
748 | 748 | pmethod(info.obj,oname,formatter,info,**kw) |
|
749 | 749 | else: |
|
750 | 750 | pmethod(info.obj,oname) |
|
751 | 751 | else: |
|
752 | 752 | print 'Object `%s` not found.' % oname |
|
753 | 753 | return 'not found' # so callers can take other action |
|
754 | 754 | |
|
755 | 755 | def magic_psearch(self, parameter_s=''): |
|
756 | 756 | """Search for object in namespaces by wildcard. |
|
757 | 757 | |
|
758 | 758 | %psearch [options] PATTERN [OBJECT TYPE] |
|
759 | 759 | |
|
760 | 760 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
761 | 761 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
762 | 762 | rest of the command line must be unchanged (options come first), so |
|
763 | 763 | for example the following forms are equivalent |
|
764 | 764 | |
|
765 | 765 | %psearch -i a* function |
|
766 | 766 | -i a* function? |
|
767 | 767 | ?-i a* function |
|
768 | 768 | |
|
769 | 769 | Arguments: |
|
770 | 770 | |
|
771 | 771 | PATTERN |
|
772 | 772 | |
|
773 | 773 | where PATTERN is a string containing * as a wildcard similar to its |
|
774 | 774 | use in a shell. The pattern is matched in all namespaces on the |
|
775 | 775 | search path. By default objects starting with a single _ are not |
|
776 | 776 | matched, many IPython generated objects have a single |
|
777 | 777 | underscore. The default is case insensitive matching. Matching is |
|
778 | 778 | also done on the attributes of objects and not only on the objects |
|
779 | 779 | in a module. |
|
780 | 780 | |
|
781 | 781 | [OBJECT TYPE] |
|
782 | 782 | |
|
783 | 783 | Is the name of a python type from the types module. The name is |
|
784 | 784 | given in lowercase without the ending type, ex. StringType is |
|
785 | 785 | written string. By adding a type here only objects matching the |
|
786 | 786 | given type are matched. Using all here makes the pattern match all |
|
787 | 787 | types (this is the default). |
|
788 | 788 | |
|
789 | 789 | Options: |
|
790 | 790 | |
|
791 | 791 | -a: makes the pattern match even objects whose names start with a |
|
792 | 792 | single underscore. These names are normally ommitted from the |
|
793 | 793 | search. |
|
794 | 794 | |
|
795 | 795 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
796 | 796 | these options is given, the default is read from your ipythonrc |
|
797 | 797 | file. The option name which sets this value is |
|
798 | 798 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
799 | 799 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
800 | 800 | search. |
|
801 | 801 | |
|
802 | 802 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
803 | 803 | specifiy can be searched in any of the following namespaces: |
|
804 | 804 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
805 | 805 | 'builtin' and 'user' are the search defaults. Note that you should |
|
806 | 806 | not use quotes when specifying namespaces. |
|
807 | 807 | |
|
808 | 808 | 'Builtin' contains the python module builtin, 'user' contains all |
|
809 | 809 | user data, 'alias' only contain the shell aliases and no python |
|
810 | 810 | objects, 'internal' contains objects used by IPython. The |
|
811 | 811 | 'user_global' namespace is only used by embedded IPython instances, |
|
812 | 812 | and it contains module-level globals. You can add namespaces to the |
|
813 | 813 | search with -s or exclude them with -e (these options can be given |
|
814 | 814 | more than once). |
|
815 | 815 | |
|
816 | 816 | Examples: |
|
817 | 817 | |
|
818 | 818 | %psearch a* -> objects beginning with an a |
|
819 | 819 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
820 | 820 | %psearch a* function -> all functions beginning with an a |
|
821 | 821 | %psearch re.e* -> objects beginning with an e in module re |
|
822 | 822 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
823 | 823 | %psearch r*.* string -> all strings in modules beginning with r |
|
824 | 824 | |
|
825 | 825 | Case sensitve search: |
|
826 | 826 | |
|
827 | 827 | %psearch -c a* list all object beginning with lower case a |
|
828 | 828 | |
|
829 | 829 | Show objects beginning with a single _: |
|
830 | 830 | |
|
831 | 831 | %psearch -a _* list objects beginning with a single underscore""" |
|
832 | 832 | try: |
|
833 | 833 | parameter_s = parameter_s.encode('ascii') |
|
834 | 834 | except UnicodeEncodeError: |
|
835 | 835 | print 'Python identifiers can only contain ascii characters.' |
|
836 | 836 | return |
|
837 | 837 | |
|
838 | 838 | # default namespaces to be searched |
|
839 | 839 | def_search = ['user','builtin'] |
|
840 | 840 | |
|
841 | 841 | # Process options/args |
|
842 | 842 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
843 | 843 | opt = opts.get |
|
844 | 844 | shell = self.shell |
|
845 | 845 | psearch = shell.inspector.psearch |
|
846 | 846 | |
|
847 | 847 | # select case options |
|
848 | 848 | if opts.has_key('i'): |
|
849 | 849 | ignore_case = True |
|
850 | 850 | elif opts.has_key('c'): |
|
851 | 851 | ignore_case = False |
|
852 | 852 | else: |
|
853 | 853 | ignore_case = not shell.rc.wildcards_case_sensitive |
|
854 | 854 | |
|
855 | 855 | # Build list of namespaces to search from user options |
|
856 | 856 | def_search.extend(opt('s',[])) |
|
857 | 857 | ns_exclude = ns_exclude=opt('e',[]) |
|
858 | 858 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
859 | 859 | |
|
860 | 860 | # Call the actual search |
|
861 | 861 | try: |
|
862 | 862 | psearch(args,shell.ns_table,ns_search, |
|
863 | 863 | show_all=opt('a'),ignore_case=ignore_case) |
|
864 | 864 | except: |
|
865 | 865 | shell.showtraceback() |
|
866 | 866 | |
|
867 | 867 | def magic_who_ls(self, parameter_s=''): |
|
868 | 868 | """Return a sorted list of all interactive variables. |
|
869 | 869 | |
|
870 | 870 | If arguments are given, only variables of types matching these |
|
871 | 871 | arguments are returned.""" |
|
872 | 872 | |
|
873 | 873 | user_ns = self.shell.user_ns |
|
874 | 874 | internal_ns = self.shell.internal_ns |
|
875 | 875 | user_config_ns = self.shell.user_config_ns |
|
876 | 876 | out = [] |
|
877 | 877 | typelist = parameter_s.split() |
|
878 | 878 | |
|
879 | 879 | for i in user_ns: |
|
880 | 880 | if not (i.startswith('_') or i.startswith('_i')) \ |
|
881 | 881 | and not (i in internal_ns or i in user_config_ns): |
|
882 | 882 | if typelist: |
|
883 | 883 | if type(user_ns[i]).__name__ in typelist: |
|
884 | 884 | out.append(i) |
|
885 | 885 | else: |
|
886 | 886 | out.append(i) |
|
887 | 887 | out.sort() |
|
888 | 888 | return out |
|
889 | 889 | |
|
890 | 890 | def magic_who(self, parameter_s=''): |
|
891 | 891 | """Print all interactive variables, with some minimal formatting. |
|
892 | 892 | |
|
893 | 893 | If any arguments are given, only variables whose type matches one of |
|
894 | 894 | these are printed. For example: |
|
895 | 895 | |
|
896 | 896 | %who function str |
|
897 | 897 | |
|
898 | 898 | will only list functions and strings, excluding all other types of |
|
899 | 899 | variables. To find the proper type names, simply use type(var) at a |
|
900 | 900 | command line to see how python prints type names. For example: |
|
901 | 901 | |
|
902 | 902 | In [1]: type('hello')\\ |
|
903 | 903 | Out[1]: <type 'str'> |
|
904 | 904 | |
|
905 | 905 | indicates that the type name for strings is 'str'. |
|
906 | 906 | |
|
907 | 907 | %who always excludes executed names loaded through your configuration |
|
908 | 908 | file and things which are internal to IPython. |
|
909 | 909 | |
|
910 | 910 | This is deliberate, as typically you may load many modules and the |
|
911 | 911 | purpose of %who is to show you only what you've manually defined.""" |
|
912 | 912 | |
|
913 | 913 | varlist = self.magic_who_ls(parameter_s) |
|
914 | 914 | if not varlist: |
|
915 | 915 | if parameter_s: |
|
916 | 916 | print 'No variables match your requested type.' |
|
917 | 917 | else: |
|
918 | 918 | print 'Interactive namespace is empty.' |
|
919 | 919 | return |
|
920 | 920 | |
|
921 | 921 | # if we have variables, move on... |
|
922 | 922 | count = 0 |
|
923 | 923 | for i in varlist: |
|
924 | 924 | print i+'\t', |
|
925 | 925 | count += 1 |
|
926 | 926 | if count > 8: |
|
927 | 927 | count = 0 |
|
928 | 928 | |
|
929 | 929 | |
|
930 | 930 | |
|
931 | 931 | def magic_whos(self, parameter_s=''): |
|
932 | 932 | """Like %who, but gives some extra information about each variable. |
|
933 | 933 | |
|
934 | 934 | The same type filtering of %who can be applied here. |
|
935 | 935 | |
|
936 | 936 | For all variables, the type is printed. Additionally it prints: |
|
937 | 937 | |
|
938 | 938 | - For {},[],(): their length. |
|
939 | 939 | |
|
940 | 940 | - For numpy and Numeric arrays, a summary with shape, number of |
|
941 | 941 | elements, typecode and size in memory. |
|
942 | 942 | |
|
943 | 943 | - Everything else: a string representation, snipping their middle if |
|
944 | 944 | too long.""" |
|
945 | 945 | |
|
946 | 946 | varnames = self.magic_who_ls(parameter_s) |
|
947 | 947 | if not varnames: |
|
948 | 948 | if parameter_s: |
|
949 | 949 | print 'No variables match your requested type.' |
|
950 | 950 | else: |
|
951 | 951 | print 'Interactive namespace is empty.' |
|
952 | 952 | return |
|
953 | 953 | |
|
954 | 954 | # if we have variables, move on... |
|
955 | 955 | |
|
956 | 956 | # for these types, show len() instead of data: |
|
957 | 957 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
958 | 958 | |
|
959 | 959 | # for numpy/Numeric arrays, display summary info |
|
960 | 960 | try: |
|
961 | 961 | import numpy |
|
962 | 962 | except ImportError: |
|
963 | 963 | ndarray_type = None |
|
964 | 964 | else: |
|
965 | 965 | ndarray_type = numpy.ndarray.__name__ |
|
966 | 966 | try: |
|
967 | 967 | import Numeric |
|
968 | 968 | except ImportError: |
|
969 | 969 | array_type = None |
|
970 | 970 | else: |
|
971 | 971 | array_type = Numeric.ArrayType.__name__ |
|
972 | 972 | |
|
973 | 973 | # Find all variable names and types so we can figure out column sizes |
|
974 | 974 | def get_vars(i): |
|
975 | 975 | return self.shell.user_ns[i] |
|
976 | 976 | |
|
977 | 977 | # some types are well known and can be shorter |
|
978 | 978 | abbrevs = {'IPython.macro.Macro' : 'Macro'} |
|
979 | 979 | def type_name(v): |
|
980 | 980 | tn = type(v).__name__ |
|
981 | 981 | return abbrevs.get(tn,tn) |
|
982 | 982 | |
|
983 | 983 | varlist = map(get_vars,varnames) |
|
984 | 984 | |
|
985 | 985 | typelist = [] |
|
986 | 986 | for vv in varlist: |
|
987 | 987 | tt = type_name(vv) |
|
988 | 988 | |
|
989 | 989 | if tt=='instance': |
|
990 | 990 | typelist.append( abbrevs.get(str(vv.__class__), |
|
991 | 991 | str(vv.__class__))) |
|
992 | 992 | else: |
|
993 | 993 | typelist.append(tt) |
|
994 | 994 | |
|
995 | 995 | # column labels and # of spaces as separator |
|
996 | 996 | varlabel = 'Variable' |
|
997 | 997 | typelabel = 'Type' |
|
998 | 998 | datalabel = 'Data/Info' |
|
999 | 999 | colsep = 3 |
|
1000 | 1000 | # variable format strings |
|
1001 | 1001 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
1002 | 1002 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
1003 | 1003 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
1004 | 1004 | # find the size of the columns to format the output nicely |
|
1005 | 1005 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
1006 | 1006 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
1007 | 1007 | # table header |
|
1008 | 1008 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
1009 | 1009 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
1010 | 1010 | # and the table itself |
|
1011 | 1011 | kb = 1024 |
|
1012 | 1012 | Mb = 1048576 # kb**2 |
|
1013 | 1013 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
1014 | 1014 | print itpl(vformat), |
|
1015 | 1015 | if vtype in seq_types: |
|
1016 | 1016 | print len(var) |
|
1017 | 1017 | elif vtype in [array_type,ndarray_type]: |
|
1018 | 1018 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
1019 | 1019 | if vtype==ndarray_type: |
|
1020 | 1020 | # numpy |
|
1021 | 1021 | vsize = var.size |
|
1022 | 1022 | vbytes = vsize*var.itemsize |
|
1023 | 1023 | vdtype = var.dtype |
|
1024 | 1024 | else: |
|
1025 | 1025 | # Numeric |
|
1026 | 1026 | vsize = Numeric.size(var) |
|
1027 | 1027 | vbytes = vsize*var.itemsize() |
|
1028 | 1028 | vdtype = var.typecode() |
|
1029 | 1029 | |
|
1030 | 1030 | if vbytes < 100000: |
|
1031 | 1031 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
1032 | 1032 | else: |
|
1033 | 1033 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
1034 | 1034 | if vbytes < Mb: |
|
1035 | 1035 | print '(%s kb)' % (vbytes/kb,) |
|
1036 | 1036 | else: |
|
1037 | 1037 | print '(%s Mb)' % (vbytes/Mb,) |
|
1038 | 1038 | else: |
|
1039 | 1039 | try: |
|
1040 | 1040 | vstr = str(var) |
|
1041 | 1041 | except UnicodeEncodeError: |
|
1042 | 1042 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
1043 | 1043 | 'backslashreplace') |
|
1044 | 1044 | vstr = vstr.replace('\n','\\n') |
|
1045 | 1045 | if len(vstr) < 50: |
|
1046 | 1046 | print vstr |
|
1047 | 1047 | else: |
|
1048 | 1048 | printpl(vfmt_short) |
|
1049 | 1049 | |
|
1050 | 1050 | def magic_reset(self, parameter_s=''): |
|
1051 | 1051 | """Resets the namespace by removing all names defined by the user. |
|
1052 | 1052 | |
|
1053 | 1053 | Input/Output history are left around in case you need them.""" |
|
1054 | 1054 | |
|
1055 | 1055 | ans = self.shell.ask_yes_no( |
|
1056 | 1056 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1057 | 1057 | if not ans: |
|
1058 | 1058 | print 'Nothing done.' |
|
1059 | 1059 | return |
|
1060 | 1060 | user_ns = self.shell.user_ns |
|
1061 | 1061 | for i in self.magic_who_ls(): |
|
1062 | 1062 | del(user_ns[i]) |
|
1063 | 1063 | |
|
1064 | 1064 | # Also flush the private list of module references kept for script |
|
1065 | 1065 | # execution protection |
|
1066 | 1066 | self.shell._user_main_modules[:] = [] |
|
1067 | 1067 | |
|
1068 | 1068 | def magic_logstart(self,parameter_s=''): |
|
1069 | 1069 | """Start logging anywhere in a session. |
|
1070 | 1070 | |
|
1071 | 1071 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1072 | 1072 | |
|
1073 | 1073 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1074 | 1074 | current directory, in 'rotate' mode (see below). |
|
1075 | 1075 | |
|
1076 | 1076 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1077 | 1077 | history up to that point and then continues logging. |
|
1078 | 1078 | |
|
1079 | 1079 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1080 | 1080 | of (note that the modes are given unquoted):\\ |
|
1081 | 1081 | append: well, that says it.\\ |
|
1082 | 1082 | backup: rename (if exists) to name~ and start name.\\ |
|
1083 | 1083 | global: single logfile in your home dir, appended to.\\ |
|
1084 | 1084 | over : overwrite existing log.\\ |
|
1085 | 1085 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1086 | 1086 | |
|
1087 | 1087 | Options: |
|
1088 | 1088 | |
|
1089 | 1089 | -o: log also IPython's output. In this mode, all commands which |
|
1090 | 1090 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1091 | 1091 | their corresponding input line. The output lines are always |
|
1092 | 1092 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1093 | 1093 | Python code. |
|
1094 | 1094 | |
|
1095 | 1095 | Since this marker is always the same, filtering only the output from |
|
1096 | 1096 | a log is very easy, using for example a simple awk call: |
|
1097 | 1097 | |
|
1098 | 1098 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1099 | 1099 | |
|
1100 | 1100 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1101 | 1101 | input, so that user lines are logged in their final form, converted |
|
1102 | 1102 | into valid Python. For example, %Exit is logged as |
|
1103 | 1103 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1104 | 1104 | exactly as typed, with no transformations applied. |
|
1105 | 1105 | |
|
1106 | 1106 | -t: put timestamps before each input line logged (these are put in |
|
1107 | 1107 | comments).""" |
|
1108 | 1108 | |
|
1109 | 1109 | opts,par = self.parse_options(parameter_s,'ort') |
|
1110 | 1110 | log_output = 'o' in opts |
|
1111 | 1111 | log_raw_input = 'r' in opts |
|
1112 | 1112 | timestamp = 't' in opts |
|
1113 | 1113 | |
|
1114 | 1114 | rc = self.shell.rc |
|
1115 | 1115 | logger = self.shell.logger |
|
1116 | 1116 | |
|
1117 | 1117 | # if no args are given, the defaults set in the logger constructor by |
|
1118 | 1118 | # ipytohn remain valid |
|
1119 | 1119 | if par: |
|
1120 | 1120 | try: |
|
1121 | 1121 | logfname,logmode = par.split() |
|
1122 | 1122 | except: |
|
1123 | 1123 | logfname = par |
|
1124 | 1124 | logmode = 'backup' |
|
1125 | 1125 | else: |
|
1126 | 1126 | logfname = logger.logfname |
|
1127 | 1127 | logmode = logger.logmode |
|
1128 | 1128 | # put logfname into rc struct as if it had been called on the command |
|
1129 | 1129 | # line, so it ends up saved in the log header Save it in case we need |
|
1130 | 1130 | # to restore it... |
|
1131 | 1131 | old_logfile = rc.opts.get('logfile','') |
|
1132 | 1132 | if logfname: |
|
1133 | 1133 | logfname = os.path.expanduser(logfname) |
|
1134 | 1134 | rc.opts.logfile = logfname |
|
1135 | 1135 | loghead = self.shell.loghead_tpl % (rc.opts,rc.args) |
|
1136 | 1136 | try: |
|
1137 | 1137 | started = logger.logstart(logfname,loghead,logmode, |
|
1138 | 1138 | log_output,timestamp,log_raw_input) |
|
1139 | 1139 | except: |
|
1140 | 1140 | rc.opts.logfile = old_logfile |
|
1141 | 1141 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1142 | 1142 | else: |
|
1143 | 1143 | # log input history up to this point, optionally interleaving |
|
1144 | 1144 | # output if requested |
|
1145 | 1145 | |
|
1146 | 1146 | if timestamp: |
|
1147 | 1147 | # disable timestamping for the previous history, since we've |
|
1148 | 1148 | # lost those already (no time machine here). |
|
1149 | 1149 | logger.timestamp = False |
|
1150 | 1150 | |
|
1151 | 1151 | if log_raw_input: |
|
1152 | 1152 | input_hist = self.shell.input_hist_raw |
|
1153 | 1153 | else: |
|
1154 | 1154 | input_hist = self.shell.input_hist |
|
1155 | 1155 | |
|
1156 | 1156 | if log_output: |
|
1157 | 1157 | log_write = logger.log_write |
|
1158 | 1158 | output_hist = self.shell.output_hist |
|
1159 | 1159 | for n in range(1,len(input_hist)-1): |
|
1160 | 1160 | log_write(input_hist[n].rstrip()) |
|
1161 | 1161 | if n in output_hist: |
|
1162 | 1162 | log_write(repr(output_hist[n]),'output') |
|
1163 | 1163 | else: |
|
1164 | 1164 | logger.log_write(input_hist[1:]) |
|
1165 | 1165 | if timestamp: |
|
1166 | 1166 | # re-enable timestamping |
|
1167 | 1167 | logger.timestamp = True |
|
1168 | 1168 | |
|
1169 | 1169 | print ('Activating auto-logging. ' |
|
1170 | 1170 | 'Current session state plus future input saved.') |
|
1171 | 1171 | logger.logstate() |
|
1172 | 1172 | |
|
1173 | 1173 | def magic_logstop(self,parameter_s=''): |
|
1174 | 1174 | """Fully stop logging and close log file. |
|
1175 | 1175 | |
|
1176 | 1176 | In order to start logging again, a new %logstart call needs to be made, |
|
1177 | 1177 | possibly (though not necessarily) with a new filename, mode and other |
|
1178 | 1178 | options.""" |
|
1179 | 1179 | self.logger.logstop() |
|
1180 | 1180 | |
|
1181 | 1181 | def magic_logoff(self,parameter_s=''): |
|
1182 | 1182 | """Temporarily stop logging. |
|
1183 | 1183 | |
|
1184 | 1184 | You must have previously started logging.""" |
|
1185 | 1185 | self.shell.logger.switch_log(0) |
|
1186 | 1186 | |
|
1187 | 1187 | def magic_logon(self,parameter_s=''): |
|
1188 | 1188 | """Restart logging. |
|
1189 | 1189 | |
|
1190 | 1190 | This function is for restarting logging which you've temporarily |
|
1191 | 1191 | stopped with %logoff. For starting logging for the first time, you |
|
1192 | 1192 | must use the %logstart function, which allows you to specify an |
|
1193 | 1193 | optional log filename.""" |
|
1194 | 1194 | |
|
1195 | 1195 | self.shell.logger.switch_log(1) |
|
1196 | 1196 | |
|
1197 | 1197 | def magic_logstate(self,parameter_s=''): |
|
1198 | 1198 | """Print the status of the logging system.""" |
|
1199 | 1199 | |
|
1200 | 1200 | self.shell.logger.logstate() |
|
1201 | 1201 | |
|
1202 | 1202 | def magic_pdb(self, parameter_s=''): |
|
1203 | 1203 | """Control the automatic calling of the pdb interactive debugger. |
|
1204 | 1204 | |
|
1205 | 1205 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1206 | 1206 | argument it works as a toggle. |
|
1207 | 1207 | |
|
1208 | 1208 | When an exception is triggered, IPython can optionally call the |
|
1209 | 1209 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1210 | 1210 | this feature on and off. |
|
1211 | 1211 | |
|
1212 | 1212 | The initial state of this feature is set in your ipythonrc |
|
1213 | 1213 | configuration file (the variable is called 'pdb'). |
|
1214 | 1214 | |
|
1215 | 1215 | If you want to just activate the debugger AFTER an exception has fired, |
|
1216 | 1216 | without having to type '%pdb on' and rerunning your code, you can use |
|
1217 | 1217 | the %debug magic.""" |
|
1218 | 1218 | |
|
1219 | 1219 | par = parameter_s.strip().lower() |
|
1220 | 1220 | |
|
1221 | 1221 | if par: |
|
1222 | 1222 | try: |
|
1223 | 1223 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1224 | 1224 | except KeyError: |
|
1225 | 1225 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1226 | 1226 | 'or nothing for a toggle.') |
|
1227 | 1227 | return |
|
1228 | 1228 | else: |
|
1229 | 1229 | # toggle |
|
1230 | 1230 | new_pdb = not self.shell.call_pdb |
|
1231 | 1231 | |
|
1232 | 1232 | # set on the shell |
|
1233 | 1233 | self.shell.call_pdb = new_pdb |
|
1234 | 1234 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1235 | 1235 | |
|
1236 | 1236 | def magic_debug(self, parameter_s=''): |
|
1237 | 1237 | """Activate the interactive debugger in post-mortem mode. |
|
1238 | 1238 | |
|
1239 | 1239 | If an exception has just occurred, this lets you inspect its stack |
|
1240 | 1240 | frames interactively. Note that this will always work only on the last |
|
1241 | 1241 | traceback that occurred, so you must call this quickly after an |
|
1242 | 1242 | exception that you wish to inspect has fired, because if another one |
|
1243 | 1243 | occurs, it clobbers the previous one. |
|
1244 | 1244 | |
|
1245 | 1245 | If you want IPython to automatically do this on every exception, see |
|
1246 | 1246 | the %pdb magic for more details. |
|
1247 | 1247 | """ |
|
1248 | 1248 | |
|
1249 | 1249 | self.shell.debugger(force=True) |
|
1250 | 1250 | |
|
1251 | 1251 | @testdec.skip_doctest |
|
1252 | 1252 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1253 | 1253 | opts=None,arg_lst=None,prog_ns=None): |
|
1254 | 1254 | |
|
1255 | 1255 | """Run a statement through the python code profiler. |
|
1256 | 1256 | |
|
1257 | 1257 | Usage: |
|
1258 | 1258 | %prun [options] statement |
|
1259 | 1259 | |
|
1260 | 1260 | The given statement (which doesn't require quote marks) is run via the |
|
1261 | 1261 | python profiler in a manner similar to the profile.run() function. |
|
1262 | 1262 | Namespaces are internally managed to work correctly; profile.run |
|
1263 | 1263 | cannot be used in IPython because it makes certain assumptions about |
|
1264 | 1264 | namespaces which do not hold under IPython. |
|
1265 | 1265 | |
|
1266 | 1266 | Options: |
|
1267 | 1267 | |
|
1268 | 1268 | -l <limit>: you can place restrictions on what or how much of the |
|
1269 | 1269 | profile gets printed. The limit value can be: |
|
1270 | 1270 | |
|
1271 | 1271 | * A string: only information for function names containing this string |
|
1272 | 1272 | is printed. |
|
1273 | 1273 | |
|
1274 | 1274 | * An integer: only these many lines are printed. |
|
1275 | 1275 | |
|
1276 | 1276 | * A float (between 0 and 1): this fraction of the report is printed |
|
1277 | 1277 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1278 | 1278 | |
|
1279 | 1279 | You can combine several limits with repeated use of the option. For |
|
1280 | 1280 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1281 | 1281 | information about class constructors. |
|
1282 | 1282 | |
|
1283 | 1283 | -r: return the pstats.Stats object generated by the profiling. This |
|
1284 | 1284 | object has all the information about the profile in it, and you can |
|
1285 | 1285 | later use it for further analysis or in other functions. |
|
1286 | 1286 | |
|
1287 | 1287 | -s <key>: sort profile by given key. You can provide more than one key |
|
1288 | 1288 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1289 | 1289 | default sorting key is 'time'. |
|
1290 | 1290 | |
|
1291 | 1291 | The following is copied verbatim from the profile documentation |
|
1292 | 1292 | referenced below: |
|
1293 | 1293 | |
|
1294 | 1294 | When more than one key is provided, additional keys are used as |
|
1295 | 1295 | secondary criteria when the there is equality in all keys selected |
|
1296 | 1296 | before them. |
|
1297 | 1297 | |
|
1298 | 1298 | Abbreviations can be used for any key names, as long as the |
|
1299 | 1299 | abbreviation is unambiguous. The following are the keys currently |
|
1300 | 1300 | defined: |
|
1301 | 1301 | |
|
1302 | 1302 | Valid Arg Meaning |
|
1303 | 1303 | "calls" call count |
|
1304 | 1304 | "cumulative" cumulative time |
|
1305 | 1305 | "file" file name |
|
1306 | 1306 | "module" file name |
|
1307 | 1307 | "pcalls" primitive call count |
|
1308 | 1308 | "line" line number |
|
1309 | 1309 | "name" function name |
|
1310 | 1310 | "nfl" name/file/line |
|
1311 | 1311 | "stdname" standard name |
|
1312 | 1312 | "time" internal time |
|
1313 | 1313 | |
|
1314 | 1314 | Note that all sorts on statistics are in descending order (placing |
|
1315 | 1315 | most time consuming items first), where as name, file, and line number |
|
1316 | 1316 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1317 | 1317 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1318 | 1318 | sort of the name as printed, which means that the embedded line |
|
1319 | 1319 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1320 | 1320 | would (if the file names were the same) appear in the string order |
|
1321 | 1321 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1322 | 1322 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1323 | 1323 | sort_stats("name", "file", "line"). |
|
1324 | 1324 | |
|
1325 | 1325 | -T <filename>: save profile results as shown on screen to a text |
|
1326 | 1326 | file. The profile is still shown on screen. |
|
1327 | 1327 | |
|
1328 | 1328 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1329 | 1329 | filename. This data is in a format understod by the pstats module, and |
|
1330 | 1330 | is generated by a call to the dump_stats() method of profile |
|
1331 | 1331 | objects. The profile is still shown on screen. |
|
1332 | 1332 | |
|
1333 | 1333 | If you want to run complete programs under the profiler's control, use |
|
1334 | 1334 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1335 | 1335 | contains profiler specific options as described here. |
|
1336 | 1336 | |
|
1337 | 1337 | You can read the complete documentation for the profile module with:: |
|
1338 | 1338 | |
|
1339 | 1339 | In [1]: import profile; profile.help() |
|
1340 | 1340 | """ |
|
1341 | 1341 | |
|
1342 | 1342 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1343 | 1343 | # protect user quote marks |
|
1344 | 1344 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1345 | 1345 | |
|
1346 | 1346 | if user_mode: # regular user call |
|
1347 | 1347 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1348 | 1348 | list_all=1) |
|
1349 | 1349 | namespace = self.shell.user_ns |
|
1350 | 1350 | else: # called to run a program by %run -p |
|
1351 | 1351 | try: |
|
1352 | 1352 | filename = get_py_filename(arg_lst[0]) |
|
1353 | 1353 | except IOError,msg: |
|
1354 | 1354 | error(msg) |
|
1355 | 1355 | return |
|
1356 | 1356 | |
|
1357 | 1357 | arg_str = 'execfile(filename,prog_ns)' |
|
1358 | 1358 | namespace = locals() |
|
1359 | 1359 | |
|
1360 | 1360 | opts.merge(opts_def) |
|
1361 | 1361 | |
|
1362 | 1362 | prof = profile.Profile() |
|
1363 | 1363 | try: |
|
1364 | 1364 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1365 | 1365 | sys_exit = '' |
|
1366 | 1366 | except SystemExit: |
|
1367 | 1367 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1368 | 1368 | |
|
1369 | 1369 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1370 | 1370 | |
|
1371 | 1371 | lims = opts.l |
|
1372 | 1372 | if lims: |
|
1373 | 1373 | lims = [] # rebuild lims with ints/floats/strings |
|
1374 | 1374 | for lim in opts.l: |
|
1375 | 1375 | try: |
|
1376 | 1376 | lims.append(int(lim)) |
|
1377 | 1377 | except ValueError: |
|
1378 | 1378 | try: |
|
1379 | 1379 | lims.append(float(lim)) |
|
1380 | 1380 | except ValueError: |
|
1381 | 1381 | lims.append(lim) |
|
1382 | 1382 | |
|
1383 | 1383 | # Trap output. |
|
1384 | 1384 | stdout_trap = StringIO() |
|
1385 | 1385 | |
|
1386 | 1386 | if hasattr(stats,'stream'): |
|
1387 | 1387 | # In newer versions of python, the stats object has a 'stream' |
|
1388 | 1388 | # attribute to write into. |
|
1389 | 1389 | stats.stream = stdout_trap |
|
1390 | 1390 | stats.print_stats(*lims) |
|
1391 | 1391 | else: |
|
1392 | 1392 | # For older versions, we manually redirect stdout during printing |
|
1393 | 1393 | sys_stdout = sys.stdout |
|
1394 | 1394 | try: |
|
1395 | 1395 | sys.stdout = stdout_trap |
|
1396 | 1396 | stats.print_stats(*lims) |
|
1397 | 1397 | finally: |
|
1398 | 1398 | sys.stdout = sys_stdout |
|
1399 | 1399 | |
|
1400 | 1400 | output = stdout_trap.getvalue() |
|
1401 | 1401 | output = output.rstrip() |
|
1402 | 1402 | |
|
1403 | 1403 | page(output,screen_lines=self.shell.rc.screen_length) |
|
1404 | 1404 | print sys_exit, |
|
1405 | 1405 | |
|
1406 | 1406 | dump_file = opts.D[0] |
|
1407 | 1407 | text_file = opts.T[0] |
|
1408 | 1408 | if dump_file: |
|
1409 | 1409 | prof.dump_stats(dump_file) |
|
1410 | 1410 | print '\n*** Profile stats marshalled to file',\ |
|
1411 | 1411 | `dump_file`+'.',sys_exit |
|
1412 | 1412 | if text_file: |
|
1413 | 1413 | pfile = file(text_file,'w') |
|
1414 | 1414 | pfile.write(output) |
|
1415 | 1415 | pfile.close() |
|
1416 | 1416 | print '\n*** Profile printout saved to text file',\ |
|
1417 | 1417 | `text_file`+'.',sys_exit |
|
1418 | 1418 | |
|
1419 | 1419 | if opts.has_key('r'): |
|
1420 | 1420 | return stats |
|
1421 | 1421 | else: |
|
1422 | 1422 | return None |
|
1423 | 1423 | |
|
1424 | 1424 | @testdec.skip_doctest |
|
1425 | 1425 | def magic_run(self, parameter_s ='',runner=None): |
|
1426 | 1426 | """Run the named file inside IPython as a program. |
|
1427 | 1427 | |
|
1428 | 1428 | Usage:\\ |
|
1429 | 1429 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1430 | 1430 | |
|
1431 | 1431 | Parameters after the filename are passed as command-line arguments to |
|
1432 | 1432 | the program (put in sys.argv). Then, control returns to IPython's |
|
1433 | 1433 | prompt. |
|
1434 | 1434 | |
|
1435 | 1435 | This is similar to running at a system prompt:\\ |
|
1436 | 1436 | $ python file args\\ |
|
1437 | 1437 | but with the advantage of giving you IPython's tracebacks, and of |
|
1438 | 1438 | loading all variables into your interactive namespace for further use |
|
1439 | 1439 | (unless -p is used, see below). |
|
1440 | 1440 | |
|
1441 | 1441 | The file is executed in a namespace initially consisting only of |
|
1442 | 1442 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1443 | 1443 | sees its environment as if it were being run as a stand-alone program |
|
1444 | 1444 | (except for sharing global objects such as previously imported |
|
1445 | 1445 | modules). But after execution, the IPython interactive namespace gets |
|
1446 | 1446 | updated with all variables defined in the program (except for __name__ |
|
1447 | 1447 | and sys.argv). This allows for very convenient loading of code for |
|
1448 | 1448 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1449 | 1449 | |
|
1450 | 1450 | Options: |
|
1451 | 1451 | |
|
1452 | 1452 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1453 | 1453 | without extension (as python does under import). This allows running |
|
1454 | 1454 | scripts and reloading the definitions in them without calling code |
|
1455 | 1455 | protected by an ' if __name__ == "__main__" ' clause. |
|
1456 | 1456 | |
|
1457 | 1457 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1458 | 1458 | is useful if you are experimenting with code written in a text editor |
|
1459 | 1459 | which depends on variables defined interactively. |
|
1460 | 1460 | |
|
1461 | 1461 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1462 | 1462 | being run. This is particularly useful if IPython is being used to |
|
1463 | 1463 | run unittests, which always exit with a sys.exit() call. In such |
|
1464 | 1464 | cases you are interested in the output of the test results, not in |
|
1465 | 1465 | seeing a traceback of the unittest module. |
|
1466 | 1466 | |
|
1467 | 1467 | -t: print timing information at the end of the run. IPython will give |
|
1468 | 1468 | you an estimated CPU time consumption for your script, which under |
|
1469 | 1469 | Unix uses the resource module to avoid the wraparound problems of |
|
1470 | 1470 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1471 | 1471 | is also given (for Windows platforms this is reported as 0.0). |
|
1472 | 1472 | |
|
1473 | 1473 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1474 | 1474 | must be an integer indicating how many times you want the script to |
|
1475 | 1475 | run. The final timing report will include total and per run results. |
|
1476 | 1476 | |
|
1477 | 1477 | For example (testing the script uniq_stable.py): |
|
1478 | 1478 | |
|
1479 | 1479 | In [1]: run -t uniq_stable |
|
1480 | 1480 | |
|
1481 | 1481 | IPython CPU timings (estimated):\\ |
|
1482 | 1482 | User : 0.19597 s.\\ |
|
1483 | 1483 | System: 0.0 s.\\ |
|
1484 | 1484 | |
|
1485 | 1485 | In [2]: run -t -N5 uniq_stable |
|
1486 | 1486 | |
|
1487 | 1487 | IPython CPU timings (estimated):\\ |
|
1488 | 1488 | Total runs performed: 5\\ |
|
1489 | 1489 | Times : Total Per run\\ |
|
1490 | 1490 | User : 0.910862 s, 0.1821724 s.\\ |
|
1491 | 1491 | System: 0.0 s, 0.0 s. |
|
1492 | 1492 | |
|
1493 | 1493 | -d: run your program under the control of pdb, the Python debugger. |
|
1494 | 1494 | This allows you to execute your program step by step, watch variables, |
|
1495 | 1495 | etc. Internally, what IPython does is similar to calling: |
|
1496 | 1496 | |
|
1497 | 1497 | pdb.run('execfile("YOURFILENAME")') |
|
1498 | 1498 | |
|
1499 | 1499 | with a breakpoint set on line 1 of your file. You can change the line |
|
1500 | 1500 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1501 | 1501 | (where N must be an integer). For example: |
|
1502 | 1502 | |
|
1503 | 1503 | %run -d -b40 myscript |
|
1504 | 1504 | |
|
1505 | 1505 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1506 | 1506 | the first breakpoint must be set on a line which actually does |
|
1507 | 1507 | something (not a comment or docstring) for it to stop execution. |
|
1508 | 1508 | |
|
1509 | 1509 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1510 | 1510 | first enter 'c' (without qoutes) to start execution up to the first |
|
1511 | 1511 | breakpoint. |
|
1512 | 1512 | |
|
1513 | 1513 | Entering 'help' gives information about the use of the debugger. You |
|
1514 | 1514 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1515 | 1515 | at a prompt. |
|
1516 | 1516 | |
|
1517 | 1517 | -p: run program under the control of the Python profiler module (which |
|
1518 | 1518 | prints a detailed report of execution times, function calls, etc). |
|
1519 | 1519 | |
|
1520 | 1520 | You can pass other options after -p which affect the behavior of the |
|
1521 | 1521 | profiler itself. See the docs for %prun for details. |
|
1522 | 1522 | |
|
1523 | 1523 | In this mode, the program's variables do NOT propagate back to the |
|
1524 | 1524 | IPython interactive namespace (because they remain in the namespace |
|
1525 | 1525 | where the profiler executes them). |
|
1526 | 1526 | |
|
1527 | 1527 | Internally this triggers a call to %prun, see its documentation for |
|
1528 | 1528 | details on the options available specifically for profiling. |
|
1529 | 1529 | |
|
1530 | 1530 | There is one special usage for which the text above doesn't apply: |
|
1531 | 1531 | if the filename ends with .ipy, the file is run as ipython script, |
|
1532 | 1532 | just as if the commands were written on IPython prompt. |
|
1533 | 1533 | """ |
|
1534 | 1534 | |
|
1535 | 1535 | # get arguments and set sys.argv for program to be run. |
|
1536 | 1536 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1537 | 1537 | mode='list',list_all=1) |
|
1538 | 1538 | |
|
1539 | 1539 | try: |
|
1540 | 1540 | filename = get_py_filename(arg_lst[0]) |
|
1541 | 1541 | except IndexError: |
|
1542 | 1542 | warn('you must provide at least a filename.') |
|
1543 | 1543 | print '\n%run:\n',OInspect.getdoc(self.magic_run) |
|
1544 | 1544 | return |
|
1545 | 1545 | except IOError,msg: |
|
1546 | 1546 | error(msg) |
|
1547 | 1547 | return |
|
1548 | 1548 | |
|
1549 | 1549 | if filename.lower().endswith('.ipy'): |
|
1550 | 1550 | self.api.runlines(open(filename).read()) |
|
1551 | 1551 | return |
|
1552 | 1552 | |
|
1553 | 1553 | # Control the response to exit() calls made by the script being run |
|
1554 | 1554 | exit_ignore = opts.has_key('e') |
|
1555 | 1555 | |
|
1556 | 1556 | # Make sure that the running script gets a proper sys.argv as if it |
|
1557 | 1557 | # were run from a system shell. |
|
1558 | 1558 | save_argv = sys.argv # save it for later restoring |
|
1559 | 1559 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1560 | 1560 | |
|
1561 | 1561 | if opts.has_key('i'): |
|
1562 | 1562 | # Run in user's interactive namespace |
|
1563 | 1563 | prog_ns = self.shell.user_ns |
|
1564 | 1564 | __name__save = self.shell.user_ns['__name__'] |
|
1565 | 1565 | prog_ns['__name__'] = '__main__' |
|
1566 | 1566 | main_mod = FakeModule(prog_ns) |
|
1567 | 1567 | else: |
|
1568 | 1568 | # Run in a fresh, empty namespace |
|
1569 | 1569 | if opts.has_key('n'): |
|
1570 | 1570 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1571 | 1571 | else: |
|
1572 | 1572 | name = '__main__' |
|
1573 | 1573 | main_mod = FakeModule() |
|
1574 | 1574 | prog_ns = main_mod.__dict__ |
|
1575 | 1575 | prog_ns['__name__'] = name |
|
1576 | 1576 | # The shell MUST hold a reference to main_mod so after %run exits, |
|
1577 | 1577 | # the python deletion mechanism doesn't zero it out (leaving |
|
1578 | 1578 | # dangling references) |
|
1579 | 1579 | self.shell._user_main_modules.append(main_mod) |
|
1580 | 1580 | |
|
1581 | 1581 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1582 | 1582 | # set the __file__ global in the script's namespace |
|
1583 | 1583 | prog_ns['__file__'] = filename |
|
1584 | 1584 | |
|
1585 | 1585 | # pickle fix. See iplib for an explanation. But we need to make sure |
|
1586 | 1586 | # that, if we overwrite __main__, we replace it at the end |
|
1587 | 1587 | main_mod_name = prog_ns['__name__'] |
|
1588 | 1588 | |
|
1589 | 1589 | if main_mod_name == '__main__': |
|
1590 | 1590 | restore_main = sys.modules['__main__'] |
|
1591 | 1591 | else: |
|
1592 | 1592 | restore_main = False |
|
1593 | 1593 | |
|
1594 | 1594 | # This needs to be undone at the end to prevent holding references to |
|
1595 | 1595 | # every single object ever created. |
|
1596 | 1596 | sys.modules[main_mod_name] = main_mod |
|
1597 | 1597 | |
|
1598 | 1598 | stats = None |
|
1599 | 1599 | try: |
|
1600 | 1600 | self.shell.savehist() |
|
1601 | 1601 | |
|
1602 | 1602 | if opts.has_key('p'): |
|
1603 | 1603 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1604 | 1604 | else: |
|
1605 | 1605 | if opts.has_key('d'): |
|
1606 | 1606 | deb = Debugger.Pdb(self.shell.rc.colors) |
|
1607 | 1607 | # reset Breakpoint state, which is moronically kept |
|
1608 | 1608 | # in a class |
|
1609 | 1609 | bdb.Breakpoint.next = 1 |
|
1610 | 1610 | bdb.Breakpoint.bplist = {} |
|
1611 | 1611 | bdb.Breakpoint.bpbynumber = [None] |
|
1612 | 1612 | # Set an initial breakpoint to stop execution |
|
1613 | 1613 | maxtries = 10 |
|
1614 | 1614 | bp = int(opts.get('b',[1])[0]) |
|
1615 | 1615 | checkline = deb.checkline(filename,bp) |
|
1616 | 1616 | if not checkline: |
|
1617 | 1617 | for bp in range(bp+1,bp+maxtries+1): |
|
1618 | 1618 | if deb.checkline(filename,bp): |
|
1619 | 1619 | break |
|
1620 | 1620 | else: |
|
1621 | 1621 | msg = ("\nI failed to find a valid line to set " |
|
1622 | 1622 | "a breakpoint\n" |
|
1623 | 1623 | "after trying up to line: %s.\n" |
|
1624 | 1624 | "Please set a valid breakpoint manually " |
|
1625 | 1625 | "with the -b option." % bp) |
|
1626 | 1626 | error(msg) |
|
1627 | 1627 | return |
|
1628 | 1628 | # if we find a good linenumber, set the breakpoint |
|
1629 | 1629 | deb.do_break('%s:%s' % (filename,bp)) |
|
1630 | 1630 | # Start file run |
|
1631 | 1631 | print "NOTE: Enter 'c' at the", |
|
1632 | 1632 | print "%s prompt to start your script." % deb.prompt |
|
1633 | 1633 | try: |
|
1634 | 1634 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1635 | 1635 | |
|
1636 | 1636 | except: |
|
1637 | 1637 | etype, value, tb = sys.exc_info() |
|
1638 | 1638 | # Skip three frames in the traceback: the %run one, |
|
1639 | 1639 | # one inside bdb.py, and the command-line typed by the |
|
1640 | 1640 | # user (run by exec in pdb itself). |
|
1641 | 1641 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1642 | 1642 | else: |
|
1643 | 1643 | if runner is None: |
|
1644 | 1644 | runner = self.shell.safe_execfile |
|
1645 | 1645 | if opts.has_key('t'): |
|
1646 | 1646 | # timed execution |
|
1647 | 1647 | try: |
|
1648 | 1648 | nruns = int(opts['N'][0]) |
|
1649 | 1649 | if nruns < 1: |
|
1650 | 1650 | error('Number of runs must be >=1') |
|
1651 | 1651 | return |
|
1652 | 1652 | except (KeyError): |
|
1653 | 1653 | nruns = 1 |
|
1654 | 1654 | if nruns == 1: |
|
1655 | 1655 | t0 = clock2() |
|
1656 | 1656 | runner(filename,prog_ns,prog_ns, |
|
1657 | 1657 | exit_ignore=exit_ignore) |
|
1658 | 1658 | t1 = clock2() |
|
1659 | 1659 | t_usr = t1[0]-t0[0] |
|
1660 | 1660 | t_sys = t1[1]-t1[1] |
|
1661 | 1661 | print "\nIPython CPU timings (estimated):" |
|
1662 | 1662 | print " User : %10s s." % t_usr |
|
1663 | 1663 | print " System: %10s s." % t_sys |
|
1664 | 1664 | else: |
|
1665 | 1665 | runs = range(nruns) |
|
1666 | 1666 | t0 = clock2() |
|
1667 | 1667 | for nr in runs: |
|
1668 | 1668 | runner(filename,prog_ns,prog_ns, |
|
1669 | 1669 | exit_ignore=exit_ignore) |
|
1670 | 1670 | t1 = clock2() |
|
1671 | 1671 | t_usr = t1[0]-t0[0] |
|
1672 | 1672 | t_sys = t1[1]-t1[1] |
|
1673 | 1673 | print "\nIPython CPU timings (estimated):" |
|
1674 | 1674 | print "Total runs performed:",nruns |
|
1675 | 1675 | print " Times : %10s %10s" % ('Total','Per run') |
|
1676 | 1676 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1677 | 1677 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1678 | 1678 | |
|
1679 | 1679 | else: |
|
1680 | 1680 | # regular execution |
|
1681 | 1681 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1682 | 1682 | if opts.has_key('i'): |
|
1683 | 1683 | self.shell.user_ns['__name__'] = __name__save |
|
1684 | 1684 | else: |
|
1685 | 1685 | # update IPython interactive namespace |
|
1686 | 1686 | del prog_ns['__name__'] |
|
1687 | 1687 | self.shell.user_ns.update(prog_ns) |
|
1688 | 1688 | finally: |
|
1689 | 1689 | # Ensure key global structures are restored |
|
1690 | 1690 | sys.argv = save_argv |
|
1691 | 1691 | if restore_main: |
|
1692 | 1692 | sys.modules['__main__'] = restore_main |
|
1693 | 1693 | else: |
|
1694 | 1694 | # Remove from sys.modules the reference to main_mod we'd |
|
1695 | 1695 | # added. Otherwise it will trap references to objects |
|
1696 | 1696 | # contained therein. |
|
1697 | 1697 | del sys.modules[main_mod_name] |
|
1698 | 1698 | self.shell.reloadhist() |
|
1699 | 1699 | |
|
1700 | 1700 | return stats |
|
1701 | 1701 | |
|
1702 | 1702 | def magic_runlog(self, parameter_s =''): |
|
1703 | 1703 | """Run files as logs. |
|
1704 | 1704 | |
|
1705 | 1705 | Usage:\\ |
|
1706 | 1706 | %runlog file1 file2 ... |
|
1707 | 1707 | |
|
1708 | 1708 | Run the named files (treating them as log files) in sequence inside |
|
1709 | 1709 | the interpreter, and return to the prompt. This is much slower than |
|
1710 | 1710 | %run because each line is executed in a try/except block, but it |
|
1711 | 1711 | allows running files with syntax errors in them. |
|
1712 | 1712 | |
|
1713 | 1713 | Normally IPython will guess when a file is one of its own logfiles, so |
|
1714 | 1714 | you can typically use %run even for logs. This shorthand allows you to |
|
1715 | 1715 | force any file to be treated as a log file.""" |
|
1716 | 1716 | |
|
1717 | 1717 | for f in parameter_s.split(): |
|
1718 | 1718 | self.shell.safe_execfile(f,self.shell.user_ns, |
|
1719 | 1719 | self.shell.user_ns,islog=1) |
|
1720 | 1720 | |
|
1721 | 1721 | @testdec.skip_doctest |
|
1722 | 1722 | def magic_timeit(self, parameter_s =''): |
|
1723 | 1723 | """Time execution of a Python statement or expression |
|
1724 | 1724 | |
|
1725 | 1725 | Usage:\\ |
|
1726 | 1726 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1727 | 1727 | |
|
1728 | 1728 | Time execution of a Python statement or expression using the timeit |
|
1729 | 1729 | module. |
|
1730 | 1730 | |
|
1731 | 1731 | Options: |
|
1732 | 1732 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1733 | 1733 | is not given, a fitting value is chosen. |
|
1734 | 1734 | |
|
1735 | 1735 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1736 | 1736 | Default: 3 |
|
1737 | 1737 | |
|
1738 | 1738 | -t: use time.time to measure the time, which is the default on Unix. |
|
1739 | 1739 | This function measures wall time. |
|
1740 | 1740 | |
|
1741 | 1741 | -c: use time.clock to measure the time, which is the default on |
|
1742 | 1742 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1743 | 1743 | instead and returns the CPU user time. |
|
1744 | 1744 | |
|
1745 | 1745 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1746 | 1746 | Default: 3 |
|
1747 | 1747 | |
|
1748 | 1748 | |
|
1749 | 1749 | Examples: |
|
1750 | 1750 | |
|
1751 | 1751 | In [1]: %timeit pass |
|
1752 | 1752 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1753 | 1753 | |
|
1754 | 1754 | In [2]: u = None |
|
1755 | 1755 | |
|
1756 | 1756 | In [3]: %timeit u is None |
|
1757 | 1757 | 10000000 loops, best of 3: 184 ns per loop |
|
1758 | 1758 | |
|
1759 | 1759 | In [4]: %timeit -r 4 u == None |
|
1760 | 1760 | 1000000 loops, best of 4: 242 ns per loop |
|
1761 | 1761 | |
|
1762 | 1762 | In [5]: import time |
|
1763 | 1763 | |
|
1764 | 1764 | In [6]: %timeit -n1 time.sleep(2) |
|
1765 | 1765 | 1 loops, best of 3: 2 s per loop |
|
1766 | 1766 | |
|
1767 | 1767 | |
|
1768 | 1768 | The times reported by %timeit will be slightly higher than those |
|
1769 | 1769 | reported by the timeit.py script when variables are accessed. This is |
|
1770 | 1770 | due to the fact that %timeit executes the statement in the namespace |
|
1771 | 1771 | of the shell, compared with timeit.py, which uses a single setup |
|
1772 | 1772 | statement to import function or create variables. Generally, the bias |
|
1773 | 1773 | does not matter as long as results from timeit.py are not mixed with |
|
1774 | 1774 | those from %timeit.""" |
|
1775 | 1775 | |
|
1776 | 1776 | import timeit |
|
1777 | 1777 | import math |
|
1778 | 1778 | |
|
1779 | 1779 | units = [u"s", u"ms", u"\xb5s", u"ns"] |
|
1780 | 1780 | scaling = [1, 1e3, 1e6, 1e9] |
|
1781 | 1781 | |
|
1782 | 1782 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1783 | 1783 | posix=False) |
|
1784 | 1784 | if stmt == "": |
|
1785 | 1785 | return |
|
1786 | 1786 | timefunc = timeit.default_timer |
|
1787 | 1787 | number = int(getattr(opts, "n", 0)) |
|
1788 | 1788 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1789 | 1789 | precision = int(getattr(opts, "p", 3)) |
|
1790 | 1790 | if hasattr(opts, "t"): |
|
1791 | 1791 | timefunc = time.time |
|
1792 | 1792 | if hasattr(opts, "c"): |
|
1793 | 1793 | timefunc = clock |
|
1794 | 1794 | |
|
1795 | 1795 | timer = timeit.Timer(timer=timefunc) |
|
1796 | 1796 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1797 | 1797 | # but is there a better way to achieve that the code stmt has access |
|
1798 | 1798 | # to the shell namespace? |
|
1799 | 1799 | |
|
1800 | 1800 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1801 | 1801 | 'setup': "pass"} |
|
1802 | 1802 | # Track compilation time so it can be reported if too long |
|
1803 | 1803 | # Minimum time above which compilation time will be reported |
|
1804 | 1804 | tc_min = 0.1 |
|
1805 | 1805 | |
|
1806 | 1806 | t0 = clock() |
|
1807 | 1807 | code = compile(src, "<magic-timeit>", "exec") |
|
1808 | 1808 | tc = clock()-t0 |
|
1809 | 1809 | |
|
1810 | 1810 | ns = {} |
|
1811 | 1811 | exec code in self.shell.user_ns, ns |
|
1812 | 1812 | timer.inner = ns["inner"] |
|
1813 | 1813 | |
|
1814 | 1814 | if number == 0: |
|
1815 | 1815 | # determine number so that 0.2 <= total time < 2.0 |
|
1816 | 1816 | number = 1 |
|
1817 | 1817 | for i in range(1, 10): |
|
1818 | 1818 | number *= 10 |
|
1819 | 1819 | if timer.timeit(number) >= 0.2: |
|
1820 | 1820 | break |
|
1821 | 1821 | |
|
1822 | 1822 | best = min(timer.repeat(repeat, number)) / number |
|
1823 | 1823 | |
|
1824 | 1824 | if best > 0.0: |
|
1825 | 1825 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1826 | 1826 | else: |
|
1827 | 1827 | order = 3 |
|
1828 | 1828 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1829 | 1829 | precision, |
|
1830 | 1830 | best * scaling[order], |
|
1831 | 1831 | units[order]) |
|
1832 | 1832 | if tc > tc_min: |
|
1833 | 1833 | print "Compiler time: %.2f s" % tc |
|
1834 | 1834 | |
|
1835 | 1835 | @testdec.skip_doctest |
|
1836 | 1836 | def magic_time(self,parameter_s = ''): |
|
1837 | 1837 | """Time execution of a Python statement or expression. |
|
1838 | 1838 | |
|
1839 | 1839 | The CPU and wall clock times are printed, and the value of the |
|
1840 | 1840 | expression (if any) is returned. Note that under Win32, system time |
|
1841 | 1841 | is always reported as 0, since it can not be measured. |
|
1842 | 1842 | |
|
1843 | 1843 | This function provides very basic timing functionality. In Python |
|
1844 | 1844 | 2.3, the timeit module offers more control and sophistication, so this |
|
1845 | 1845 | could be rewritten to use it (patches welcome). |
|
1846 | 1846 | |
|
1847 | 1847 | Some examples: |
|
1848 | 1848 | |
|
1849 | 1849 | In [1]: time 2**128 |
|
1850 | 1850 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1851 | 1851 | Wall time: 0.00 |
|
1852 | 1852 | Out[1]: 340282366920938463463374607431768211456L |
|
1853 | 1853 | |
|
1854 | 1854 | In [2]: n = 1000000 |
|
1855 | 1855 | |
|
1856 | 1856 | In [3]: time sum(range(n)) |
|
1857 | 1857 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1858 | 1858 | Wall time: 1.37 |
|
1859 | 1859 | Out[3]: 499999500000L |
|
1860 | 1860 | |
|
1861 | 1861 | In [4]: time print 'hello world' |
|
1862 | 1862 | hello world |
|
1863 | 1863 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1864 | 1864 | Wall time: 0.00 |
|
1865 | 1865 | |
|
1866 | 1866 | Note that the time needed by Python to compile the given expression |
|
1867 | 1867 | will be reported if it is more than 0.1s. In this example, the |
|
1868 | 1868 | actual exponentiation is done by Python at compilation time, so while |
|
1869 | 1869 | the expression can take a noticeable amount of time to compute, that |
|
1870 | 1870 | time is purely due to the compilation: |
|
1871 | 1871 | |
|
1872 | 1872 | In [5]: time 3**9999; |
|
1873 | 1873 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1874 | 1874 | Wall time: 0.00 s |
|
1875 | 1875 | |
|
1876 | 1876 | In [6]: time 3**999999; |
|
1877 | 1877 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1878 | 1878 | Wall time: 0.00 s |
|
1879 | 1879 | Compiler : 0.78 s |
|
1880 | 1880 | """ |
|
1881 | 1881 | |
|
1882 | 1882 | # fail immediately if the given expression can't be compiled |
|
1883 | 1883 | |
|
1884 | 1884 | expr = self.shell.prefilter(parameter_s,False) |
|
1885 | 1885 | |
|
1886 | 1886 | # Minimum time above which compilation time will be reported |
|
1887 | 1887 | tc_min = 0.1 |
|
1888 | 1888 | |
|
1889 | 1889 | try: |
|
1890 | 1890 | mode = 'eval' |
|
1891 | 1891 | t0 = clock() |
|
1892 | 1892 | code = compile(expr,'<timed eval>',mode) |
|
1893 | 1893 | tc = clock()-t0 |
|
1894 | 1894 | except SyntaxError: |
|
1895 | 1895 | mode = 'exec' |
|
1896 | 1896 | t0 = clock() |
|
1897 | 1897 | code = compile(expr,'<timed exec>',mode) |
|
1898 | 1898 | tc = clock()-t0 |
|
1899 | 1899 | # skew measurement as little as possible |
|
1900 | 1900 | glob = self.shell.user_ns |
|
1901 | 1901 | clk = clock2 |
|
1902 | 1902 | wtime = time.time |
|
1903 | 1903 | # time execution |
|
1904 | 1904 | wall_st = wtime() |
|
1905 | 1905 | if mode=='eval': |
|
1906 | 1906 | st = clk() |
|
1907 | 1907 | out = eval(code,glob) |
|
1908 | 1908 | end = clk() |
|
1909 | 1909 | else: |
|
1910 | 1910 | st = clk() |
|
1911 | 1911 | exec code in glob |
|
1912 | 1912 | end = clk() |
|
1913 | 1913 | out = None |
|
1914 | 1914 | wall_end = wtime() |
|
1915 | 1915 | # Compute actual times and report |
|
1916 | 1916 | wall_time = wall_end-wall_st |
|
1917 | 1917 | cpu_user = end[0]-st[0] |
|
1918 | 1918 | cpu_sys = end[1]-st[1] |
|
1919 | 1919 | cpu_tot = cpu_user+cpu_sys |
|
1920 | 1920 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1921 | 1921 | (cpu_user,cpu_sys,cpu_tot) |
|
1922 | 1922 | print "Wall time: %.2f s" % wall_time |
|
1923 | 1923 | if tc > tc_min: |
|
1924 | 1924 | print "Compiler : %.2f s" % tc |
|
1925 | 1925 | return out |
|
1926 | 1926 | |
|
1927 | 1927 | @testdec.skip_doctest |
|
1928 | 1928 | def magic_macro(self,parameter_s = ''): |
|
1929 | 1929 | """Define a set of input lines as a macro for future re-execution. |
|
1930 | 1930 | |
|
1931 | 1931 | Usage:\\ |
|
1932 | 1932 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1933 | 1933 | |
|
1934 | 1934 | Options: |
|
1935 | 1935 | |
|
1936 | 1936 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1937 | 1937 | so that magics are loaded in their transformed version to valid |
|
1938 | 1938 | Python. If this option is given, the raw input as typed as the |
|
1939 | 1939 | command line is used instead. |
|
1940 | 1940 | |
|
1941 | 1941 | This will define a global variable called `name` which is a string |
|
1942 | 1942 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1943 | 1943 | above) from your input history into a single string. This variable |
|
1944 | 1944 | acts like an automatic function which re-executes those lines as if |
|
1945 | 1945 | you had typed them. You just type 'name' at the prompt and the code |
|
1946 | 1946 | executes. |
|
1947 | 1947 | |
|
1948 | 1948 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
1949 | 1949 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
1950 | 1950 | using the lines numbered 5,6 and 7. |
|
1951 | 1951 | |
|
1952 | 1952 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1953 | 1953 | notation, where N:M means numbers N through M-1. |
|
1954 | 1954 | |
|
1955 | 1955 | For example, if your history contains (%hist prints it): |
|
1956 | 1956 | |
|
1957 | 1957 | 44: x=1 |
|
1958 | 1958 | 45: y=3 |
|
1959 | 1959 | 46: z=x+y |
|
1960 | 1960 | 47: print x |
|
1961 | 1961 | 48: a=5 |
|
1962 | 1962 | 49: print 'x',x,'y',y |
|
1963 | 1963 | |
|
1964 | 1964 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1965 | 1965 | called my_macro with: |
|
1966 | 1966 | |
|
1967 | 1967 | In [55]: %macro my_macro 44-47 49 |
|
1968 | 1968 | |
|
1969 | 1969 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1970 | 1970 | in one pass. |
|
1971 | 1971 | |
|
1972 | 1972 | You don't need to give the line-numbers in order, and any given line |
|
1973 | 1973 | number can appear multiple times. You can assemble macros with any |
|
1974 | 1974 | lines from your input history in any order. |
|
1975 | 1975 | |
|
1976 | 1976 | The macro is a simple object which holds its value in an attribute, |
|
1977 | 1977 | but IPython's display system checks for macros and executes them as |
|
1978 | 1978 | code instead of printing them when you type their name. |
|
1979 | 1979 | |
|
1980 | 1980 | You can view a macro's contents by explicitly printing it with: |
|
1981 | 1981 | |
|
1982 | 1982 | 'print macro_name'. |
|
1983 | 1983 | |
|
1984 | 1984 | For one-off cases which DON'T contain magic function calls in them you |
|
1985 | 1985 | can obtain similar results by explicitly executing slices from your |
|
1986 | 1986 | input history with: |
|
1987 | 1987 | |
|
1988 | 1988 | In [60]: exec In[44:48]+In[49]""" |
|
1989 | 1989 | |
|
1990 | 1990 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
1991 | 1991 | if not args: |
|
1992 | 1992 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] |
|
1993 | 1993 | macs.sort() |
|
1994 | 1994 | return macs |
|
1995 | 1995 | if len(args) == 1: |
|
1996 | 1996 | raise UsageError( |
|
1997 | 1997 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
1998 | 1998 | name,ranges = args[0], args[1:] |
|
1999 | 1999 | |
|
2000 | 2000 | #print 'rng',ranges # dbg |
|
2001 | 2001 | lines = self.extract_input_slices(ranges,opts.has_key('r')) |
|
2002 | 2002 | macro = Macro(lines) |
|
2003 | 2003 | self.shell.user_ns.update({name:macro}) |
|
2004 | 2004 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
2005 | 2005 | print 'Macro contents:' |
|
2006 | 2006 | print macro, |
|
2007 | 2007 | |
|
2008 | 2008 | def magic_save(self,parameter_s = ''): |
|
2009 | 2009 | """Save a set of lines to a given filename. |
|
2010 | 2010 | |
|
2011 | 2011 | Usage:\\ |
|
2012 | 2012 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
2013 | 2013 | |
|
2014 | 2014 | Options: |
|
2015 | 2015 | |
|
2016 | 2016 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2017 | 2017 | so that magics are loaded in their transformed version to valid |
|
2018 | 2018 | Python. If this option is given, the raw input as typed as the |
|
2019 | 2019 | command line is used instead. |
|
2020 | 2020 | |
|
2021 | 2021 | This function uses the same syntax as %macro for line extraction, but |
|
2022 | 2022 | instead of creating a macro it saves the resulting string to the |
|
2023 | 2023 | filename you specify. |
|
2024 | 2024 | |
|
2025 | 2025 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2026 | 2026 | it asks for confirmation before overwriting existing files.""" |
|
2027 | 2027 | |
|
2028 | 2028 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2029 | 2029 | fname,ranges = args[0], args[1:] |
|
2030 | 2030 | if not fname.endswith('.py'): |
|
2031 | 2031 | fname += '.py' |
|
2032 | 2032 | if os.path.isfile(fname): |
|
2033 | 2033 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2034 | 2034 | if ans.lower() not in ['y','yes']: |
|
2035 | 2035 | print 'Operation cancelled.' |
|
2036 | 2036 | return |
|
2037 | 2037 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) |
|
2038 | 2038 | f = file(fname,'w') |
|
2039 | 2039 | f.write(cmds) |
|
2040 | 2040 | f.close() |
|
2041 | 2041 | print 'The following commands were written to file `%s`:' % fname |
|
2042 | 2042 | print cmds |
|
2043 | 2043 | |
|
2044 | 2044 | def _edit_macro(self,mname,macro): |
|
2045 | 2045 | """open an editor with the macro data in a file""" |
|
2046 | 2046 | filename = self.shell.mktempfile(macro.value) |
|
2047 | 2047 | self.shell.hooks.editor(filename) |
|
2048 | 2048 | |
|
2049 | 2049 | # and make a new macro object, to replace the old one |
|
2050 | 2050 | mfile = open(filename) |
|
2051 | 2051 | mvalue = mfile.read() |
|
2052 | 2052 | mfile.close() |
|
2053 | 2053 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2054 | 2054 | |
|
2055 | 2055 | def magic_ed(self,parameter_s=''): |
|
2056 | 2056 | """Alias to %edit.""" |
|
2057 | 2057 | return self.magic_edit(parameter_s) |
|
2058 | 2058 | |
|
2059 | 2059 | @testdec.skip_doctest |
|
2060 | 2060 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2061 | 2061 | """Bring up an editor and execute the resulting code. |
|
2062 | 2062 | |
|
2063 | 2063 | Usage: |
|
2064 | 2064 | %edit [options] [args] |
|
2065 | 2065 | |
|
2066 | 2066 | %edit runs IPython's editor hook. The default version of this hook is |
|
2067 | 2067 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
2068 | 2068 | environment variable $EDITOR. If this isn't found, it will default to |
|
2069 | 2069 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
2070 | 2070 | docstring for how to change the editor hook. |
|
2071 | 2071 | |
|
2072 | 2072 | You can also set the value of this editor via the command line option |
|
2073 | 2073 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
2074 | 2074 | specifically for IPython an editor different from your typical default |
|
2075 | 2075 | (and for Windows users who typically don't set environment variables). |
|
2076 | 2076 | |
|
2077 | 2077 | This command allows you to conveniently edit multi-line code right in |
|
2078 | 2078 | your IPython session. |
|
2079 | 2079 | |
|
2080 | 2080 | If called without arguments, %edit opens up an empty editor with a |
|
2081 | 2081 | temporary file and will execute the contents of this file when you |
|
2082 | 2082 | close it (don't forget to save it!). |
|
2083 | 2083 | |
|
2084 | 2084 | |
|
2085 | 2085 | Options: |
|
2086 | 2086 | |
|
2087 | 2087 | -n <number>: open the editor at a specified line number. By default, |
|
2088 | 2088 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2089 | 2089 | you can configure this by providing your own modified hook if your |
|
2090 | 2090 | favorite editor supports line-number specifications with a different |
|
2091 | 2091 | syntax. |
|
2092 | 2092 | |
|
2093 | 2093 | -p: this will call the editor with the same data as the previous time |
|
2094 | 2094 | it was used, regardless of how long ago (in your current session) it |
|
2095 | 2095 | was. |
|
2096 | 2096 | |
|
2097 | 2097 | -r: use 'raw' input. This option only applies to input taken from the |
|
2098 | 2098 | user's history. By default, the 'processed' history is used, so that |
|
2099 | 2099 | magics are loaded in their transformed version to valid Python. If |
|
2100 | 2100 | this option is given, the raw input as typed as the command line is |
|
2101 | 2101 | used instead. When you exit the editor, it will be executed by |
|
2102 | 2102 | IPython's own processor. |
|
2103 | 2103 | |
|
2104 | 2104 | -x: do not execute the edited code immediately upon exit. This is |
|
2105 | 2105 | mainly useful if you are editing programs which need to be called with |
|
2106 | 2106 | command line arguments, which you can then do using %run. |
|
2107 | 2107 | |
|
2108 | 2108 | |
|
2109 | 2109 | Arguments: |
|
2110 | 2110 | |
|
2111 | 2111 | If arguments are given, the following possibilites exist: |
|
2112 | 2112 | |
|
2113 | 2113 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
2114 | 2114 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
2115 | 2115 | loaded into the editor. The syntax is the same of the %macro command. |
|
2116 | 2116 | |
|
2117 | 2117 | - If the argument doesn't start with a number, it is evaluated as a |
|
2118 | 2118 | variable and its contents loaded into the editor. You can thus edit |
|
2119 | 2119 | any string which contains python code (including the result of |
|
2120 | 2120 | previous edits). |
|
2121 | 2121 | |
|
2122 | 2122 | - If the argument is the name of an object (other than a string), |
|
2123 | 2123 | IPython will try to locate the file where it was defined and open the |
|
2124 | 2124 | editor at the point where it is defined. You can use `%edit function` |
|
2125 | 2125 | to load an editor exactly at the point where 'function' is defined, |
|
2126 | 2126 | edit it and have the file be executed automatically. |
|
2127 | 2127 | |
|
2128 | 2128 | If the object is a macro (see %macro for details), this opens up your |
|
2129 | 2129 | specified editor with a temporary file containing the macro's data. |
|
2130 | 2130 | Upon exit, the macro is reloaded with the contents of the file. |
|
2131 | 2131 | |
|
2132 | 2132 | Note: opening at an exact line is only supported under Unix, and some |
|
2133 | 2133 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2134 | 2134 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2135 | 2135 | (X)Emacs, vi, jed, pico and joe all do. |
|
2136 | 2136 | |
|
2137 | 2137 | - If the argument is not found as a variable, IPython will look for a |
|
2138 | 2138 | file with that name (adding .py if necessary) and load it into the |
|
2139 | 2139 | editor. It will execute its contents with execfile() when you exit, |
|
2140 | 2140 | loading any code in the file into your interactive namespace. |
|
2141 | 2141 | |
|
2142 | 2142 | After executing your code, %edit will return as output the code you |
|
2143 | 2143 | typed in the editor (except when it was an existing file). This way |
|
2144 | 2144 | you can reload the code in further invocations of %edit as a variable, |
|
2145 | 2145 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2146 | 2146 | the output. |
|
2147 | 2147 | |
|
2148 | 2148 | Note that %edit is also available through the alias %ed. |
|
2149 | 2149 | |
|
2150 | 2150 | This is an example of creating a simple function inside the editor and |
|
2151 | 2151 | then modifying it. First, start up the editor: |
|
2152 | 2152 | |
|
2153 | 2153 | In [1]: ed |
|
2154 | 2154 | Editing... done. Executing edited code... |
|
2155 | 2155 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
2156 | 2156 | |
|
2157 | 2157 | We can then call the function foo(): |
|
2158 | 2158 | |
|
2159 | 2159 | In [2]: foo() |
|
2160 | 2160 | foo() was defined in an editing session |
|
2161 | 2161 | |
|
2162 | 2162 | Now we edit foo. IPython automatically loads the editor with the |
|
2163 | 2163 | (temporary) file where foo() was previously defined: |
|
2164 | 2164 | |
|
2165 | 2165 | In [3]: ed foo |
|
2166 | 2166 | Editing... done. Executing edited code... |
|
2167 | 2167 | |
|
2168 | 2168 | And if we call foo() again we get the modified version: |
|
2169 | 2169 | |
|
2170 | 2170 | In [4]: foo() |
|
2171 | 2171 | foo() has now been changed! |
|
2172 | 2172 | |
|
2173 | 2173 | Here is an example of how to edit a code snippet successive |
|
2174 | 2174 | times. First we call the editor: |
|
2175 | 2175 | |
|
2176 | 2176 | In [5]: ed |
|
2177 | 2177 | Editing... done. Executing edited code... |
|
2178 | 2178 | hello |
|
2179 | 2179 | Out[5]: "print 'hello'n" |
|
2180 | 2180 | |
|
2181 | 2181 | Now we call it again with the previous output (stored in _): |
|
2182 | 2182 | |
|
2183 | 2183 | In [6]: ed _ |
|
2184 | 2184 | Editing... done. Executing edited code... |
|
2185 | 2185 | hello world |
|
2186 | 2186 | Out[6]: "print 'hello world'n" |
|
2187 | 2187 | |
|
2188 | 2188 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2189 | 2189 | |
|
2190 | 2190 | In [7]: ed _8 |
|
2191 | 2191 | Editing... done. Executing edited code... |
|
2192 | 2192 | hello again |
|
2193 | 2193 | Out[7]: "print 'hello again'n" |
|
2194 | 2194 | |
|
2195 | 2195 | |
|
2196 | 2196 | Changing the default editor hook: |
|
2197 | 2197 | |
|
2198 | 2198 | If you wish to write your own editor hook, you can put it in a |
|
2199 | 2199 | configuration file which you load at startup time. The default hook |
|
2200 | 2200 | is defined in the IPython.hooks module, and you can use that as a |
|
2201 | 2201 | starting example for further modifications. That file also has |
|
2202 | 2202 | general instructions on how to set a new hook for use once you've |
|
2203 | 2203 | defined it.""" |
|
2204 | 2204 | |
|
2205 | 2205 | # FIXME: This function has become a convoluted mess. It needs a |
|
2206 | 2206 | # ground-up rewrite with clean, simple logic. |
|
2207 | 2207 | |
|
2208 | 2208 | def make_filename(arg): |
|
2209 | 2209 | "Make a filename from the given args" |
|
2210 | 2210 | try: |
|
2211 | 2211 | filename = get_py_filename(arg) |
|
2212 | 2212 | except IOError: |
|
2213 | 2213 | if args.endswith('.py'): |
|
2214 | 2214 | filename = arg |
|
2215 | 2215 | else: |
|
2216 | 2216 | filename = None |
|
2217 | 2217 | return filename |
|
2218 | 2218 | |
|
2219 | 2219 | # custom exceptions |
|
2220 | 2220 | class DataIsObject(Exception): pass |
|
2221 | 2221 | |
|
2222 | 2222 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2223 | 2223 | # Set a few locals from the options for convenience: |
|
2224 | 2224 | opts_p = opts.has_key('p') |
|
2225 | 2225 | opts_r = opts.has_key('r') |
|
2226 | 2226 | |
|
2227 | 2227 | # Default line number value |
|
2228 | 2228 | lineno = opts.get('n',None) |
|
2229 | 2229 | |
|
2230 | 2230 | if opts_p: |
|
2231 | 2231 | args = '_%s' % last_call[0] |
|
2232 | 2232 | if not self.shell.user_ns.has_key(args): |
|
2233 | 2233 | args = last_call[1] |
|
2234 | 2234 | |
|
2235 | 2235 | # use last_call to remember the state of the previous call, but don't |
|
2236 | 2236 | # let it be clobbered by successive '-p' calls. |
|
2237 | 2237 | try: |
|
2238 | 2238 | last_call[0] = self.shell.outputcache.prompt_count |
|
2239 | 2239 | if not opts_p: |
|
2240 | 2240 | last_call[1] = parameter_s |
|
2241 | 2241 | except: |
|
2242 | 2242 | pass |
|
2243 | 2243 | |
|
2244 | 2244 | # by default this is done with temp files, except when the given |
|
2245 | 2245 | # arg is a filename |
|
2246 | 2246 | use_temp = 1 |
|
2247 | 2247 | |
|
2248 | 2248 | if re.match(r'\d',args): |
|
2249 | 2249 | # Mode where user specifies ranges of lines, like in %macro. |
|
2250 | 2250 | # This means that you can't edit files whose names begin with |
|
2251 | 2251 | # numbers this way. Tough. |
|
2252 | 2252 | ranges = args.split() |
|
2253 | 2253 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
2254 | 2254 | elif args.endswith('.py'): |
|
2255 | 2255 | filename = make_filename(args) |
|
2256 | 2256 | data = '' |
|
2257 | 2257 | use_temp = 0 |
|
2258 | 2258 | elif args: |
|
2259 | 2259 | try: |
|
2260 | 2260 | # Load the parameter given as a variable. If not a string, |
|
2261 | 2261 | # process it as an object instead (below) |
|
2262 | 2262 | |
|
2263 | 2263 | #print '*** args',args,'type',type(args) # dbg |
|
2264 | 2264 | data = eval(args,self.shell.user_ns) |
|
2265 | 2265 | if not type(data) in StringTypes: |
|
2266 | 2266 | raise DataIsObject |
|
2267 | 2267 | |
|
2268 | 2268 | except (NameError,SyntaxError): |
|
2269 | 2269 | # given argument is not a variable, try as a filename |
|
2270 | 2270 | filename = make_filename(args) |
|
2271 | 2271 | if filename is None: |
|
2272 | 2272 | warn("Argument given (%s) can't be found as a variable " |
|
2273 | 2273 | "or as a filename." % args) |
|
2274 | 2274 | return |
|
2275 | 2275 | |
|
2276 | 2276 | data = '' |
|
2277 | 2277 | use_temp = 0 |
|
2278 | 2278 | except DataIsObject: |
|
2279 | 2279 | |
|
2280 | 2280 | # macros have a special edit function |
|
2281 | 2281 | if isinstance(data,Macro): |
|
2282 | 2282 | self._edit_macro(args,data) |
|
2283 | 2283 | return |
|
2284 | 2284 | |
|
2285 | 2285 | # For objects, try to edit the file where they are defined |
|
2286 | 2286 | try: |
|
2287 | 2287 | filename = inspect.getabsfile(data) |
|
2288 | 2288 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2289 | 2289 | # class created by %edit? Try to find source |
|
2290 | 2290 | # by looking for method definitions instead, the |
|
2291 | 2291 | # __module__ in those classes is FakeModule. |
|
2292 | 2292 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2293 | 2293 | for attr in attrs: |
|
2294 | 2294 | if not inspect.ismethod(attr): |
|
2295 | 2295 | continue |
|
2296 | 2296 | filename = inspect.getabsfile(attr) |
|
2297 | 2297 | if filename and 'fakemodule' not in filename.lower(): |
|
2298 | 2298 | # change the attribute to be the edit target instead |
|
2299 | 2299 | data = attr |
|
2300 | 2300 | break |
|
2301 | 2301 | |
|
2302 | 2302 | datafile = 1 |
|
2303 | 2303 | except TypeError: |
|
2304 | 2304 | filename = make_filename(args) |
|
2305 | 2305 | datafile = 1 |
|
2306 | 2306 | warn('Could not find file where `%s` is defined.\n' |
|
2307 | 2307 | 'Opening a file named `%s`' % (args,filename)) |
|
2308 | 2308 | # Now, make sure we can actually read the source (if it was in |
|
2309 | 2309 | # a temp file it's gone by now). |
|
2310 | 2310 | if datafile: |
|
2311 | 2311 | try: |
|
2312 | 2312 | if lineno is None: |
|
2313 | 2313 | lineno = inspect.getsourcelines(data)[1] |
|
2314 | 2314 | except IOError: |
|
2315 | 2315 | filename = make_filename(args) |
|
2316 | 2316 | if filename is None: |
|
2317 | 2317 | warn('The file `%s` where `%s` was defined cannot ' |
|
2318 | 2318 | 'be read.' % (filename,data)) |
|
2319 | 2319 | return |
|
2320 | 2320 | use_temp = 0 |
|
2321 | 2321 | else: |
|
2322 | 2322 | data = '' |
|
2323 | 2323 | |
|
2324 | 2324 | if use_temp: |
|
2325 | 2325 | filename = self.shell.mktempfile(data) |
|
2326 | 2326 | print 'IPython will make a temporary file named:',filename |
|
2327 | 2327 | |
|
2328 | 2328 | # do actual editing here |
|
2329 | 2329 | print 'Editing...', |
|
2330 | 2330 | sys.stdout.flush() |
|
2331 | 2331 | self.shell.hooks.editor(filename,lineno) |
|
2332 | 2332 | if opts.has_key('x'): # -x prevents actual execution |
|
2333 | 2333 | |
|
2334 | 2334 | else: |
|
2335 | 2335 | print 'done. Executing edited code...' |
|
2336 | 2336 | if opts_r: |
|
2337 | 2337 | self.shell.runlines(file_read(filename)) |
|
2338 | 2338 | else: |
|
2339 | 2339 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2340 | 2340 | self.shell.user_ns) |
|
2341 | 2341 | if use_temp: |
|
2342 | 2342 | try: |
|
2343 | 2343 | return open(filename).read() |
|
2344 | 2344 | except IOError,msg: |
|
2345 | 2345 | if msg.filename == filename: |
|
2346 | 2346 | warn('File not found. Did you forget to save?') |
|
2347 | 2347 | return |
|
2348 | 2348 | else: |
|
2349 | 2349 | self.shell.showtraceback() |
|
2350 | 2350 | |
|
2351 | 2351 | def magic_xmode(self,parameter_s = ''): |
|
2352 | 2352 | """Switch modes for the exception handlers. |
|
2353 | 2353 | |
|
2354 | 2354 | Valid modes: Plain, Context and Verbose. |
|
2355 | 2355 | |
|
2356 | 2356 | If called without arguments, acts as a toggle.""" |
|
2357 | 2357 | |
|
2358 | 2358 | def xmode_switch_err(name): |
|
2359 | 2359 | warn('Error changing %s exception modes.\n%s' % |
|
2360 | 2360 | (name,sys.exc_info()[1])) |
|
2361 | 2361 | |
|
2362 | 2362 | shell = self.shell |
|
2363 | 2363 | new_mode = parameter_s.strip().capitalize() |
|
2364 | 2364 | try: |
|
2365 | 2365 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2366 | 2366 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2367 | 2367 | except: |
|
2368 | 2368 | xmode_switch_err('user') |
|
2369 | 2369 | |
|
2370 | 2370 | # threaded shells use a special handler in sys.excepthook |
|
2371 | 2371 | if shell.isthreaded: |
|
2372 | 2372 | try: |
|
2373 | 2373 | shell.sys_excepthook.set_mode(mode=new_mode) |
|
2374 | 2374 | except: |
|
2375 | 2375 | xmode_switch_err('threaded') |
|
2376 | 2376 | |
|
2377 | 2377 | def magic_colors(self,parameter_s = ''): |
|
2378 | 2378 | """Switch color scheme for prompts, info system and exception handlers. |
|
2379 | 2379 | |
|
2380 | 2380 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2381 | 2381 | |
|
2382 | 2382 | Color scheme names are not case-sensitive.""" |
|
2383 | 2383 | |
|
2384 | 2384 | def color_switch_err(name): |
|
2385 | 2385 | warn('Error changing %s color schemes.\n%s' % |
|
2386 | 2386 | (name,sys.exc_info()[1])) |
|
2387 | 2387 | |
|
2388 | 2388 | |
|
2389 | 2389 | new_scheme = parameter_s.strip() |
|
2390 | 2390 | if not new_scheme: |
|
2391 | 2391 | raise UsageError( |
|
2392 | 2392 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2393 | 2393 | return |
|
2394 | 2394 | # local shortcut |
|
2395 | 2395 | shell = self.shell |
|
2396 | 2396 | |
|
2397 | 2397 | import IPython.rlineimpl as readline |
|
2398 | 2398 | |
|
2399 | 2399 | if not readline.have_readline and sys.platform == "win32": |
|
2400 | 2400 | msg = """\ |
|
2401 | 2401 | Proper color support under MS Windows requires the pyreadline library. |
|
2402 | 2402 | You can find it at: |
|
2403 | 2403 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2404 | 2404 | Gary's readline needs the ctypes module, from: |
|
2405 | 2405 | http://starship.python.net/crew/theller/ctypes |
|
2406 | 2406 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2407 | 2407 | |
|
2408 | 2408 | Defaulting color scheme to 'NoColor'""" |
|
2409 | 2409 | new_scheme = 'NoColor' |
|
2410 | 2410 | warn(msg) |
|
2411 | 2411 | |
|
2412 | 2412 | # readline option is 0 |
|
2413 | 2413 | if not shell.has_readline: |
|
2414 | 2414 | new_scheme = 'NoColor' |
|
2415 | 2415 | |
|
2416 | 2416 | # Set prompt colors |
|
2417 | 2417 | try: |
|
2418 | 2418 | shell.outputcache.set_colors(new_scheme) |
|
2419 | 2419 | except: |
|
2420 | 2420 | color_switch_err('prompt') |
|
2421 | 2421 | else: |
|
2422 | 2422 | shell.rc.colors = \ |
|
2423 | 2423 | shell.outputcache.color_table.active_scheme_name |
|
2424 | 2424 | # Set exception colors |
|
2425 | 2425 | try: |
|
2426 | 2426 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2427 | 2427 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2428 | 2428 | except: |
|
2429 | 2429 | color_switch_err('exception') |
|
2430 | 2430 | |
|
2431 | 2431 | # threaded shells use a verbose traceback in sys.excepthook |
|
2432 | 2432 | if shell.isthreaded: |
|
2433 | 2433 | try: |
|
2434 | 2434 | shell.sys_excepthook.set_colors(scheme=new_scheme) |
|
2435 | 2435 | except: |
|
2436 | 2436 | color_switch_err('system exception handler') |
|
2437 | 2437 | |
|
2438 | 2438 | # Set info (for 'object?') colors |
|
2439 | 2439 | if shell.rc.color_info: |
|
2440 | 2440 | try: |
|
2441 | 2441 | shell.inspector.set_active_scheme(new_scheme) |
|
2442 | 2442 | except: |
|
2443 | 2443 | color_switch_err('object inspector') |
|
2444 | 2444 | else: |
|
2445 | 2445 | shell.inspector.set_active_scheme('NoColor') |
|
2446 | 2446 | |
|
2447 | 2447 | def magic_color_info(self,parameter_s = ''): |
|
2448 | 2448 | """Toggle color_info. |
|
2449 | 2449 | |
|
2450 | 2450 | The color_info configuration parameter controls whether colors are |
|
2451 | 2451 | used for displaying object details (by things like %psource, %pfile or |
|
2452 | 2452 | the '?' system). This function toggles this value with each call. |
|
2453 | 2453 | |
|
2454 | 2454 | Note that unless you have a fairly recent pager (less works better |
|
2455 | 2455 | than more) in your system, using colored object information displays |
|
2456 | 2456 | will not work properly. Test it and see.""" |
|
2457 | 2457 | |
|
2458 | 2458 | self.shell.rc.color_info = 1 - self.shell.rc.color_info |
|
2459 | 2459 | self.magic_colors(self.shell.rc.colors) |
|
2460 | 2460 | print 'Object introspection functions have now coloring:', |
|
2461 | 2461 | print ['OFF','ON'][self.shell.rc.color_info] |
|
2462 | 2462 | |
|
2463 | 2463 | def magic_Pprint(self, parameter_s=''): |
|
2464 | 2464 | """Toggle pretty printing on/off.""" |
|
2465 | 2465 | |
|
2466 | 2466 | self.shell.rc.pprint = 1 - self.shell.rc.pprint |
|
2467 | 2467 | print 'Pretty printing has been turned', \ |
|
2468 | 2468 | ['OFF','ON'][self.shell.rc.pprint] |
|
2469 | 2469 | |
|
2470 | 2470 | def magic_exit(self, parameter_s=''): |
|
2471 | 2471 | """Exit IPython, confirming if configured to do so. |
|
2472 | 2472 | |
|
2473 | 2473 | You can configure whether IPython asks for confirmation upon exit by |
|
2474 | 2474 | setting the confirm_exit flag in the ipythonrc file.""" |
|
2475 | 2475 | |
|
2476 | 2476 | self.shell.exit() |
|
2477 | 2477 | |
|
2478 | 2478 | def magic_quit(self, parameter_s=''): |
|
2479 | 2479 | """Exit IPython, confirming if configured to do so (like %exit)""" |
|
2480 | 2480 | |
|
2481 | 2481 | self.shell.exit() |
|
2482 | 2482 | |
|
2483 | 2483 | def magic_Exit(self, parameter_s=''): |
|
2484 | 2484 | """Exit IPython without confirmation.""" |
|
2485 | 2485 | |
|
2486 |
self.shell. |
|
|
2486 | self.shell.ask_exit() | |
|
2487 | 2487 | |
|
2488 | 2488 | #...................................................................... |
|
2489 | 2489 | # Functions to implement unix shell-type things |
|
2490 | 2490 | |
|
2491 | 2491 | @testdec.skip_doctest |
|
2492 | 2492 | def magic_alias(self, parameter_s = ''): |
|
2493 | 2493 | """Define an alias for a system command. |
|
2494 | 2494 | |
|
2495 | 2495 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2496 | 2496 | |
|
2497 | 2497 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2498 | 2498 | params' (from your underlying operating system). |
|
2499 | 2499 | |
|
2500 | 2500 | Aliases have lower precedence than magic functions and Python normal |
|
2501 | 2501 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2502 | 2502 | alias can not be executed until 'del foo' removes the Python variable. |
|
2503 | 2503 | |
|
2504 | 2504 | You can use the %l specifier in an alias definition to represent the |
|
2505 | 2505 | whole line when the alias is called. For example: |
|
2506 | 2506 | |
|
2507 | 2507 | In [2]: alias all echo "Input in brackets: <%l>" |
|
2508 | 2508 | In [3]: all hello world |
|
2509 | 2509 | Input in brackets: <hello world> |
|
2510 | 2510 | |
|
2511 | 2511 | You can also define aliases with parameters using %s specifiers (one |
|
2512 | 2512 | per parameter): |
|
2513 | 2513 | |
|
2514 | 2514 | In [1]: alias parts echo first %s second %s |
|
2515 | 2515 | In [2]: %parts A B |
|
2516 | 2516 | first A second B |
|
2517 | 2517 | In [3]: %parts A |
|
2518 | 2518 | Incorrect number of arguments: 2 expected. |
|
2519 | 2519 | parts is an alias to: 'echo first %s second %s' |
|
2520 | 2520 | |
|
2521 | 2521 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2522 | 2522 | the other in your aliases. |
|
2523 | 2523 | |
|
2524 | 2524 | Aliases expand Python variables just like system calls using ! or !! |
|
2525 | 2525 | do: all expressions prefixed with '$' get expanded. For details of |
|
2526 | 2526 | the semantic rules, see PEP-215: |
|
2527 | 2527 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2528 | 2528 | IPython for variable expansion. If you want to access a true shell |
|
2529 | 2529 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2530 | 2530 | |
|
2531 | 2531 | In [6]: alias show echo |
|
2532 | 2532 | In [7]: PATH='A Python string' |
|
2533 | 2533 | In [8]: show $PATH |
|
2534 | 2534 | A Python string |
|
2535 | 2535 | In [9]: show $$PATH |
|
2536 | 2536 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2537 | 2537 | |
|
2538 | 2538 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2539 | 2539 | and %rehashx functions, which automatically create aliases for the |
|
2540 | 2540 | contents of your $PATH. |
|
2541 | 2541 | |
|
2542 | 2542 | If called with no parameters, %alias prints the current alias table.""" |
|
2543 | 2543 | |
|
2544 | 2544 | par = parameter_s.strip() |
|
2545 | 2545 | if not par: |
|
2546 | 2546 | stored = self.db.get('stored_aliases', {} ) |
|
2547 | 2547 | atab = self.shell.alias_table |
|
2548 | 2548 | aliases = atab.keys() |
|
2549 | 2549 | aliases.sort() |
|
2550 | 2550 | res = [] |
|
2551 | 2551 | showlast = [] |
|
2552 | 2552 | for alias in aliases: |
|
2553 | 2553 | special = False |
|
2554 | 2554 | try: |
|
2555 | 2555 | tgt = atab[alias][1] |
|
2556 | 2556 | except (TypeError, AttributeError): |
|
2557 | 2557 | # unsubscriptable? probably a callable |
|
2558 | 2558 | tgt = atab[alias] |
|
2559 | 2559 | special = True |
|
2560 | 2560 | # 'interesting' aliases |
|
2561 | 2561 | if (alias in stored or |
|
2562 | 2562 | special or |
|
2563 | 2563 | alias.lower() != os.path.splitext(tgt)[0].lower() or |
|
2564 | 2564 | ' ' in tgt): |
|
2565 | 2565 | showlast.append((alias, tgt)) |
|
2566 | 2566 | else: |
|
2567 | 2567 | res.append((alias, tgt )) |
|
2568 | 2568 | |
|
2569 | 2569 | # show most interesting aliases last |
|
2570 | 2570 | res.extend(showlast) |
|
2571 | 2571 | print "Total number of aliases:",len(aliases) |
|
2572 | 2572 | return res |
|
2573 | 2573 | try: |
|
2574 | 2574 | alias,cmd = par.split(None,1) |
|
2575 | 2575 | except: |
|
2576 | 2576 | print OInspect.getdoc(self.magic_alias) |
|
2577 | 2577 | else: |
|
2578 | 2578 | nargs = cmd.count('%s') |
|
2579 | 2579 | if nargs>0 and cmd.find('%l')>=0: |
|
2580 | 2580 | error('The %s and %l specifiers are mutually exclusive ' |
|
2581 | 2581 | 'in alias definitions.') |
|
2582 | 2582 | else: # all looks OK |
|
2583 | 2583 | self.shell.alias_table[alias] = (nargs,cmd) |
|
2584 | 2584 | self.shell.alias_table_validate(verbose=0) |
|
2585 | 2585 | # end magic_alias |
|
2586 | 2586 | |
|
2587 | 2587 | def magic_unalias(self, parameter_s = ''): |
|
2588 | 2588 | """Remove an alias""" |
|
2589 | 2589 | |
|
2590 | 2590 | aname = parameter_s.strip() |
|
2591 | 2591 | if aname in self.shell.alias_table: |
|
2592 | 2592 | del self.shell.alias_table[aname] |
|
2593 | 2593 | stored = self.db.get('stored_aliases', {} ) |
|
2594 | 2594 | if aname in stored: |
|
2595 | 2595 | print "Removing %stored alias",aname |
|
2596 | 2596 | del stored[aname] |
|
2597 | 2597 | self.db['stored_aliases'] = stored |
|
2598 | 2598 | |
|
2599 | 2599 | |
|
2600 | 2600 | def magic_rehashx(self, parameter_s = ''): |
|
2601 | 2601 | """Update the alias table with all executable files in $PATH. |
|
2602 | 2602 | |
|
2603 | 2603 | This version explicitly checks that every entry in $PATH is a file |
|
2604 | 2604 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2605 | 2605 | |
|
2606 | 2606 | Under Windows, it checks executability as a match agains a |
|
2607 | 2607 | '|'-separated string of extensions, stored in the IPython config |
|
2608 | 2608 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2609 | 2609 | |
|
2610 | 2610 | This function also resets the root module cache of module completer, |
|
2611 | 2611 | used on slow filesystems. |
|
2612 | 2612 | """ |
|
2613 | 2613 | |
|
2614 | 2614 | |
|
2615 | 2615 | ip = self.api |
|
2616 | 2616 | |
|
2617 | 2617 | # for the benefit of module completer in ipy_completers.py |
|
2618 | 2618 | del ip.db['rootmodules'] |
|
2619 | 2619 | |
|
2620 | 2620 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2621 | 2621 | os.environ.get('PATH','').split(os.pathsep)] |
|
2622 | 2622 | path = filter(os.path.isdir,path) |
|
2623 | 2623 | |
|
2624 | 2624 | alias_table = self.shell.alias_table |
|
2625 | 2625 | syscmdlist = [] |
|
2626 | 2626 | if os.name == 'posix': |
|
2627 | 2627 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2628 | 2628 | os.access(fname,os.X_OK) |
|
2629 | 2629 | else: |
|
2630 | 2630 | |
|
2631 | 2631 | try: |
|
2632 | 2632 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2633 | 2633 | except KeyError: |
|
2634 | 2634 | winext = 'exe|com|bat|py' |
|
2635 | 2635 | if 'py' not in winext: |
|
2636 | 2636 | winext += '|py' |
|
2637 | 2637 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2638 | 2638 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2639 | 2639 | savedir = os.getcwd() |
|
2640 | 2640 | try: |
|
2641 | 2641 | # write the whole loop for posix/Windows so we don't have an if in |
|
2642 | 2642 | # the innermost part |
|
2643 | 2643 | if os.name == 'posix': |
|
2644 | 2644 | for pdir in path: |
|
2645 | 2645 | os.chdir(pdir) |
|
2646 | 2646 | for ff in os.listdir(pdir): |
|
2647 | 2647 | if isexec(ff) and ff not in self.shell.no_alias: |
|
2648 | 2648 | # each entry in the alias table must be (N,name), |
|
2649 | 2649 | # where N is the number of positional arguments of the |
|
2650 | 2650 | # alias. |
|
2651 | 2651 | alias_table[ff] = (0,ff) |
|
2652 | 2652 | syscmdlist.append(ff) |
|
2653 | 2653 | else: |
|
2654 | 2654 | for pdir in path: |
|
2655 | 2655 | os.chdir(pdir) |
|
2656 | 2656 | for ff in os.listdir(pdir): |
|
2657 | 2657 | base, ext = os.path.splitext(ff) |
|
2658 | 2658 | if isexec(ff) and base.lower() not in self.shell.no_alias: |
|
2659 | 2659 | if ext.lower() == '.exe': |
|
2660 | 2660 | ff = base |
|
2661 | 2661 | alias_table[base.lower()] = (0,ff) |
|
2662 | 2662 | syscmdlist.append(ff) |
|
2663 | 2663 | # Make sure the alias table doesn't contain keywords or builtins |
|
2664 | 2664 | self.shell.alias_table_validate() |
|
2665 | 2665 | # Call again init_auto_alias() so we get 'rm -i' and other |
|
2666 | 2666 | # modified aliases since %rehashx will probably clobber them |
|
2667 | 2667 | |
|
2668 | 2668 | # no, we don't want them. if %rehashx clobbers them, good, |
|
2669 | 2669 | # we'll probably get better versions |
|
2670 | 2670 | # self.shell.init_auto_alias() |
|
2671 | 2671 | db = ip.db |
|
2672 | 2672 | db['syscmdlist'] = syscmdlist |
|
2673 | 2673 | finally: |
|
2674 | 2674 | os.chdir(savedir) |
|
2675 | 2675 | |
|
2676 | 2676 | def magic_pwd(self, parameter_s = ''): |
|
2677 | 2677 | """Return the current working directory path.""" |
|
2678 | 2678 | return os.getcwd() |
|
2679 | 2679 | |
|
2680 | 2680 | def magic_cd(self, parameter_s=''): |
|
2681 | 2681 | """Change the current working directory. |
|
2682 | 2682 | |
|
2683 | 2683 | This command automatically maintains an internal list of directories |
|
2684 | 2684 | you visit during your IPython session, in the variable _dh. The |
|
2685 | 2685 | command %dhist shows this history nicely formatted. You can also |
|
2686 | 2686 | do 'cd -<tab>' to see directory history conveniently. |
|
2687 | 2687 | |
|
2688 | 2688 | Usage: |
|
2689 | 2689 | |
|
2690 | 2690 | cd 'dir': changes to directory 'dir'. |
|
2691 | 2691 | |
|
2692 | 2692 | cd -: changes to the last visited directory. |
|
2693 | 2693 | |
|
2694 | 2694 | cd -<n>: changes to the n-th directory in the directory history. |
|
2695 | 2695 | |
|
2696 | 2696 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2697 | 2697 | (note: cd <bookmark_name> is enough if there is no |
|
2698 | 2698 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2699 | 2699 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2700 | 2700 | |
|
2701 | 2701 | Options: |
|
2702 | 2702 | |
|
2703 | 2703 | -q: quiet. Do not print the working directory after the cd command is |
|
2704 | 2704 | executed. By default IPython's cd command does print this directory, |
|
2705 | 2705 | since the default prompts do not display path information. |
|
2706 | 2706 | |
|
2707 | 2707 | Note that !cd doesn't work for this purpose because the shell where |
|
2708 | 2708 | !command runs is immediately discarded after executing 'command'.""" |
|
2709 | 2709 | |
|
2710 | 2710 | parameter_s = parameter_s.strip() |
|
2711 | 2711 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2712 | 2712 | |
|
2713 | 2713 | oldcwd = os.getcwd() |
|
2714 | 2714 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2715 | 2715 | # jump in directory history by number |
|
2716 | 2716 | if numcd: |
|
2717 | 2717 | nn = int(numcd.group(2)) |
|
2718 | 2718 | try: |
|
2719 | 2719 | ps = self.shell.user_ns['_dh'][nn] |
|
2720 | 2720 | except IndexError: |
|
2721 | 2721 | print 'The requested directory does not exist in history.' |
|
2722 | 2722 | return |
|
2723 | 2723 | else: |
|
2724 | 2724 | opts = {} |
|
2725 | 2725 | else: |
|
2726 | 2726 | #turn all non-space-escaping backslashes to slashes, |
|
2727 | 2727 | # for c:\windows\directory\names\ |
|
2728 | 2728 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2729 | 2729 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2730 | 2730 | # jump to previous |
|
2731 | 2731 | if ps == '-': |
|
2732 | 2732 | try: |
|
2733 | 2733 | ps = self.shell.user_ns['_dh'][-2] |
|
2734 | 2734 | except IndexError: |
|
2735 | 2735 | raise UsageError('%cd -: No previous directory to change to.') |
|
2736 | 2736 | # jump to bookmark if needed |
|
2737 | 2737 | else: |
|
2738 | 2738 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2739 | 2739 | bkms = self.db.get('bookmarks', {}) |
|
2740 | 2740 | |
|
2741 | 2741 | if bkms.has_key(ps): |
|
2742 | 2742 | target = bkms[ps] |
|
2743 | 2743 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2744 | 2744 | ps = target |
|
2745 | 2745 | else: |
|
2746 | 2746 | if opts.has_key('b'): |
|
2747 | 2747 | raise UsageError("Bookmark '%s' not found. " |
|
2748 | 2748 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2749 | 2749 | |
|
2750 | 2750 | # at this point ps should point to the target dir |
|
2751 | 2751 | if ps: |
|
2752 | 2752 | try: |
|
2753 | 2753 | os.chdir(os.path.expanduser(ps)) |
|
2754 | 2754 | if self.shell.rc.term_title: |
|
2755 | 2755 | #print 'set term title:',self.shell.rc.term_title # dbg |
|
2756 | 2756 | platutils.set_term_title('IPy ' + abbrev_cwd()) |
|
2757 | 2757 | except OSError: |
|
2758 | 2758 | print sys.exc_info()[1] |
|
2759 | 2759 | else: |
|
2760 | 2760 | cwd = os.getcwd() |
|
2761 | 2761 | dhist = self.shell.user_ns['_dh'] |
|
2762 | 2762 | if oldcwd != cwd: |
|
2763 | 2763 | dhist.append(cwd) |
|
2764 | 2764 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2765 | 2765 | |
|
2766 | 2766 | else: |
|
2767 | 2767 | os.chdir(self.shell.home_dir) |
|
2768 | 2768 | if self.shell.rc.term_title: |
|
2769 | 2769 | platutils.set_term_title("IPy ~") |
|
2770 | 2770 | cwd = os.getcwd() |
|
2771 | 2771 | dhist = self.shell.user_ns['_dh'] |
|
2772 | 2772 | |
|
2773 | 2773 | if oldcwd != cwd: |
|
2774 | 2774 | dhist.append(cwd) |
|
2775 | 2775 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2776 | 2776 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2777 | 2777 | print self.shell.user_ns['_dh'][-1] |
|
2778 | 2778 | |
|
2779 | 2779 | |
|
2780 | 2780 | def magic_env(self, parameter_s=''): |
|
2781 | 2781 | """List environment variables.""" |
|
2782 | 2782 | |
|
2783 | 2783 | return os.environ.data |
|
2784 | 2784 | |
|
2785 | 2785 | def magic_pushd(self, parameter_s=''): |
|
2786 | 2786 | """Place the current dir on stack and change directory. |
|
2787 | 2787 | |
|
2788 | 2788 | Usage:\\ |
|
2789 | 2789 | %pushd ['dirname'] |
|
2790 | 2790 | """ |
|
2791 | 2791 | |
|
2792 | 2792 | dir_s = self.shell.dir_stack |
|
2793 | 2793 | tgt = os.path.expanduser(parameter_s) |
|
2794 | 2794 | cwd = os.getcwd().replace(self.home_dir,'~') |
|
2795 | 2795 | if tgt: |
|
2796 | 2796 | self.magic_cd(parameter_s) |
|
2797 | 2797 | dir_s.insert(0,cwd) |
|
2798 | 2798 | return self.magic_dirs() |
|
2799 | 2799 | |
|
2800 | 2800 | def magic_popd(self, parameter_s=''): |
|
2801 | 2801 | """Change to directory popped off the top of the stack. |
|
2802 | 2802 | """ |
|
2803 | 2803 | if not self.shell.dir_stack: |
|
2804 | 2804 | raise UsageError("%popd on empty stack") |
|
2805 | 2805 | top = self.shell.dir_stack.pop(0) |
|
2806 | 2806 | self.magic_cd(top) |
|
2807 | 2807 | print "popd ->",top |
|
2808 | 2808 | |
|
2809 | 2809 | def magic_dirs(self, parameter_s=''): |
|
2810 | 2810 | """Return the current directory stack.""" |
|
2811 | 2811 | |
|
2812 | 2812 | return self.shell.dir_stack |
|
2813 | 2813 | |
|
2814 | 2814 | def magic_dhist(self, parameter_s=''): |
|
2815 | 2815 | """Print your history of visited directories. |
|
2816 | 2816 | |
|
2817 | 2817 | %dhist -> print full history\\ |
|
2818 | 2818 | %dhist n -> print last n entries only\\ |
|
2819 | 2819 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2820 | 2820 | |
|
2821 | 2821 | This history is automatically maintained by the %cd command, and |
|
2822 | 2822 | always available as the global list variable _dh. You can use %cd -<n> |
|
2823 | 2823 | to go to directory number <n>. |
|
2824 | 2824 | |
|
2825 | 2825 | Note that most of time, you should view directory history by entering |
|
2826 | 2826 | cd -<TAB>. |
|
2827 | 2827 | |
|
2828 | 2828 | """ |
|
2829 | 2829 | |
|
2830 | 2830 | dh = self.shell.user_ns['_dh'] |
|
2831 | 2831 | if parameter_s: |
|
2832 | 2832 | try: |
|
2833 | 2833 | args = map(int,parameter_s.split()) |
|
2834 | 2834 | except: |
|
2835 | 2835 | self.arg_err(Magic.magic_dhist) |
|
2836 | 2836 | return |
|
2837 | 2837 | if len(args) == 1: |
|
2838 | 2838 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2839 | 2839 | elif len(args) == 2: |
|
2840 | 2840 | ini,fin = args |
|
2841 | 2841 | else: |
|
2842 | 2842 | self.arg_err(Magic.magic_dhist) |
|
2843 | 2843 | return |
|
2844 | 2844 | else: |
|
2845 | 2845 | ini,fin = 0,len(dh) |
|
2846 | 2846 | nlprint(dh, |
|
2847 | 2847 | header = 'Directory history (kept in _dh)', |
|
2848 | 2848 | start=ini,stop=fin) |
|
2849 | 2849 | |
|
2850 | 2850 | @testdec.skip_doctest |
|
2851 | 2851 | def magic_sc(self, parameter_s=''): |
|
2852 | 2852 | """Shell capture - execute a shell command and capture its output. |
|
2853 | 2853 | |
|
2854 | 2854 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2855 | 2855 | |
|
2856 | 2856 | You should use the form 'var = !command' instead. Example: |
|
2857 | 2857 | |
|
2858 | 2858 | "%sc -l myfiles = ls ~" should now be written as |
|
2859 | 2859 | |
|
2860 | 2860 | "myfiles = !ls ~" |
|
2861 | 2861 | |
|
2862 | 2862 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2863 | 2863 | below. |
|
2864 | 2864 | |
|
2865 | 2865 | -- |
|
2866 | 2866 | %sc [options] varname=command |
|
2867 | 2867 | |
|
2868 | 2868 | IPython will run the given command using commands.getoutput(), and |
|
2869 | 2869 | will then update the user's interactive namespace with a variable |
|
2870 | 2870 | called varname, containing the value of the call. Your command can |
|
2871 | 2871 | contain shell wildcards, pipes, etc. |
|
2872 | 2872 | |
|
2873 | 2873 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2874 | 2874 | supply must follow Python's standard conventions for valid names. |
|
2875 | 2875 | |
|
2876 | 2876 | (A special format without variable name exists for internal use) |
|
2877 | 2877 | |
|
2878 | 2878 | Options: |
|
2879 | 2879 | |
|
2880 | 2880 | -l: list output. Split the output on newlines into a list before |
|
2881 | 2881 | assigning it to the given variable. By default the output is stored |
|
2882 | 2882 | as a single string. |
|
2883 | 2883 | |
|
2884 | 2884 | -v: verbose. Print the contents of the variable. |
|
2885 | 2885 | |
|
2886 | 2886 | In most cases you should not need to split as a list, because the |
|
2887 | 2887 | returned value is a special type of string which can automatically |
|
2888 | 2888 | provide its contents either as a list (split on newlines) or as a |
|
2889 | 2889 | space-separated string. These are convenient, respectively, either |
|
2890 | 2890 | for sequential processing or to be passed to a shell command. |
|
2891 | 2891 | |
|
2892 | 2892 | For example: |
|
2893 | 2893 | |
|
2894 | 2894 | # all-random |
|
2895 | 2895 | |
|
2896 | 2896 | # Capture into variable a |
|
2897 | 2897 | In [1]: sc a=ls *py |
|
2898 | 2898 | |
|
2899 | 2899 | # a is a string with embedded newlines |
|
2900 | 2900 | In [2]: a |
|
2901 | 2901 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
2902 | 2902 | |
|
2903 | 2903 | # which can be seen as a list: |
|
2904 | 2904 | In [3]: a.l |
|
2905 | 2905 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
2906 | 2906 | |
|
2907 | 2907 | # or as a whitespace-separated string: |
|
2908 | 2908 | In [4]: a.s |
|
2909 | 2909 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
2910 | 2910 | |
|
2911 | 2911 | # a.s is useful to pass as a single command line: |
|
2912 | 2912 | In [5]: !wc -l $a.s |
|
2913 | 2913 | 146 setup.py |
|
2914 | 2914 | 130 win32_manual_post_install.py |
|
2915 | 2915 | 276 total |
|
2916 | 2916 | |
|
2917 | 2917 | # while the list form is useful to loop over: |
|
2918 | 2918 | In [6]: for f in a.l: |
|
2919 | 2919 | ...: !wc -l $f |
|
2920 | 2920 | ...: |
|
2921 | 2921 | 146 setup.py |
|
2922 | 2922 | 130 win32_manual_post_install.py |
|
2923 | 2923 | |
|
2924 | 2924 | Similiarly, the lists returned by the -l option are also special, in |
|
2925 | 2925 | the sense that you can equally invoke the .s attribute on them to |
|
2926 | 2926 | automatically get a whitespace-separated string from their contents: |
|
2927 | 2927 | |
|
2928 | 2928 | In [7]: sc -l b=ls *py |
|
2929 | 2929 | |
|
2930 | 2930 | In [8]: b |
|
2931 | 2931 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
2932 | 2932 | |
|
2933 | 2933 | In [9]: b.s |
|
2934 | 2934 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
2935 | 2935 | |
|
2936 | 2936 | In summary, both the lists and strings used for ouptut capture have |
|
2937 | 2937 | the following special attributes: |
|
2938 | 2938 | |
|
2939 | 2939 | .l (or .list) : value as list. |
|
2940 | 2940 | .n (or .nlstr): value as newline-separated string. |
|
2941 | 2941 | .s (or .spstr): value as space-separated string. |
|
2942 | 2942 | """ |
|
2943 | 2943 | |
|
2944 | 2944 | opts,args = self.parse_options(parameter_s,'lv') |
|
2945 | 2945 | # Try to get a variable name and command to run |
|
2946 | 2946 | try: |
|
2947 | 2947 | # the variable name must be obtained from the parse_options |
|
2948 | 2948 | # output, which uses shlex.split to strip options out. |
|
2949 | 2949 | var,_ = args.split('=',1) |
|
2950 | 2950 | var = var.strip() |
|
2951 | 2951 | # But the the command has to be extracted from the original input |
|
2952 | 2952 | # parameter_s, not on what parse_options returns, to avoid the |
|
2953 | 2953 | # quote stripping which shlex.split performs on it. |
|
2954 | 2954 | _,cmd = parameter_s.split('=',1) |
|
2955 | 2955 | except ValueError: |
|
2956 | 2956 | var,cmd = '','' |
|
2957 | 2957 | # If all looks ok, proceed |
|
2958 | 2958 | out,err = self.shell.getoutputerror(cmd) |
|
2959 | 2959 | if err: |
|
2960 | 2960 | print >> Term.cerr,err |
|
2961 | 2961 | if opts.has_key('l'): |
|
2962 | 2962 | out = SList(out.split('\n')) |
|
2963 | 2963 | else: |
|
2964 | 2964 | out = LSString(out) |
|
2965 | 2965 | if opts.has_key('v'): |
|
2966 | 2966 | print '%s ==\n%s' % (var,pformat(out)) |
|
2967 | 2967 | if var: |
|
2968 | 2968 | self.shell.user_ns.update({var:out}) |
|
2969 | 2969 | else: |
|
2970 | 2970 | return out |
|
2971 | 2971 | |
|
2972 | 2972 | def magic_sx(self, parameter_s=''): |
|
2973 | 2973 | """Shell execute - run a shell command and capture its output. |
|
2974 | 2974 | |
|
2975 | 2975 | %sx command |
|
2976 | 2976 | |
|
2977 | 2977 | IPython will run the given command using commands.getoutput(), and |
|
2978 | 2978 | return the result formatted as a list (split on '\\n'). Since the |
|
2979 | 2979 | output is _returned_, it will be stored in ipython's regular output |
|
2980 | 2980 | cache Out[N] and in the '_N' automatic variables. |
|
2981 | 2981 | |
|
2982 | 2982 | Notes: |
|
2983 | 2983 | |
|
2984 | 2984 | 1) If an input line begins with '!!', then %sx is automatically |
|
2985 | 2985 | invoked. That is, while: |
|
2986 | 2986 | !ls |
|
2987 | 2987 | causes ipython to simply issue system('ls'), typing |
|
2988 | 2988 | !!ls |
|
2989 | 2989 | is a shorthand equivalent to: |
|
2990 | 2990 | %sx ls |
|
2991 | 2991 | |
|
2992 | 2992 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
2993 | 2993 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
2994 | 2994 | to process line-oriented shell output via further python commands. |
|
2995 | 2995 | %sc is meant to provide much finer control, but requires more |
|
2996 | 2996 | typing. |
|
2997 | 2997 | |
|
2998 | 2998 | 3) Just like %sc -l, this is a list with special attributes: |
|
2999 | 2999 | |
|
3000 | 3000 | .l (or .list) : value as list. |
|
3001 | 3001 | .n (or .nlstr): value as newline-separated string. |
|
3002 | 3002 | .s (or .spstr): value as whitespace-separated string. |
|
3003 | 3003 | |
|
3004 | 3004 | This is very useful when trying to use such lists as arguments to |
|
3005 | 3005 | system commands.""" |
|
3006 | 3006 | |
|
3007 | 3007 | if parameter_s: |
|
3008 | 3008 | out,err = self.shell.getoutputerror(parameter_s) |
|
3009 | 3009 | if err: |
|
3010 | 3010 | print >> Term.cerr,err |
|
3011 | 3011 | return SList(out.split('\n')) |
|
3012 | 3012 | |
|
3013 | 3013 | def magic_bg(self, parameter_s=''): |
|
3014 | 3014 | """Run a job in the background, in a separate thread. |
|
3015 | 3015 | |
|
3016 | 3016 | For example, |
|
3017 | 3017 | |
|
3018 | 3018 | %bg myfunc(x,y,z=1) |
|
3019 | 3019 | |
|
3020 | 3020 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the |
|
3021 | 3021 | execution starts, a message will be printed indicating the job |
|
3022 | 3022 | number. If your job number is 5, you can use |
|
3023 | 3023 | |
|
3024 | 3024 | myvar = jobs.result(5) or myvar = jobs[5].result |
|
3025 | 3025 | |
|
3026 | 3026 | to assign this result to variable 'myvar'. |
|
3027 | 3027 | |
|
3028 | 3028 | IPython has a job manager, accessible via the 'jobs' object. You can |
|
3029 | 3029 | type jobs? to get more information about it, and use jobs.<TAB> to see |
|
3030 | 3030 | its attributes. All attributes not starting with an underscore are |
|
3031 | 3031 | meant for public use. |
|
3032 | 3032 | |
|
3033 | 3033 | In particular, look at the jobs.new() method, which is used to create |
|
3034 | 3034 | new jobs. This magic %bg function is just a convenience wrapper |
|
3035 | 3035 | around jobs.new(), for expression-based jobs. If you want to create a |
|
3036 | 3036 | new job with an explicit function object and arguments, you must call |
|
3037 | 3037 | jobs.new() directly. |
|
3038 | 3038 | |
|
3039 | 3039 | The jobs.new docstring also describes in detail several important |
|
3040 | 3040 | caveats associated with a thread-based model for background job |
|
3041 | 3041 | execution. Type jobs.new? for details. |
|
3042 | 3042 | |
|
3043 | 3043 | You can check the status of all jobs with jobs.status(). |
|
3044 | 3044 | |
|
3045 | 3045 | The jobs variable is set by IPython into the Python builtin namespace. |
|
3046 | 3046 | If you ever declare a variable named 'jobs', you will shadow this |
|
3047 | 3047 | name. You can either delete your global jobs variable to regain |
|
3048 | 3048 | access to the job manager, or make a new name and assign it manually |
|
3049 | 3049 | to the manager (stored in IPython's namespace). For example, to |
|
3050 | 3050 | assign the job manager to the Jobs name, use: |
|
3051 | 3051 | |
|
3052 | 3052 | Jobs = __builtins__.jobs""" |
|
3053 | 3053 | |
|
3054 | 3054 | self.shell.jobs.new(parameter_s,self.shell.user_ns) |
|
3055 | 3055 | |
|
3056 | 3056 | def magic_r(self, parameter_s=''): |
|
3057 | 3057 | """Repeat previous input. |
|
3058 | 3058 | |
|
3059 | 3059 | Note: Consider using the more powerfull %rep instead! |
|
3060 | 3060 | |
|
3061 | 3061 | If given an argument, repeats the previous command which starts with |
|
3062 | 3062 | the same string, otherwise it just repeats the previous input. |
|
3063 | 3063 | |
|
3064 | 3064 | Shell escaped commands (with ! as first character) are not recognized |
|
3065 | 3065 | by this system, only pure python code and magic commands. |
|
3066 | 3066 | """ |
|
3067 | 3067 | |
|
3068 | 3068 | start = parameter_s.strip() |
|
3069 | 3069 | esc_magic = self.shell.ESC_MAGIC |
|
3070 | 3070 | # Identify magic commands even if automagic is on (which means |
|
3071 | 3071 | # the in-memory version is different from that typed by the user). |
|
3072 | 3072 | if self.shell.rc.automagic: |
|
3073 | 3073 | start_magic = esc_magic+start |
|
3074 | 3074 | else: |
|
3075 | 3075 | start_magic = start |
|
3076 | 3076 | # Look through the input history in reverse |
|
3077 | 3077 | for n in range(len(self.shell.input_hist)-2,0,-1): |
|
3078 | 3078 | input = self.shell.input_hist[n] |
|
3079 | 3079 | # skip plain 'r' lines so we don't recurse to infinity |
|
3080 | 3080 | if input != '_ip.magic("r")\n' and \ |
|
3081 | 3081 | (input.startswith(start) or input.startswith(start_magic)): |
|
3082 | 3082 | #print 'match',`input` # dbg |
|
3083 | 3083 | print 'Executing:',input, |
|
3084 | 3084 | self.shell.runlines(input) |
|
3085 | 3085 | return |
|
3086 | 3086 | print 'No previous input matching `%s` found.' % start |
|
3087 | 3087 | |
|
3088 | 3088 | |
|
3089 | 3089 | def magic_bookmark(self, parameter_s=''): |
|
3090 | 3090 | """Manage IPython's bookmark system. |
|
3091 | 3091 | |
|
3092 | 3092 | %bookmark <name> - set bookmark to current dir |
|
3093 | 3093 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3094 | 3094 | %bookmark -l - list all bookmarks |
|
3095 | 3095 | %bookmark -d <name> - remove bookmark |
|
3096 | 3096 | %bookmark -r - remove all bookmarks |
|
3097 | 3097 | |
|
3098 | 3098 | You can later on access a bookmarked folder with: |
|
3099 | 3099 | %cd -b <name> |
|
3100 | 3100 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3101 | 3101 | there is such a bookmark defined. |
|
3102 | 3102 | |
|
3103 | 3103 | Your bookmarks persist through IPython sessions, but they are |
|
3104 | 3104 | associated with each profile.""" |
|
3105 | 3105 | |
|
3106 | 3106 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3107 | 3107 | if len(args) > 2: |
|
3108 | 3108 | raise UsageError("%bookmark: too many arguments") |
|
3109 | 3109 | |
|
3110 | 3110 | bkms = self.db.get('bookmarks',{}) |
|
3111 | 3111 | |
|
3112 | 3112 | if opts.has_key('d'): |
|
3113 | 3113 | try: |
|
3114 | 3114 | todel = args[0] |
|
3115 | 3115 | except IndexError: |
|
3116 | 3116 | raise UsageError( |
|
3117 | 3117 | "%bookmark -d: must provide a bookmark to delete") |
|
3118 | 3118 | else: |
|
3119 | 3119 | try: |
|
3120 | 3120 | del bkms[todel] |
|
3121 | 3121 | except KeyError: |
|
3122 | 3122 | raise UsageError( |
|
3123 | 3123 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3124 | 3124 | |
|
3125 | 3125 | elif opts.has_key('r'): |
|
3126 | 3126 | bkms = {} |
|
3127 | 3127 | elif opts.has_key('l'): |
|
3128 | 3128 | bks = bkms.keys() |
|
3129 | 3129 | bks.sort() |
|
3130 | 3130 | if bks: |
|
3131 | 3131 | size = max(map(len,bks)) |
|
3132 | 3132 | else: |
|
3133 | 3133 | size = 0 |
|
3134 | 3134 | fmt = '%-'+str(size)+'s -> %s' |
|
3135 | 3135 | print 'Current bookmarks:' |
|
3136 | 3136 | for bk in bks: |
|
3137 | 3137 | print fmt % (bk,bkms[bk]) |
|
3138 | 3138 | else: |
|
3139 | 3139 | if not args: |
|
3140 | 3140 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3141 | 3141 | elif len(args)==1: |
|
3142 | 3142 | bkms[args[0]] = os.getcwd() |
|
3143 | 3143 | elif len(args)==2: |
|
3144 | 3144 | bkms[args[0]] = args[1] |
|
3145 | 3145 | self.db['bookmarks'] = bkms |
|
3146 | 3146 | |
|
3147 | 3147 | def magic_pycat(self, parameter_s=''): |
|
3148 | 3148 | """Show a syntax-highlighted file through a pager. |
|
3149 | 3149 | |
|
3150 | 3150 | This magic is similar to the cat utility, but it will assume the file |
|
3151 | 3151 | to be Python source and will show it with syntax highlighting. """ |
|
3152 | 3152 | |
|
3153 | 3153 | try: |
|
3154 | 3154 | filename = get_py_filename(parameter_s) |
|
3155 | 3155 | cont = file_read(filename) |
|
3156 | 3156 | except IOError: |
|
3157 | 3157 | try: |
|
3158 | 3158 | cont = eval(parameter_s,self.user_ns) |
|
3159 | 3159 | except NameError: |
|
3160 | 3160 | cont = None |
|
3161 | 3161 | if cont is None: |
|
3162 | 3162 | print "Error: no such file or variable" |
|
3163 | 3163 | return |
|
3164 | 3164 | |
|
3165 | 3165 | page(self.shell.pycolorize(cont), |
|
3166 | 3166 | screen_lines=self.shell.rc.screen_length) |
|
3167 | 3167 | |
|
3168 | 3168 | def magic_cpaste(self, parameter_s=''): |
|
3169 | 3169 | """Allows you to paste & execute a pre-formatted code block from clipboard. |
|
3170 | 3170 | |
|
3171 | 3171 | You must terminate the block with '--' (two minus-signs) alone on the |
|
3172 | 3172 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' |
|
3173 | 3173 | is the new sentinel for this operation) |
|
3174 | 3174 | |
|
3175 | 3175 | The block is dedented prior to execution to enable execution of method |
|
3176 | 3176 | definitions. '>' and '+' characters at the beginning of a line are |
|
3177 | 3177 | ignored, to allow pasting directly from e-mails, diff files and |
|
3178 | 3178 | doctests (the '...' continuation prompt is also stripped). The |
|
3179 | 3179 | executed block is also assigned to variable named 'pasted_block' for |
|
3180 | 3180 | later editing with '%edit pasted_block'. |
|
3181 | 3181 | |
|
3182 | 3182 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
3183 | 3183 | This assigns the pasted block to variable 'foo' as string, without |
|
3184 | 3184 | dedenting or executing it (preceding >>> and + is still stripped) |
|
3185 | 3185 | |
|
3186 | 3186 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
3187 | 3187 | Just press enter and type -- (and press enter again) and the block |
|
3188 | 3188 | will be what was just pasted. |
|
3189 | 3189 | |
|
3190 | 3190 | IPython statements (magics, shell escapes) are not supported (yet). |
|
3191 | 3191 | """ |
|
3192 | 3192 | opts,args = self.parse_options(parameter_s,'s:',mode='string') |
|
3193 | 3193 | par = args.strip() |
|
3194 | 3194 | sentinel = opts.get('s','--') |
|
3195 | 3195 | |
|
3196 | 3196 | # Regular expressions that declare text we strip from the input: |
|
3197 | 3197 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt |
|
3198 | 3198 | r'^\s*(\s?>)+', # Python input prompt |
|
3199 | 3199 | r'^\s*\.{3,}', # Continuation prompts |
|
3200 | 3200 | r'^\++', |
|
3201 | 3201 | ] |
|
3202 | 3202 | |
|
3203 | 3203 | strip_from_start = map(re.compile,strip_re) |
|
3204 | 3204 | |
|
3205 | 3205 | from IPython import iplib |
|
3206 | 3206 | lines = [] |
|
3207 | 3207 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3208 | 3208 | while 1: |
|
3209 | 3209 | l = iplib.raw_input_original(':') |
|
3210 | 3210 | if l ==sentinel: |
|
3211 | 3211 | break |
|
3212 | 3212 | |
|
3213 | 3213 | for pat in strip_from_start: |
|
3214 | 3214 | l = pat.sub('',l) |
|
3215 | 3215 | lines.append(l) |
|
3216 | 3216 | |
|
3217 | 3217 | block = "\n".join(lines) + '\n' |
|
3218 | 3218 | #print "block:\n",block |
|
3219 | 3219 | if not par: |
|
3220 | 3220 | b = textwrap.dedent(block) |
|
3221 | 3221 | exec b in self.user_ns |
|
3222 | 3222 | self.user_ns['pasted_block'] = b |
|
3223 | 3223 | else: |
|
3224 | 3224 | self.user_ns[par] = SList(block.splitlines()) |
|
3225 | 3225 | print "Block assigned to '%s'" % par |
|
3226 | 3226 | |
|
3227 | 3227 | def magic_quickref(self,arg): |
|
3228 | 3228 | """ Show a quick reference sheet """ |
|
3229 | 3229 | import IPython.usage |
|
3230 | 3230 | qr = IPython.usage.quick_reference + self.magic_magic('-brief') |
|
3231 | 3231 | |
|
3232 | 3232 | page(qr) |
|
3233 | 3233 | |
|
3234 | 3234 | def magic_upgrade(self,arg): |
|
3235 | 3235 | """ Upgrade your IPython installation |
|
3236 | 3236 | |
|
3237 | 3237 | This will copy the config files that don't yet exist in your |
|
3238 | 3238 | ipython dir from the system config dir. Use this after upgrading |
|
3239 | 3239 | IPython if you don't wish to delete your .ipython dir. |
|
3240 | 3240 | |
|
3241 | 3241 | Call with -nolegacy to get rid of ipythonrc* files (recommended for |
|
3242 | 3242 | new users) |
|
3243 | 3243 | |
|
3244 | 3244 | """ |
|
3245 | 3245 | ip = self.getapi() |
|
3246 | 3246 | ipinstallation = path(IPython.__file__).dirname() |
|
3247 | 3247 | upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py') |
|
3248 | 3248 | src_config = ipinstallation / 'UserConfig' |
|
3249 | 3249 | userdir = path(ip.options.ipythondir) |
|
3250 | 3250 | cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir) |
|
3251 | 3251 | print ">",cmd |
|
3252 | 3252 | shell(cmd) |
|
3253 | 3253 | if arg == '-nolegacy': |
|
3254 | 3254 | legacy = userdir.files('ipythonrc*') |
|
3255 | 3255 | print "Nuking legacy files:",legacy |
|
3256 | 3256 | |
|
3257 | 3257 | [p.remove() for p in legacy] |
|
3258 | 3258 | suffix = (sys.platform == 'win32' and '.ini' or '') |
|
3259 | 3259 | (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n') |
|
3260 | 3260 | |
|
3261 | 3261 | |
|
3262 | 3262 | def magic_doctest_mode(self,parameter_s=''): |
|
3263 | 3263 | """Toggle doctest mode on and off. |
|
3264 | 3264 | |
|
3265 | 3265 | This mode allows you to toggle the prompt behavior between normal |
|
3266 | 3266 | IPython prompts and ones that are as similar to the default IPython |
|
3267 | 3267 | interpreter as possible. |
|
3268 | 3268 | |
|
3269 | 3269 | It also supports the pasting of code snippets that have leading '>>>' |
|
3270 | 3270 | and '...' prompts in them. This means that you can paste doctests from |
|
3271 | 3271 | files or docstrings (even if they have leading whitespace), and the |
|
3272 | 3272 | code will execute correctly. You can then use '%history -tn' to see |
|
3273 | 3273 | the translated history without line numbers; this will give you the |
|
3274 | 3274 | input after removal of all the leading prompts and whitespace, which |
|
3275 | 3275 | can be pasted back into an editor. |
|
3276 | 3276 | |
|
3277 | 3277 | With these features, you can switch into this mode easily whenever you |
|
3278 | 3278 | need to do testing and changes to doctests, without having to leave |
|
3279 | 3279 | your existing IPython session. |
|
3280 | 3280 | """ |
|
3281 | 3281 | |
|
3282 | 3282 | # XXX - Fix this to have cleaner activate/deactivate calls. |
|
3283 | 3283 | from IPython.Extensions import InterpreterPasteInput as ipaste |
|
3284 | 3284 | from IPython.ipstruct import Struct |
|
3285 | 3285 | |
|
3286 | 3286 | # Shorthands |
|
3287 | 3287 | shell = self.shell |
|
3288 | 3288 | oc = shell.outputcache |
|
3289 | 3289 | rc = shell.rc |
|
3290 | 3290 | meta = shell.meta |
|
3291 | 3291 | # dstore is a data store kept in the instance metadata bag to track any |
|
3292 | 3292 | # changes we make, so we can undo them later. |
|
3293 | 3293 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3294 | 3294 | save_dstore = dstore.setdefault |
|
3295 | 3295 | |
|
3296 | 3296 | # save a few values we'll need to recover later |
|
3297 | 3297 | mode = save_dstore('mode',False) |
|
3298 | 3298 | save_dstore('rc_pprint',rc.pprint) |
|
3299 | 3299 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3300 | 3300 | save_dstore('rc_separate_out',rc.separate_out) |
|
3301 | 3301 | save_dstore('rc_separate_out2',rc.separate_out2) |
|
3302 | 3302 | save_dstore('rc_prompts_pad_left',rc.prompts_pad_left) |
|
3303 | 3303 | save_dstore('rc_separate_in',rc.separate_in) |
|
3304 | 3304 | |
|
3305 | 3305 | if mode == False: |
|
3306 | 3306 | # turn on |
|
3307 | 3307 | ipaste.activate_prefilter() |
|
3308 | 3308 | |
|
3309 | 3309 | oc.prompt1.p_template = '>>> ' |
|
3310 | 3310 | oc.prompt2.p_template = '... ' |
|
3311 | 3311 | oc.prompt_out.p_template = '' |
|
3312 | 3312 | |
|
3313 | 3313 | # Prompt separators like plain python |
|
3314 | 3314 | oc.input_sep = oc.prompt1.sep = '' |
|
3315 | 3315 | oc.output_sep = '' |
|
3316 | 3316 | oc.output_sep2 = '' |
|
3317 | 3317 | |
|
3318 | 3318 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3319 | 3319 | oc.prompt_out.pad_left = False |
|
3320 | 3320 | |
|
3321 | 3321 | rc.pprint = False |
|
3322 | 3322 | |
|
3323 | 3323 | shell.magic_xmode('Plain') |
|
3324 | 3324 | |
|
3325 | 3325 | else: |
|
3326 | 3326 | # turn off |
|
3327 | 3327 | ipaste.deactivate_prefilter() |
|
3328 | 3328 | |
|
3329 | 3329 | oc.prompt1.p_template = rc.prompt_in1 |
|
3330 | 3330 | oc.prompt2.p_template = rc.prompt_in2 |
|
3331 | 3331 | oc.prompt_out.p_template = rc.prompt_out |
|
3332 | 3332 | |
|
3333 | 3333 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in |
|
3334 | 3334 | |
|
3335 | 3335 | oc.output_sep = dstore.rc_separate_out |
|
3336 | 3336 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3337 | 3337 | |
|
3338 | 3338 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3339 | 3339 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3340 | 3340 | |
|
3341 | 3341 | rc.pprint = dstore.rc_pprint |
|
3342 | 3342 | |
|
3343 | 3343 | shell.magic_xmode(dstore.xmode) |
|
3344 | 3344 | |
|
3345 | 3345 | # Store new mode and inform |
|
3346 | 3346 | dstore.mode = bool(1-int(mode)) |
|
3347 | 3347 | print 'Doctest mode is:', |
|
3348 | 3348 | print ['OFF','ON'][dstore.mode] |
|
3349 | 3349 | |
|
3350 | 3350 | # end Magic |
@@ -1,560 +1,560 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | # -*- test-case-name: IPython.frontend.cocoa.tests.test_cocoa_frontend -*- |
|
3 | 3 | |
|
4 | 4 | """PyObjC classes to provide a Cocoa frontend to the |
|
5 | 5 | IPython.kernel.engineservice.IEngineBase. |
|
6 | 6 | |
|
7 | 7 | To add an IPython interpreter to a cocoa app, instantiate an |
|
8 | 8 | IPythonCocoaController in a XIB and connect its textView outlet to an |
|
9 | 9 | NSTextView instance in your UI. That's it. |
|
10 | 10 | |
|
11 | 11 | Author: Barry Wark |
|
12 | 12 | """ |
|
13 | 13 | |
|
14 | 14 | __docformat__ = "restructuredtext en" |
|
15 | 15 | |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | # Copyright (C) 2008 The IPython Development Team |
|
18 | 18 | # |
|
19 | 19 | # Distributed under the terms of the BSD License. The full license is in |
|
20 | 20 | # the file COPYING, distributed as part of this software. |
|
21 | 21 | #----------------------------------------------------------------------------- |
|
22 | 22 | |
|
23 | 23 | #----------------------------------------------------------------------------- |
|
24 | 24 | # Imports |
|
25 | 25 | #----------------------------------------------------------------------------- |
|
26 | 26 | |
|
27 | 27 | import sys |
|
28 | 28 | import objc |
|
29 | 29 | import uuid |
|
30 | 30 | |
|
31 | 31 | from Foundation import NSObject, NSMutableArray, NSMutableDictionary,\ |
|
32 | 32 | NSLog, NSNotificationCenter, NSMakeRange,\ |
|
33 | 33 | NSLocalizedString, NSIntersectionRange,\ |
|
34 | 34 | NSString, NSAutoreleasePool |
|
35 | 35 | |
|
36 | 36 | from AppKit import NSApplicationWillTerminateNotification, NSBeep,\ |
|
37 | 37 | NSTextView, NSRulerView, NSVerticalRuler |
|
38 | 38 | |
|
39 | 39 | from pprint import saferepr |
|
40 | 40 | |
|
41 | 41 | import IPython |
|
42 | 42 | from IPython.kernel.engineservice import ThreadedEngineService |
|
43 | from IPython.frontend.frontendbase import AsyncFrontEndBase | |
|
43 | from IPython.frontend.asyncfrontendbase import AsyncFrontEndBase | |
|
44 | 44 | |
|
45 | 45 | from twisted.internet.threads import blockingCallFromThread |
|
46 | 46 | from twisted.python.failure import Failure |
|
47 | 47 | |
|
48 | 48 | #----------------------------------------------------------------------------- |
|
49 | 49 | # Classes to implement the Cocoa frontend |
|
50 | 50 | #----------------------------------------------------------------------------- |
|
51 | 51 | |
|
52 | 52 | # TODO: |
|
53 | 53 | # 1. use MultiEngineClient and out-of-process engine rather than |
|
54 | 54 | # ThreadedEngineService? |
|
55 | 55 | # 2. integrate Xgrid launching of engines |
|
56 | 56 | |
|
57 | 57 | class AutoreleasePoolWrappedThreadedEngineService(ThreadedEngineService): |
|
58 | 58 | """Wrap all blocks in an NSAutoreleasePool""" |
|
59 | 59 | |
|
60 | 60 | def wrapped_execute(self, msg, lines): |
|
61 | 61 | """wrapped_execute""" |
|
62 | 62 | try: |
|
63 | 63 | p = NSAutoreleasePool.alloc().init() |
|
64 | 64 | result = super(AutoreleasePoolWrappedThreadedEngineService, |
|
65 | 65 | self).wrapped_execute(msg, lines) |
|
66 | 66 | finally: |
|
67 | 67 | p.drain() |
|
68 | 68 | |
|
69 | 69 | return result |
|
70 | 70 | |
|
71 | 71 | |
|
72 | 72 | |
|
73 | 73 | class Cell(NSObject): |
|
74 | 74 | """ |
|
75 | 75 | Representation of the prompts, input and output of a cell in the |
|
76 | 76 | frontend |
|
77 | 77 | """ |
|
78 | 78 | |
|
79 | 79 | blockNumber = objc.ivar().unsigned_long() |
|
80 | 80 | blockID = objc.ivar() |
|
81 | 81 | inputBlock = objc.ivar() |
|
82 | 82 | output = objc.ivar() |
|
83 | 83 | |
|
84 | 84 | |
|
85 | 85 | |
|
86 | 86 | class CellBlock(object): |
|
87 | 87 | """ |
|
88 | 88 | Storage for information about text ranges relating to a single cell |
|
89 | 89 | """ |
|
90 | 90 | |
|
91 | 91 | |
|
92 | 92 | def __init__(self, inputPromptRange, inputRange=None, outputPromptRange=None, |
|
93 | 93 | outputRange=None): |
|
94 | 94 | super(CellBlock, self).__init__() |
|
95 | 95 | self.inputPromptRange = inputPromptRange |
|
96 | 96 | self.inputRange = inputRange |
|
97 | 97 | self.outputPromptRange = outputPromptRange |
|
98 | 98 | self.outputRange = outputRange |
|
99 | 99 | |
|
100 | 100 | def update_ranges_for_insertion(self, text, textRange): |
|
101 | 101 | """Update ranges for text insertion at textRange""" |
|
102 | 102 | |
|
103 | 103 | for r in [self.inputPromptRange,self.inputRange, |
|
104 | 104 | self.outputPromptRange, self.outputRange]: |
|
105 | 105 | if(r == None): |
|
106 | 106 | continue |
|
107 | 107 | intersection = NSIntersectionRange(r,textRange) |
|
108 | 108 | if(intersection.length == 0): #ranges don't intersect |
|
109 | 109 | if r.location >= textRange.location: |
|
110 | 110 | r.location += len(text) |
|
111 | 111 | else: #ranges intersect |
|
112 | 112 | if(r.location > textRange.location): |
|
113 | 113 | offset = len(text) - intersection.length |
|
114 | 114 | r.length -= offset |
|
115 | 115 | r.location += offset |
|
116 | 116 | elif(r.location == textRange.location): |
|
117 | 117 | r.length += len(text) - intersection.length |
|
118 | 118 | else: |
|
119 | 119 | r.length -= intersection.length |
|
120 | 120 | |
|
121 | 121 | |
|
122 | 122 | def update_ranges_for_deletion(self, textRange): |
|
123 | 123 | """Update ranges for text deletion at textRange""" |
|
124 | 124 | |
|
125 | 125 | for r in [self.inputPromptRange,self.inputRange, |
|
126 | 126 | self.outputPromptRange, self.outputRange]: |
|
127 | 127 | if(r==None): |
|
128 | 128 | continue |
|
129 | 129 | intersection = NSIntersectionRange(r, textRange) |
|
130 | 130 | if(intersection.length == 0): #ranges don't intersect |
|
131 | 131 | if r.location >= textRange.location: |
|
132 | 132 | r.location -= textRange.length |
|
133 | 133 | else: #ranges intersect |
|
134 | 134 | if(r.location > textRange.location): |
|
135 | 135 | offset = intersection.length |
|
136 | 136 | r.length -= offset |
|
137 | 137 | r.location += offset |
|
138 | 138 | elif(r.location == textRange.location): |
|
139 | 139 | r.length += intersection.length |
|
140 | 140 | else: |
|
141 | 141 | r.length -= intersection.length |
|
142 | 142 | |
|
143 | 143 | def __repr__(self): |
|
144 | 144 | return 'CellBlock('+ str((self.inputPromptRange, |
|
145 | 145 | self.inputRange, |
|
146 | 146 | self.outputPromptRange, |
|
147 | 147 | self.outputRange)) + ')' |
|
148 | 148 | |
|
149 | 149 | |
|
150 | 150 | |
|
151 | 151 | |
|
152 | 152 | class IPythonCocoaController(NSObject, AsyncFrontEndBase): |
|
153 | 153 | userNS = objc.ivar() #mirror of engine.user_ns (key=>str(value)) |
|
154 | 154 | waitingForEngine = objc.ivar().bool() |
|
155 | 155 | textView = objc.IBOutlet() |
|
156 | 156 | |
|
157 | 157 | def init(self): |
|
158 | 158 | self = super(IPythonCocoaController, self).init() |
|
159 | 159 | AsyncFrontEndBase.__init__(self, |
|
160 | 160 | engine=AutoreleasePoolWrappedThreadedEngineService()) |
|
161 | 161 | if(self != None): |
|
162 | 162 | self._common_init() |
|
163 | 163 | |
|
164 | 164 | return self |
|
165 | 165 | |
|
166 | 166 | def _common_init(self): |
|
167 | 167 | """_common_init""" |
|
168 | 168 | |
|
169 | 169 | self.userNS = NSMutableDictionary.dictionary() |
|
170 | 170 | self.waitingForEngine = False |
|
171 | 171 | |
|
172 | 172 | self.lines = {} |
|
173 | 173 | self.tabSpaces = 4 |
|
174 | 174 | self.tabUsesSpaces = True |
|
175 | 175 | self.currentBlockID = self.next_block_ID() |
|
176 | 176 | self.blockRanges = {} # blockID=>CellBlock |
|
177 | 177 | |
|
178 | 178 | |
|
179 | 179 | def awakeFromNib(self): |
|
180 | 180 | """awakeFromNib""" |
|
181 | 181 | |
|
182 | 182 | self._common_init() |
|
183 | 183 | |
|
184 | 184 | # Start the IPython engine |
|
185 | 185 | self.engine.startService() |
|
186 | 186 | NSLog('IPython engine started') |
|
187 | 187 | |
|
188 | 188 | # Register for app termination |
|
189 | 189 | nc = NSNotificationCenter.defaultCenter() |
|
190 | 190 | nc.addObserver_selector_name_object_( |
|
191 | 191 | self, |
|
192 | 192 | 'appWillTerminate:', |
|
193 | 193 | NSApplicationWillTerminateNotification, |
|
194 | 194 | None) |
|
195 | 195 | |
|
196 | 196 | self.textView.setDelegate_(self) |
|
197 | 197 | self.textView.enclosingScrollView().setHasVerticalRuler_(True) |
|
198 | 198 | r = NSRulerView.alloc().initWithScrollView_orientation_( |
|
199 | 199 | self.textView.enclosingScrollView(), |
|
200 | 200 | NSVerticalRuler) |
|
201 | 201 | self.verticalRulerView = r |
|
202 | 202 | self.verticalRulerView.setClientView_(self.textView) |
|
203 | 203 | self._start_cli_banner() |
|
204 | 204 | self.start_new_block() |
|
205 | 205 | |
|
206 | 206 | |
|
207 | 207 | def appWillTerminate_(self, notification): |
|
208 | 208 | """appWillTerminate""" |
|
209 | 209 | |
|
210 | 210 | self.engine.stopService() |
|
211 | 211 | |
|
212 | 212 | |
|
213 | 213 | def complete(self, token): |
|
214 | 214 | """Complete token in engine's user_ns |
|
215 | 215 | |
|
216 | 216 | Parameters |
|
217 | 217 | ---------- |
|
218 | 218 | token : string |
|
219 | 219 | |
|
220 | 220 | Result |
|
221 | 221 | ------ |
|
222 | 222 | Deferred result of |
|
223 | 223 | IPython.kernel.engineservice.IEngineBase.complete |
|
224 | 224 | """ |
|
225 | 225 | |
|
226 | 226 | return self.engine.complete(token) |
|
227 | 227 | |
|
228 | 228 | |
|
229 | 229 | def execute(self, block, blockID=None): |
|
230 | 230 | self.waitingForEngine = True |
|
231 | 231 | self.willChangeValueForKey_('commandHistory') |
|
232 | 232 | d = super(IPythonCocoaController, self).execute(block, |
|
233 | 233 | blockID) |
|
234 | 234 | d.addBoth(self._engine_done) |
|
235 | 235 | d.addCallback(self._update_user_ns) |
|
236 | 236 | |
|
237 | 237 | return d |
|
238 | 238 | |
|
239 | 239 | |
|
240 | 240 | def push_(self, namespace): |
|
241 | 241 | """Push dictionary of key=>values to python namespace""" |
|
242 | 242 | |
|
243 | 243 | self.waitingForEngine = True |
|
244 | 244 | self.willChangeValueForKey_('commandHistory') |
|
245 | 245 | d = self.engine.push(namespace) |
|
246 | 246 | d.addBoth(self._engine_done) |
|
247 | 247 | d.addCallback(self._update_user_ns) |
|
248 | 248 | |
|
249 | 249 | |
|
250 | 250 | def pull_(self, keys): |
|
251 | 251 | """Pull keys from python namespace""" |
|
252 | 252 | |
|
253 | 253 | self.waitingForEngine = True |
|
254 | 254 | result = blockingCallFromThread(self.engine.pull, keys) |
|
255 | 255 | self.waitingForEngine = False |
|
256 | 256 | |
|
257 | 257 | @objc.signature('v@:@I') |
|
258 | 258 | def executeFileAtPath_encoding_(self, path, encoding): |
|
259 | 259 | """Execute file at path in an empty namespace. Update the engine |
|
260 | 260 | user_ns with the resulting locals.""" |
|
261 | 261 | |
|
262 | 262 | lines,err = NSString.stringWithContentsOfFile_encoding_error_( |
|
263 | 263 | path, |
|
264 | 264 | encoding, |
|
265 | 265 | None) |
|
266 | 266 | self.engine.execute(lines) |
|
267 | 267 | |
|
268 | 268 | |
|
269 | 269 | def _engine_done(self, x): |
|
270 | 270 | self.waitingForEngine = False |
|
271 | 271 | self.didChangeValueForKey_('commandHistory') |
|
272 | 272 | return x |
|
273 | 273 | |
|
274 | 274 | def _update_user_ns(self, result): |
|
275 | 275 | """Update self.userNS from self.engine's namespace""" |
|
276 | 276 | d = self.engine.keys() |
|
277 | 277 | d.addCallback(self._get_engine_namespace_values_for_keys) |
|
278 | 278 | |
|
279 | 279 | return result |
|
280 | 280 | |
|
281 | 281 | |
|
282 | 282 | def _get_engine_namespace_values_for_keys(self, keys): |
|
283 | 283 | d = self.engine.pull(keys) |
|
284 | 284 | d.addCallback(self._store_engine_namespace_values, keys=keys) |
|
285 | 285 | |
|
286 | 286 | |
|
287 | 287 | def _store_engine_namespace_values(self, values, keys=[]): |
|
288 | 288 | assert(len(values) == len(keys)) |
|
289 | 289 | self.willChangeValueForKey_('userNS') |
|
290 | 290 | for (k,v) in zip(keys,values): |
|
291 | 291 | self.userNS[k] = saferepr(v) |
|
292 | 292 | self.didChangeValueForKey_('userNS') |
|
293 | 293 | |
|
294 | 294 | |
|
295 | 295 | def update_cell_prompt(self, result, blockID=None): |
|
296 | 296 | print self.blockRanges |
|
297 | 297 | if(isinstance(result, Failure)): |
|
298 | 298 | prompt = self.input_prompt() |
|
299 | 299 | |
|
300 | 300 | else: |
|
301 | 301 | prompt = self.input_prompt(number=result['number']) |
|
302 | 302 | |
|
303 | 303 | r = self.blockRanges[blockID].inputPromptRange |
|
304 | 304 | self.insert_text(prompt, |
|
305 | 305 | textRange=r, |
|
306 | 306 | scrollToVisible=False |
|
307 | 307 | ) |
|
308 | 308 | |
|
309 | 309 | return result |
|
310 | 310 | |
|
311 | 311 | |
|
312 | 312 | def render_result(self, result): |
|
313 | 313 | blockID = result['blockID'] |
|
314 | 314 | inputRange = self.blockRanges[blockID].inputRange |
|
315 | 315 | del self.blockRanges[blockID] |
|
316 | 316 | |
|
317 | 317 | #print inputRange,self.current_block_range() |
|
318 | 318 | self.insert_text('\n' + |
|
319 | 319 | self.output_prompt(number=result['number']) + |
|
320 | 320 | result.get('display',{}).get('pprint','') + |
|
321 | 321 | '\n\n', |
|
322 | 322 | textRange=NSMakeRange(inputRange.location+inputRange.length, |
|
323 | 323 | 0)) |
|
324 | 324 | return result |
|
325 | 325 | |
|
326 | 326 | |
|
327 | 327 | def render_error(self, failure): |
|
328 | 328 | print failure |
|
329 | 329 | blockID = failure.blockID |
|
330 | 330 | inputRange = self.blockRanges[blockID].inputRange |
|
331 | 331 | self.insert_text('\n' + |
|
332 | 332 | self.output_prompt() + |
|
333 | 333 | '\n' + |
|
334 | 334 | failure.getErrorMessage() + |
|
335 | 335 | '\n\n', |
|
336 | 336 | textRange=NSMakeRange(inputRange.location + |
|
337 | 337 | inputRange.length, |
|
338 | 338 | 0)) |
|
339 | 339 | self.start_new_block() |
|
340 | 340 | return failure |
|
341 | 341 | |
|
342 | 342 | |
|
343 | 343 | def _start_cli_banner(self): |
|
344 | 344 | """Print banner""" |
|
345 | 345 | |
|
346 | 346 | banner = """IPython1 %s -- An enhanced Interactive Python.""" % \ |
|
347 | 347 | IPython.__version__ |
|
348 | 348 | |
|
349 | 349 | self.insert_text(banner + '\n\n') |
|
350 | 350 | |
|
351 | 351 | |
|
352 | 352 | def start_new_block(self): |
|
353 | 353 | """""" |
|
354 | 354 | |
|
355 | 355 | self.currentBlockID = self.next_block_ID() |
|
356 | 356 | self.blockRanges[self.currentBlockID] = self.new_cell_block() |
|
357 | 357 | self.insert_text(self.input_prompt(), |
|
358 | 358 | textRange=self.current_block_range().inputPromptRange) |
|
359 | 359 | |
|
360 | 360 | |
|
361 | 361 | |
|
362 | 362 | def next_block_ID(self): |
|
363 | 363 | |
|
364 | 364 | return uuid.uuid4() |
|
365 | 365 | |
|
366 | 366 | def new_cell_block(self): |
|
367 | 367 | """A new CellBlock at the end of self.textView.textStorage()""" |
|
368 | 368 | |
|
369 | 369 | return CellBlock(NSMakeRange(self.textView.textStorage().length(), |
|
370 | 370 | 0), #len(self.input_prompt())), |
|
371 | 371 | NSMakeRange(self.textView.textStorage().length(),# + len(self.input_prompt()), |
|
372 | 372 | 0)) |
|
373 | 373 | |
|
374 | 374 | |
|
375 | 375 | def current_block_range(self): |
|
376 | 376 | return self.blockRanges.get(self.currentBlockID, |
|
377 | 377 | self.new_cell_block()) |
|
378 | 378 | |
|
379 | 379 | def current_block(self): |
|
380 | 380 | """The current block's text""" |
|
381 | 381 | |
|
382 | 382 | return self.text_for_range(self.current_block_range().inputRange) |
|
383 | 383 | |
|
384 | 384 | def text_for_range(self, textRange): |
|
385 | 385 | """text_for_range""" |
|
386 | 386 | |
|
387 | 387 | ts = self.textView.textStorage() |
|
388 | 388 | return ts.string().substringWithRange_(textRange) |
|
389 | 389 | |
|
390 | 390 | def current_line(self): |
|
391 | 391 | block = self.text_for_range(self.current_block_range().inputRange) |
|
392 | 392 | block = block.split('\n') |
|
393 | 393 | return block[-1] |
|
394 | 394 | |
|
395 | 395 | |
|
396 | 396 | def insert_text(self, string=None, textRange=None, scrollToVisible=True): |
|
397 | 397 | """Insert text into textView at textRange, updating blockRanges |
|
398 | 398 | as necessary |
|
399 | 399 | """ |
|
400 | 400 | if(textRange == None): |
|
401 | 401 | #range for end of text |
|
402 | 402 | textRange = NSMakeRange(self.textView.textStorage().length(), 0) |
|
403 | 403 | |
|
404 | 404 | |
|
405 | 405 | self.textView.replaceCharactersInRange_withString_( |
|
406 | 406 | textRange, string) |
|
407 | 407 | |
|
408 | 408 | for r in self.blockRanges.itervalues(): |
|
409 | 409 | r.update_ranges_for_insertion(string, textRange) |
|
410 | 410 | |
|
411 | 411 | self.textView.setSelectedRange_(textRange) |
|
412 | 412 | if(scrollToVisible): |
|
413 | 413 | self.textView.scrollRangeToVisible_(textRange) |
|
414 | 414 | |
|
415 | 415 | |
|
416 | 416 | |
|
417 | 417 | def replace_current_block_with_string(self, textView, string): |
|
418 | 418 | textView.replaceCharactersInRange_withString_( |
|
419 | 419 | self.current_block_range().inputRange, |
|
420 | 420 | string) |
|
421 | 421 | self.current_block_range().inputRange.length = len(string) |
|
422 | 422 | r = NSMakeRange(textView.textStorage().length(), 0) |
|
423 | 423 | textView.scrollRangeToVisible_(r) |
|
424 | 424 | textView.setSelectedRange_(r) |
|
425 | 425 | |
|
426 | 426 | |
|
427 | 427 | def current_indent_string(self): |
|
428 | 428 | """returns string for indent or None if no indent""" |
|
429 | 429 | |
|
430 | 430 | return self._indent_for_block(self.current_block()) |
|
431 | 431 | |
|
432 | 432 | |
|
433 | 433 | def _indent_for_block(self, block): |
|
434 | 434 | lines = block.split('\n') |
|
435 | 435 | if(len(lines) > 1): |
|
436 | 436 | currentIndent = len(lines[-1]) - len(lines[-1].lstrip()) |
|
437 | 437 | if(currentIndent == 0): |
|
438 | 438 | currentIndent = self.tabSpaces |
|
439 | 439 | |
|
440 | 440 | if(self.tabUsesSpaces): |
|
441 | 441 | result = ' ' * currentIndent |
|
442 | 442 | else: |
|
443 | 443 | result = '\t' * (currentIndent/self.tabSpaces) |
|
444 | 444 | else: |
|
445 | 445 | result = None |
|
446 | 446 | |
|
447 | 447 | return result |
|
448 | 448 | |
|
449 | 449 | |
|
450 | 450 | # NSTextView delegate methods... |
|
451 | 451 | def textView_doCommandBySelector_(self, textView, selector): |
|
452 | 452 | assert(textView == self.textView) |
|
453 | 453 | NSLog("textView_doCommandBySelector_: "+selector) |
|
454 | 454 | |
|
455 | 455 | |
|
456 | 456 | if(selector == 'insertNewline:'): |
|
457 | 457 | indent = self.current_indent_string() |
|
458 | 458 | if(indent): |
|
459 | 459 | line = indent + self.current_line() |
|
460 | 460 | else: |
|
461 | 461 | line = self.current_line() |
|
462 | 462 | |
|
463 | 463 | if(self.is_complete(self.current_block())): |
|
464 | 464 | self.execute(self.current_block(), |
|
465 | 465 | blockID=self.currentBlockID) |
|
466 | 466 | self.start_new_block() |
|
467 | 467 | |
|
468 | 468 | return True |
|
469 | 469 | |
|
470 | 470 | return False |
|
471 | 471 | |
|
472 | 472 | elif(selector == 'moveUp:'): |
|
473 | 473 | prevBlock = self.get_history_previous(self.current_block()) |
|
474 | 474 | if(prevBlock != None): |
|
475 | 475 | self.replace_current_block_with_string(textView, prevBlock) |
|
476 | 476 | else: |
|
477 | 477 | NSBeep() |
|
478 | 478 | return True |
|
479 | 479 | |
|
480 | 480 | elif(selector == 'moveDown:'): |
|
481 | 481 | nextBlock = self.get_history_next() |
|
482 | 482 | if(nextBlock != None): |
|
483 | 483 | self.replace_current_block_with_string(textView, nextBlock) |
|
484 | 484 | else: |
|
485 | 485 | NSBeep() |
|
486 | 486 | return True |
|
487 | 487 | |
|
488 | 488 | elif(selector == 'moveToBeginningOfParagraph:'): |
|
489 | 489 | textView.setSelectedRange_(NSMakeRange( |
|
490 | 490 | self.current_block_range().inputRange.location, |
|
491 | 491 | 0)) |
|
492 | 492 | return True |
|
493 | 493 | elif(selector == 'moveToEndOfParagraph:'): |
|
494 | 494 | textView.setSelectedRange_(NSMakeRange( |
|
495 | 495 | self.current_block_range().inputRange.location + \ |
|
496 | 496 | self.current_block_range().inputRange.length, 0)) |
|
497 | 497 | return True |
|
498 | 498 | elif(selector == 'deleteToEndOfParagraph:'): |
|
499 | 499 | if(textView.selectedRange().location <= \ |
|
500 | 500 | self.current_block_range().location): |
|
501 | 501 | raise NotImplemented() |
|
502 | 502 | |
|
503 | 503 | return False # don't actually handle the delete |
|
504 | 504 | |
|
505 | 505 | elif(selector == 'insertTab:'): |
|
506 | 506 | if(len(self.current_line().strip()) == 0): #only white space |
|
507 | 507 | return False |
|
508 | 508 | else: |
|
509 | 509 | self.textView.complete_(self) |
|
510 | 510 | return True |
|
511 | 511 | |
|
512 | 512 | elif(selector == 'deleteBackward:'): |
|
513 | 513 | #if we're at the beginning of the current block, ignore |
|
514 | 514 | if(textView.selectedRange().location == \ |
|
515 | 515 | self.current_block_range().inputRange.location): |
|
516 | 516 | return True |
|
517 | 517 | else: |
|
518 | 518 | for r in self.blockRanges.itervalues(): |
|
519 | 519 | deleteRange = textView.selectedRange |
|
520 | 520 | if(deleteRange.length == 0): |
|
521 | 521 | deleteRange.location -= 1 |
|
522 | 522 | deleteRange.length = 1 |
|
523 | 523 | r.update_ranges_for_deletion(deleteRange) |
|
524 | 524 | return False |
|
525 | 525 | return False |
|
526 | 526 | |
|
527 | 527 | |
|
528 | 528 | def textView_shouldChangeTextInRanges_replacementStrings_(self, |
|
529 | 529 | textView, ranges, replacementStrings): |
|
530 | 530 | """ |
|
531 | 531 | Delegate method for NSTextView. |
|
532 | 532 | |
|
533 | 533 | Refuse change text in ranges not at end, but make those changes at |
|
534 | 534 | end. |
|
535 | 535 | """ |
|
536 | 536 | |
|
537 | 537 | assert(len(ranges) == len(replacementStrings)) |
|
538 | 538 | allow = True |
|
539 | 539 | for r,s in zip(ranges, replacementStrings): |
|
540 | 540 | r = r.rangeValue() |
|
541 | 541 | if(textView.textStorage().length() > 0 and |
|
542 | 542 | r.location < self.current_block_range().inputRange.location): |
|
543 | 543 | self.insert_text(s) |
|
544 | 544 | allow = False |
|
545 | 545 | |
|
546 | 546 | return allow |
|
547 | 547 | |
|
548 | 548 | def textView_completions_forPartialWordRange_indexOfSelectedItem_(self, |
|
549 | 549 | textView, words, charRange, index): |
|
550 | 550 | try: |
|
551 | 551 | ts = textView.textStorage() |
|
552 | 552 | token = ts.string().substringWithRange_(charRange) |
|
553 | 553 | completions = blockingCallFromThread(self.complete, token) |
|
554 | 554 | except: |
|
555 | 555 | completions = objc.nil |
|
556 | 556 | NSBeep() |
|
557 | 557 | |
|
558 | 558 | return (completions,0) |
|
559 | 559 | |
|
560 | 560 |
@@ -1,400 +1,359 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | # -*- test-case-name: IPython.frontend.tests.test_frontendbase -*- |
|
3 | 3 | """ |
|
4 | 4 | frontendbase provides an interface and base class for GUI frontends for |
|
5 | 5 | IPython.kernel/IPython.kernel.core. |
|
6 | 6 | |
|
7 | 7 | Frontend implementations will likely want to subclass FrontEndBase. |
|
8 | 8 | |
|
9 | 9 | Author: Barry Wark |
|
10 | 10 | """ |
|
11 | 11 | __docformat__ = "restructuredtext en" |
|
12 | 12 | |
|
13 | 13 | #------------------------------------------------------------------------------- |
|
14 | 14 | # Copyright (C) 2008 The IPython Development Team |
|
15 | 15 | # |
|
16 | 16 | # Distributed under the terms of the BSD License. The full license is in |
|
17 | 17 | # the file COPYING, distributed as part of this software. |
|
18 | 18 | #------------------------------------------------------------------------------- |
|
19 | 19 | |
|
20 | 20 | #------------------------------------------------------------------------------- |
|
21 | 21 | # Imports |
|
22 | 22 | #------------------------------------------------------------------------------- |
|
23 | 23 | import string |
|
24 | 24 | import uuid |
|
25 | 25 | import _ast |
|
26 | 26 | |
|
27 | try: | |
|
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 | |
|
27 | from zopeinterface import Interface, Attribute, implements, classProvides | |
|
35 | 28 | |
|
36 | 29 | from IPython.kernel.core.history import FrontEndHistory |
|
37 | 30 | from IPython.kernel.core.util import Bunch |
|
38 | 31 | from IPython.kernel.engineservice import IEngineCore |
|
39 | 32 | |
|
40 | ||
|
41 | 33 | ############################################################################## |
|
42 | 34 | # TEMPORARY!!! fake configuration, while we decide whether to use tconfig or |
|
43 | 35 | # not |
|
44 | 36 | |
|
45 | 37 | rc = Bunch() |
|
46 | 38 | rc.prompt_in1 = r'In [$number]: ' |
|
47 | 39 | rc.prompt_in2 = r'...' |
|
48 | 40 | rc.prompt_out = r'Out [$number]: ' |
|
49 | 41 | |
|
50 | 42 | ############################################################################## |
|
43 | # Interface definitions | |
|
44 | ############################################################################## | |
|
51 | 45 | |
|
52 | 46 | class IFrontEndFactory(Interface): |
|
53 | 47 | """Factory interface for frontends.""" |
|
54 | 48 | |
|
55 | 49 | def __call__(engine=None, history=None): |
|
56 | 50 | """ |
|
57 | 51 | Parameters: |
|
58 | 52 | interpreter : IPython.kernel.engineservice.IEngineCore |
|
59 | 53 | """ |
|
60 | 54 | |
|
61 | 55 | pass |
|
62 | 56 | |
|
63 | 57 | |
|
64 | ||
|
65 | 58 | class IFrontEnd(Interface): |
|
66 | 59 | """Interface for frontends. All methods return t.i.d.Deferred""" |
|
67 | 60 | |
|
68 | 61 | Attribute("input_prompt_template", "string.Template instance\ |
|
69 | 62 | substituteable with execute result.") |
|
70 | 63 | Attribute("output_prompt_template", "string.Template instance\ |
|
71 | 64 | substituteable with execute result.") |
|
72 | 65 | Attribute("continuation_prompt_template", "string.Template instance\ |
|
73 | 66 | substituteable with execute result.") |
|
74 | 67 | |
|
75 | 68 | def update_cell_prompt(result, blockID=None): |
|
76 | 69 | """Subclass may override to update the input prompt for a block. |
|
77 | Since this method will be called as a | |
|
78 | twisted.internet.defer.Deferred's callback/errback, | |
|
79 | implementations should return result when finished. | |
|
70 | ||
|
71 | In asynchronous frontends, this method will be called as a | |
|
72 | twisted.internet.defer.Deferred's callback/errback. | |
|
73 | Implementations should thus return result when finished. | |
|
80 | 74 | |
|
81 | 75 | Result is a result dict in case of success, and a |
|
82 | 76 | twisted.python.util.failure.Failure in case of an error |
|
83 | 77 | """ |
|
84 | 78 | |
|
85 | 79 | pass |
|
86 | 80 | |
|
87 | ||
|
88 | 81 | def render_result(result): |
|
89 | 82 | """Render the result of an execute call. Implementors may choose the |
|
90 | 83 | method of rendering. |
|
91 | 84 | For example, a notebook-style frontend might render a Chaco plot |
|
92 | 85 | inline. |
|
93 | 86 | |
|
94 | 87 | Parameters: |
|
95 | 88 | result : dict (result of IEngineBase.execute ) |
|
96 | 89 | blockID = result['blockID'] |
|
97 | 90 | |
|
98 | 91 | Result: |
|
99 | 92 | Output of frontend rendering |
|
100 | 93 | """ |
|
101 | 94 | |
|
102 | 95 | pass |
|
103 | 96 | |
|
104 | 97 | def render_error(failure): |
|
105 |
"""Subclasses must override to render the failure. |
|
|
106 | will be called as a twisted.internet.defer.Deferred's callback, | |
|
107 | implementations should return result when finished. | |
|
98 | """Subclasses must override to render the failure. | |
|
99 | ||
|
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 | 104 | blockID = failure.blockID |
|
110 | 105 | """ |
|
111 | 106 | |
|
112 | 107 | pass |
|
113 | 108 | |
|
114 | ||
|
115 | 109 | def input_prompt(number=''): |
|
116 | 110 | """Returns the input prompt by subsituting into |
|
117 | 111 | self.input_prompt_template |
|
118 | 112 | """ |
|
119 | 113 | pass |
|
120 | 114 | |
|
121 | 115 | def output_prompt(number=''): |
|
122 | 116 | """Returns the output prompt by subsituting into |
|
123 | 117 | self.output_prompt_template |
|
124 | 118 | """ |
|
125 | 119 | |
|
126 | 120 | pass |
|
127 | 121 | |
|
128 | 122 | def continuation_prompt(): |
|
129 | 123 | """Returns the continuation prompt by subsituting into |
|
130 | 124 | self.continuation_prompt_template |
|
131 | 125 | """ |
|
132 | 126 | |
|
133 | 127 | pass |
|
134 | 128 | |
|
135 | 129 | def is_complete(block): |
|
136 | 130 | """Returns True if block is complete, False otherwise.""" |
|
137 | 131 | |
|
138 | 132 | pass |
|
139 | 133 | |
|
140 | 134 | def compile_ast(block): |
|
141 | 135 | """Compiles block to an _ast.AST""" |
|
142 | 136 | |
|
143 | 137 | pass |
|
144 | 138 | |
|
145 | ||
|
146 | def get_history_previous(currentBlock): | |
|
139 | def get_history_previous(current_block): | |
|
147 | 140 | """Returns the block previous in the history. Saves currentBlock if |
|
148 | 141 | the history_cursor is currently at the end of the input history""" |
|
149 | 142 | pass |
|
150 | 143 | |
|
151 | 144 | def get_history_next(): |
|
152 | 145 | """Returns the next block in the history.""" |
|
153 | 146 | |
|
154 | 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 | 164 | class FrontEndBase(object): |
|
158 | 165 | """ |
|
159 | 166 | FrontEndBase manages the state tasks for a CLI frontend: |
|
160 | 167 | - Input and output history management |
|
161 | 168 | - Input/continuation and output prompt generation |
|
162 | 169 | |
|
163 | 170 | Some issues (due to possibly unavailable engine): |
|
164 | 171 | - How do we get the current cell number for the engine? |
|
165 | 172 | - How do we handle completions? |
|
166 | 173 | """ |
|
167 | 174 | |
|
168 | 175 | history_cursor = 0 |
|
169 | 176 | |
|
170 | current_indent_level = 0 | |
|
171 | ||
|
172 | ||
|
173 | 177 | input_prompt_template = string.Template(rc.prompt_in1) |
|
174 | 178 | output_prompt_template = string.Template(rc.prompt_out) |
|
175 | 179 | continuation_prompt_template = string.Template(rc.prompt_in2) |
|
176 | 180 | |
|
177 | 181 | def __init__(self, shell=None, history=None): |
|
178 | 182 | self.shell = shell |
|
179 | 183 | if history is None: |
|
180 | 184 | self.history = FrontEndHistory(input_cache=['']) |
|
181 | 185 | else: |
|
182 | 186 | self.history = history |
|
183 | 187 | |
|
184 | 188 | |
|
185 | 189 | def input_prompt(self, number=''): |
|
186 | 190 | """Returns the current input prompt |
|
187 | 191 | |
|
188 | 192 | It would be great to use ipython1.core.prompts.Prompt1 here |
|
189 | 193 | """ |
|
190 | 194 | return self.input_prompt_template.safe_substitute({'number':number}) |
|
191 | 195 | |
|
192 | 196 | |
|
193 | 197 | def continuation_prompt(self): |
|
194 | 198 | """Returns the current continuation prompt""" |
|
195 | 199 | |
|
196 | 200 | return self.continuation_prompt_template.safe_substitute() |
|
197 | 201 | |
|
198 | 202 | def output_prompt(self, number=''): |
|
199 | 203 | """Returns the output prompt for result""" |
|
200 | 204 | |
|
201 | 205 | return self.output_prompt_template.safe_substitute({'number':number}) |
|
202 | 206 | |
|
203 | 207 | |
|
204 | 208 | def is_complete(self, block): |
|
205 | 209 | """Determine if block is complete. |
|
206 | 210 | |
|
207 | 211 | Parameters |
|
208 | 212 | block : string |
|
209 | 213 | |
|
210 | 214 | Result |
|
211 | 215 | True if block can be sent to the engine without compile errors. |
|
212 | 216 | False otherwise. |
|
213 | 217 | """ |
|
214 | 218 | |
|
215 | 219 | try: |
|
216 | 220 | ast = self.compile_ast(block) |
|
217 | 221 | except: |
|
218 | 222 | return False |
|
219 | 223 | |
|
220 | 224 | lines = block.split('\n') |
|
221 | 225 | return (len(lines)==1 or str(lines[-1])=='') |
|
222 | 226 | |
|
223 | 227 | |
|
224 | 228 | def compile_ast(self, block): |
|
225 | 229 | """Compile block to an AST |
|
226 | 230 | |
|
227 | 231 | Parameters: |
|
228 | 232 | block : str |
|
229 | 233 | |
|
230 | 234 | Result: |
|
231 | 235 | AST |
|
232 | 236 | |
|
233 | 237 | Throws: |
|
234 | 238 | Exception if block cannot be compiled |
|
235 | 239 | """ |
|
236 | 240 | |
|
237 | 241 | return compile(block, "<string>", "exec", _ast.PyCF_ONLY_AST) |
|
238 | 242 | |
|
239 | 243 | |
|
240 | 244 | def execute(self, block, blockID=None): |
|
241 | 245 | """Execute the block and return the result. |
|
242 | 246 | |
|
243 | 247 | Parameters: |
|
244 | 248 | block : {str, AST} |
|
245 | 249 | blockID : any |
|
246 | 250 | Caller may provide an ID to identify this block. |
|
247 | 251 | result['blockID'] := blockID |
|
248 | 252 | |
|
249 | 253 | Result: |
|
250 | 254 | Deferred result of self.interpreter.execute |
|
251 | 255 | """ |
|
252 | 256 | |
|
253 | 257 | if(not self.is_complete(block)): |
|
254 | 258 | raise Exception("Block is not compilable") |
|
255 | 259 | |
|
256 | 260 | if(blockID == None): |
|
257 | 261 | blockID = uuid.uuid4() #random UUID |
|
258 | 262 | |
|
259 | 263 | try: |
|
260 | 264 | result = self.shell.execute(block) |
|
261 | 265 | except Exception,e: |
|
262 | 266 | e = self._add_block_id_for_failure(e, blockID=blockID) |
|
263 | 267 | e = self.update_cell_prompt(e, blockID=blockID) |
|
264 | 268 | e = self.render_error(e) |
|
265 | 269 | else: |
|
266 | 270 | result = self._add_block_id_for_result(result, blockID=blockID) |
|
267 | 271 | result = self.update_cell_prompt(result, blockID=blockID) |
|
268 | 272 | result = self.render_result(result) |
|
269 | 273 | |
|
270 | 274 | return result |
|
271 | 275 | |
|
272 | 276 | |
|
273 | 277 | def _add_block_id_for_result(self, result, blockID): |
|
274 | 278 | """Add the blockID to result or failure. Unfortunatley, we have to |
|
275 | 279 | treat failures differently than result dicts. |
|
276 | 280 | """ |
|
277 | 281 | |
|
278 | 282 | result['blockID'] = blockID |
|
279 | 283 | |
|
280 | 284 | return result |
|
281 | 285 | |
|
282 | 286 | def _add_block_id_for_failure(self, failure, blockID): |
|
283 | 287 | """_add_block_id_for_failure""" |
|
284 | 288 | failure.blockID = blockID |
|
285 | 289 | return failure |
|
286 | 290 | |
|
287 | 291 | |
|
288 | 292 | def _add_history(self, result, block=None): |
|
289 | 293 | """Add block to the history""" |
|
290 | 294 | |
|
291 | 295 | assert(block != None) |
|
292 | 296 | self.history.add_items([block]) |
|
293 | 297 | self.history_cursor += 1 |
|
294 | 298 | |
|
295 | 299 | return result |
|
296 | 300 | |
|
297 | 301 | |
|
298 |
def get_history_previous(self, current |
|
|
302 | def get_history_previous(self, current_block): | |
|
299 | 303 | """ Returns previous history string and decrement history cursor. |
|
300 | 304 | """ |
|
301 | 305 | command = self.history.get_history_item(self.history_cursor - 1) |
|
302 | 306 | |
|
303 | 307 | if command is not None: |
|
304 | if(self.history_cursor == len(self.history.input_cache)): | |
|
305 |
self.history.input_cache[self.history_cursor] = current |
|
|
308 | if(self.history_cursor+1 == len(self.history.input_cache)): | |
|
309 | self.history.input_cache[self.history_cursor] = current_block | |
|
306 | 310 | self.history_cursor -= 1 |
|
307 | 311 | return command |
|
308 | 312 | |
|
309 | 313 | |
|
310 | 314 | def get_history_next(self): |
|
311 | 315 | """ Returns next history string and increment history cursor. |
|
312 | 316 | """ |
|
313 | 317 | command = self.history.get_history_item(self.history_cursor+1) |
|
314 | 318 | |
|
315 | 319 | if command is not None: |
|
316 | 320 | self.history_cursor += 1 |
|
317 | 321 | return command |
|
318 | 322 | |
|
319 | 323 | ### |
|
320 | 324 | # Subclasses probably want to override these methods... |
|
321 | 325 | ### |
|
322 | 326 | |
|
323 | 327 | def update_cell_prompt(self, result, blockID=None): |
|
324 | 328 | """Subclass may override to update the input prompt for a block. |
|
329 | ||
|
330 | This method only really makes sens in asyncrhonous frontend. | |
|
325 | 331 | Since this method will be called as a |
|
326 | 332 | twisted.internet.defer.Deferred's callback, implementations should |
|
327 | 333 | return result when finished. |
|
328 | 334 | """ |
|
329 | 335 | |
|
330 | return result | |
|
336 | raise NotImplementedError | |
|
331 | 337 | |
|
332 | 338 | |
|
333 | 339 | def render_result(self, result): |
|
334 |
"""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 | """ | |
|
340 | """Subclasses must override to render result. | |
|
338 | 341 |
|
|
339 | return result | |
|
340 | ||
|
341 | ||
|
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. | |
|
342 | In asynchronous frontends, this method will be called as a | |
|
343 | twisted.internet.defer.Deferred's callback. Implementations | |
|
344 | should thus return result when finished. | |
|
346 | 345 | """ |
|
347 | 346 | |
|
348 | return failure | |
|
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 | |
|
347 | raise NotImplementedError | |
|
368 | 348 | |
|
369 | 349 | |
|
370 | def execute(self, block, blockID=None): | |
|
371 | """Execute the block and return the deferred result. | |
|
372 | ||
|
373 | Parameters: | |
|
374 | block : {str, AST} | |
|
375 | blockID : any | |
|
376 | Caller may provide an ID to identify this block. | |
|
377 | result['blockID'] := blockID | |
|
350 | def render_error(self, failure): | |
|
351 | """Subclasses must override to render the failure. | |
|
378 | 352 | |
|
379 | Result: | |
|
380 | Deferred result of self.interpreter.execute | |
|
353 | In asynchronous frontends, this method will be called as a | |
|
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)): | |
|
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 | ||
|
358 | raise NotImplementedError | |
|
400 | 359 |
@@ -1,151 +1,152 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | |
|
3 | 3 | """This file contains unittests for the frontendbase module.""" |
|
4 | 4 | |
|
5 | 5 | __docformat__ = "restructuredtext en" |
|
6 | 6 | |
|
7 | 7 | #--------------------------------------------------------------------------- |
|
8 | 8 | # Copyright (C) 2008 The IPython Development Team |
|
9 | 9 | # |
|
10 | 10 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | 11 | # the file COPYING, distributed as part of this software. |
|
12 | 12 | #--------------------------------------------------------------------------- |
|
13 | 13 | |
|
14 | 14 | #--------------------------------------------------------------------------- |
|
15 | 15 | # Imports |
|
16 | 16 | #--------------------------------------------------------------------------- |
|
17 | 17 | |
|
18 | 18 | import unittest |
|
19 |
from IPython.frontend import |
|
|
19 | from IPython.frontend.asyncfrontendbase import AsyncFrontEndBase | |
|
20 | from IPython.frontend import frontendbase | |
|
20 | 21 | from IPython.kernel.engineservice import EngineService |
|
21 | 22 | |
|
22 |
class FrontEndCallbackChecker( |
|
|
23 | class FrontEndCallbackChecker(AsyncFrontEndBase): | |
|
23 | 24 | """FrontEndBase subclass for checking callbacks""" |
|
24 | 25 | def __init__(self, engine=None, history=None): |
|
25 | 26 | super(FrontEndCallbackChecker, self).__init__(engine=engine, |
|
26 | 27 | history=history) |
|
27 | 28 | self.updateCalled = False |
|
28 | 29 | self.renderResultCalled = False |
|
29 | 30 | self.renderErrorCalled = False |
|
30 | 31 | |
|
31 | 32 | def update_cell_prompt(self, result, blockID=None): |
|
32 | 33 | self.updateCalled = True |
|
33 | 34 | return result |
|
34 | 35 | |
|
35 | 36 | def render_result(self, result): |
|
36 | 37 | self.renderResultCalled = True |
|
37 | 38 | return result |
|
38 | 39 | |
|
39 | 40 | |
|
40 | 41 | def render_error(self, failure): |
|
41 | 42 | self.renderErrorCalled = True |
|
42 | 43 | return failure |
|
43 | 44 | |
|
44 | 45 | |
|
45 | 46 | |
|
46 | 47 | |
|
47 | 48 | class TestAsyncFrontendBase(unittest.TestCase): |
|
48 | 49 | def setUp(self): |
|
49 | 50 | """Setup the EngineService and FrontEndBase""" |
|
50 | 51 | |
|
51 | 52 | self.fb = FrontEndCallbackChecker(engine=EngineService()) |
|
52 | 53 | |
|
53 | 54 | |
|
54 | 55 | def test_implements_IFrontEnd(self): |
|
55 | 56 | assert(frontendbase.IFrontEnd.implementedBy( |
|
56 |
|
|
|
57 | AsyncFrontEndBase)) | |
|
57 | 58 | |
|
58 | 59 | |
|
59 | 60 | def test_is_complete_returns_False_for_incomplete_block(self): |
|
60 | 61 | """""" |
|
61 | 62 | |
|
62 | 63 | block = """def test(a):""" |
|
63 | 64 | |
|
64 | 65 | assert(self.fb.is_complete(block) == False) |
|
65 | 66 | |
|
66 | 67 | def test_is_complete_returns_True_for_complete_block(self): |
|
67 | 68 | """""" |
|
68 | 69 | |
|
69 | 70 | block = """def test(a): pass""" |
|
70 | 71 | |
|
71 | 72 | assert(self.fb.is_complete(block)) |
|
72 | 73 | |
|
73 | 74 | block = """a=3""" |
|
74 | 75 | |
|
75 | 76 | assert(self.fb.is_complete(block)) |
|
76 | 77 | |
|
77 | 78 | |
|
78 | 79 | def test_blockID_added_to_result(self): |
|
79 | 80 | block = """3+3""" |
|
80 | 81 | |
|
81 | 82 | d = self.fb.execute(block, blockID='TEST_ID') |
|
82 | 83 | |
|
83 | 84 | d.addCallback(self.checkBlockID, expected='TEST_ID') |
|
84 | 85 | |
|
85 | 86 | def test_blockID_added_to_failure(self): |
|
86 | 87 | block = "raise Exception()" |
|
87 | 88 | |
|
88 | 89 | d = self.fb.execute(block,blockID='TEST_ID') |
|
89 | 90 | d.addErrback(self.checkFailureID, expected='TEST_ID') |
|
90 | 91 | |
|
91 | 92 | def checkBlockID(self, result, expected=""): |
|
92 | 93 | assert(result['blockID'] == expected) |
|
93 | 94 | |
|
94 | 95 | |
|
95 | 96 | def checkFailureID(self, failure, expected=""): |
|
96 | 97 | assert(failure.blockID == expected) |
|
97 | 98 | |
|
98 | 99 | |
|
99 | 100 | def test_callbacks_added_to_execute(self): |
|
100 | 101 | """test that |
|
101 | 102 | update_cell_prompt |
|
102 | 103 | render_result |
|
103 | 104 | |
|
104 | 105 | are added to execute request |
|
105 | 106 | """ |
|
106 | 107 | |
|
107 | 108 | d = self.fb.execute("10+10") |
|
108 | 109 | d.addCallback(self.checkCallbacks) |
|
109 | 110 | |
|
110 | 111 | |
|
111 | 112 | def checkCallbacks(self, result): |
|
112 | 113 | assert(self.fb.updateCalled) |
|
113 | 114 | assert(self.fb.renderResultCalled) |
|
114 | 115 | |
|
115 | 116 | |
|
116 | 117 | def test_error_callback_added_to_execute(self): |
|
117 | 118 | """test that render_error called on execution error""" |
|
118 | 119 | |
|
119 | 120 | d = self.fb.execute("raise Exception()") |
|
120 | 121 | d.addCallback(self.checkRenderError) |
|
121 | 122 | |
|
122 | 123 | def checkRenderError(self, result): |
|
123 | 124 | assert(self.fb.renderErrorCalled) |
|
124 | 125 | |
|
125 | 126 | def test_history_returns_expected_block(self): |
|
126 | 127 | """Make sure history browsing doesn't fail""" |
|
127 | 128 | |
|
128 | 129 | blocks = ["a=1","a=2","a=3"] |
|
129 | 130 | for b in blocks: |
|
130 | 131 | d = self.fb.execute(b) |
|
131 | 132 | |
|
132 | 133 | # d is now the deferred for the last executed block |
|
133 | 134 | d.addCallback(self.historyTests, blocks) |
|
134 | 135 | |
|
135 | 136 | |
|
136 | 137 | def historyTests(self, result, blocks): |
|
137 | 138 | """historyTests""" |
|
138 | 139 | |
|
139 | 140 | assert(len(blocks) >= 3) |
|
140 | 141 | assert(self.fb.get_history_previous("") == blocks[-2]) |
|
141 | 142 | assert(self.fb.get_history_previous("") == blocks[-3]) |
|
142 | 143 | assert(self.fb.get_history_next() == blocks[-2]) |
|
143 | 144 | |
|
144 | 145 | |
|
145 | 146 | def test_history_returns_none_at_startup(self): |
|
146 | 147 | """test_history_returns_none_at_startup""" |
|
147 | 148 | |
|
148 | 149 | assert(self.fb.get_history_previous("")==None) |
|
149 | 150 | assert(self.fb.get_history_next()==None) |
|
150 | 151 | |
|
151 | 152 |
@@ -1,2681 +1,2686 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | IPython -- An enhanced Interactive Python |
|
4 | 4 | |
|
5 | 5 | Requires Python 2.3 or newer. |
|
6 | 6 | |
|
7 | 7 | This file contains all the classes and helper functions specific to IPython. |
|
8 | 8 | |
|
9 | 9 | """ |
|
10 | 10 | |
|
11 | 11 | #***************************************************************************** |
|
12 | 12 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
13 | 13 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
14 | 14 | # |
|
15 | 15 | # Distributed under the terms of the BSD License. The full license is in |
|
16 | 16 | # the file COPYING, distributed as part of this software. |
|
17 | 17 | # |
|
18 | 18 | # Note: this code originally subclassed code.InteractiveConsole from the |
|
19 | 19 | # Python standard library. Over time, all of that class has been copied |
|
20 | 20 | # verbatim here for modifications which could not be accomplished by |
|
21 | 21 | # subclassing. At this point, there are no dependencies at all on the code |
|
22 | 22 | # module anymore (it is not even imported). The Python License (sec. 2) |
|
23 | 23 | # allows for this, but it's always nice to acknowledge credit where credit is |
|
24 | 24 | # due. |
|
25 | 25 | #***************************************************************************** |
|
26 | 26 | |
|
27 | 27 | #**************************************************************************** |
|
28 | 28 | # Modules and globals |
|
29 | 29 | |
|
30 | 30 | from IPython import Release |
|
31 | 31 | __author__ = '%s <%s>\n%s <%s>' % \ |
|
32 | 32 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) |
|
33 | 33 | __license__ = Release.license |
|
34 | 34 | __version__ = Release.version |
|
35 | 35 | |
|
36 | 36 | # Python standard modules |
|
37 | 37 | import __main__ |
|
38 | 38 | import __builtin__ |
|
39 | 39 | import StringIO |
|
40 | 40 | import bdb |
|
41 | 41 | import cPickle as pickle |
|
42 | 42 | import codeop |
|
43 | 43 | import exceptions |
|
44 | 44 | import glob |
|
45 | 45 | import inspect |
|
46 | 46 | import keyword |
|
47 | 47 | import new |
|
48 | 48 | import os |
|
49 | 49 | import pydoc |
|
50 | 50 | import re |
|
51 | 51 | import shutil |
|
52 | 52 | import string |
|
53 | 53 | import sys |
|
54 | 54 | import tempfile |
|
55 | 55 | import traceback |
|
56 | 56 | import types |
|
57 | 57 | import warnings |
|
58 | 58 | warnings.filterwarnings('ignore', r'.*sets module*') |
|
59 | 59 | from sets import Set |
|
60 | 60 | from pprint import pprint, pformat |
|
61 | 61 | |
|
62 | 62 | # IPython's own modules |
|
63 | 63 | #import IPython |
|
64 | 64 | from IPython import Debugger,OInspect,PyColorize,ultraTB |
|
65 | 65 | from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names |
|
66 | 66 | from IPython.Extensions import pickleshare |
|
67 | 67 | from IPython.FakeModule import FakeModule |
|
68 | 68 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns |
|
69 | 69 | from IPython.Logger import Logger |
|
70 | 70 | from IPython.Magic import Magic |
|
71 | 71 | from IPython.Prompts import CachedOutput |
|
72 | 72 | from IPython.ipstruct import Struct |
|
73 | 73 | from IPython.background_jobs import BackgroundJobManager |
|
74 | 74 | from IPython.usage import cmd_line_usage,interactive_usage |
|
75 | 75 | from IPython.genutils import * |
|
76 | 76 | from IPython.strdispatch import StrDispatch |
|
77 | 77 | import IPython.ipapi |
|
78 | 78 | import IPython.history |
|
79 | 79 | import IPython.prefilter as prefilter |
|
80 | 80 | import IPython.shadowns |
|
81 | 81 | # Globals |
|
82 | 82 | |
|
83 | 83 | # store the builtin raw_input globally, and use this always, in case user code |
|
84 | 84 | # overwrites it (like wx.py.PyShell does) |
|
85 | 85 | raw_input_original = raw_input |
|
86 | 86 | |
|
87 | 87 | # compiled regexps for autoindent management |
|
88 | 88 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
89 | 89 | |
|
90 | 90 | |
|
91 | 91 | #**************************************************************************** |
|
92 | 92 | # Some utility function definitions |
|
93 | 93 | |
|
94 | 94 | ini_spaces_re = re.compile(r'^(\s+)') |
|
95 | 95 | |
|
96 | 96 | def num_ini_spaces(strng): |
|
97 | 97 | """Return the number of initial spaces in a string""" |
|
98 | 98 | |
|
99 | 99 | ini_spaces = ini_spaces_re.match(strng) |
|
100 | 100 | if ini_spaces: |
|
101 | 101 | return ini_spaces.end() |
|
102 | 102 | else: |
|
103 | 103 | return 0 |
|
104 | 104 | |
|
105 | 105 | def softspace(file, newvalue): |
|
106 | 106 | """Copied from code.py, to remove the dependency""" |
|
107 | 107 | |
|
108 | 108 | oldvalue = 0 |
|
109 | 109 | try: |
|
110 | 110 | oldvalue = file.softspace |
|
111 | 111 | except AttributeError: |
|
112 | 112 | pass |
|
113 | 113 | try: |
|
114 | 114 | file.softspace = newvalue |
|
115 | 115 | except (AttributeError, TypeError): |
|
116 | 116 | # "attribute-less object" or "read-only attributes" |
|
117 | 117 | pass |
|
118 | 118 | return oldvalue |
|
119 | 119 | |
|
120 | 120 | |
|
121 | 121 | #**************************************************************************** |
|
122 | 122 | # Local use exceptions |
|
123 | 123 | class SpaceInInput(exceptions.Exception): pass |
|
124 | 124 | |
|
125 | 125 | |
|
126 | 126 | #**************************************************************************** |
|
127 | 127 | # Local use classes |
|
128 | 128 | class Bunch: pass |
|
129 | 129 | |
|
130 | 130 | class Undefined: pass |
|
131 | 131 | |
|
132 | 132 | class Quitter(object): |
|
133 | 133 | """Simple class to handle exit, similar to Python 2.5's. |
|
134 | 134 | |
|
135 | 135 | It handles exiting in an ipython-safe manner, which the one in Python 2.5 |
|
136 | 136 | doesn't do (obviously, since it doesn't know about ipython).""" |
|
137 | 137 | |
|
138 | 138 | def __init__(self,shell,name): |
|
139 | 139 | self.shell = shell |
|
140 | 140 | self.name = name |
|
141 | 141 | |
|
142 | 142 | def __repr__(self): |
|
143 | 143 | return 'Type %s() to exit.' % self.name |
|
144 | 144 | __str__ = __repr__ |
|
145 | 145 | |
|
146 | 146 | def __call__(self): |
|
147 | 147 | self.shell.exit() |
|
148 | 148 | |
|
149 | 149 | class InputList(list): |
|
150 | 150 | """Class to store user input. |
|
151 | 151 | |
|
152 | 152 | It's basically a list, but slices return a string instead of a list, thus |
|
153 | 153 | allowing things like (assuming 'In' is an instance): |
|
154 | 154 | |
|
155 | 155 | exec In[4:7] |
|
156 | 156 | |
|
157 | 157 | or |
|
158 | 158 | |
|
159 | 159 | exec In[5:9] + In[14] + In[21:25]""" |
|
160 | 160 | |
|
161 | 161 | def __getslice__(self,i,j): |
|
162 | 162 | return ''.join(list.__getslice__(self,i,j)) |
|
163 | 163 | |
|
164 | 164 | class SyntaxTB(ultraTB.ListTB): |
|
165 | 165 | """Extension which holds some state: the last exception value""" |
|
166 | 166 | |
|
167 | 167 | def __init__(self,color_scheme = 'NoColor'): |
|
168 | 168 | ultraTB.ListTB.__init__(self,color_scheme) |
|
169 | 169 | self.last_syntax_error = None |
|
170 | 170 | |
|
171 | 171 | def __call__(self, etype, value, elist): |
|
172 | 172 | self.last_syntax_error = value |
|
173 | 173 | ultraTB.ListTB.__call__(self,etype,value,elist) |
|
174 | 174 | |
|
175 | 175 | def clear_err_state(self): |
|
176 | 176 | """Return the current error state and clear it""" |
|
177 | 177 | e = self.last_syntax_error |
|
178 | 178 | self.last_syntax_error = None |
|
179 | 179 | return e |
|
180 | 180 | |
|
181 | 181 | #**************************************************************************** |
|
182 | 182 | # Main IPython class |
|
183 | 183 | |
|
184 | 184 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so |
|
185 | 185 | # until a full rewrite is made. I've cleaned all cross-class uses of |
|
186 | 186 | # attributes and methods, but too much user code out there relies on the |
|
187 | 187 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. |
|
188 | 188 | # |
|
189 | 189 | # But at least now, all the pieces have been separated and we could, in |
|
190 | 190 | # principle, stop using the mixin. This will ease the transition to the |
|
191 | 191 | # chainsaw branch. |
|
192 | 192 | |
|
193 | 193 | # For reference, the following is the list of 'self.foo' uses in the Magic |
|
194 | 194 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython |
|
195 | 195 | # class, to prevent clashes. |
|
196 | 196 | |
|
197 | 197 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', |
|
198 | 198 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', |
|
199 | 199 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', |
|
200 | 200 | # 'self.value'] |
|
201 | 201 | |
|
202 | 202 | class InteractiveShell(object,Magic): |
|
203 | 203 | """An enhanced console for Python.""" |
|
204 | 204 | |
|
205 | 205 | # class attribute to indicate whether the class supports threads or not. |
|
206 | 206 | # Subclasses with thread support should override this as needed. |
|
207 | 207 | isthreaded = False |
|
208 | 208 | |
|
209 | 209 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
210 | 210 | user_ns=None,user_global_ns=None,banner2='', |
|
211 | 211 | custom_exceptions=((),None),embedded=False): |
|
212 | 212 | |
|
213 | 213 | # log system |
|
214 | 214 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') |
|
215 | 215 | |
|
216 | 216 | # Job manager (for jobs run as background threads) |
|
217 | 217 | self.jobs = BackgroundJobManager() |
|
218 | 218 | |
|
219 | 219 | # Store the actual shell's name |
|
220 | 220 | self.name = name |
|
221 | 221 | self.more = False |
|
222 | 222 | |
|
223 | 223 | # We need to know whether the instance is meant for embedding, since |
|
224 | 224 | # global/local namespaces need to be handled differently in that case |
|
225 | 225 | self.embedded = embedded |
|
226 | 226 | if embedded: |
|
227 | 227 | # Control variable so users can, from within the embedded instance, |
|
228 | 228 | # permanently deactivate it. |
|
229 | 229 | self.embedded_active = True |
|
230 | 230 | |
|
231 | 231 | # command compiler |
|
232 | 232 | self.compile = codeop.CommandCompiler() |
|
233 | 233 | |
|
234 | 234 | # User input buffer |
|
235 | 235 | self.buffer = [] |
|
236 | 236 | |
|
237 | 237 | # Default name given in compilation of code |
|
238 | 238 | self.filename = '<ipython console>' |
|
239 | 239 | |
|
240 | 240 | # Install our own quitter instead of the builtins. For python2.3-2.4, |
|
241 | 241 | # this brings in behavior like 2.5, and for 2.5 it's identical. |
|
242 | 242 | __builtin__.exit = Quitter(self,'exit') |
|
243 | 243 | __builtin__.quit = Quitter(self,'quit') |
|
244 | 244 | |
|
245 | 245 | # Make an empty namespace, which extension writers can rely on both |
|
246 | 246 | # existing and NEVER being used by ipython itself. This gives them a |
|
247 | 247 | # convenient location for storing additional information and state |
|
248 | 248 | # their extensions may require, without fear of collisions with other |
|
249 | 249 | # ipython names that may develop later. |
|
250 | 250 | self.meta = Struct() |
|
251 | 251 | |
|
252 | 252 | # Create the namespace where the user will operate. user_ns is |
|
253 | 253 | # normally the only one used, and it is passed to the exec calls as |
|
254 | 254 | # the locals argument. But we do carry a user_global_ns namespace |
|
255 | 255 | # given as the exec 'globals' argument, This is useful in embedding |
|
256 | 256 | # situations where the ipython shell opens in a context where the |
|
257 | 257 | # distinction between locals and globals is meaningful. For |
|
258 | 258 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
259 | 259 | |
|
260 | 260 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
261 | 261 | # level as a dict instead of a module. This is a manual fix, but I |
|
262 | 262 | # should really track down where the problem is coming from. Alex |
|
263 | 263 | # Schmolck reported this problem first. |
|
264 | 264 | |
|
265 | 265 | # A useful post by Alex Martelli on this topic: |
|
266 | 266 | # Re: inconsistent value from __builtins__ |
|
267 | 267 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
268 | 268 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
269 | 269 | # Gruppen: comp.lang.python |
|
270 | 270 | |
|
271 | 271 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
272 | 272 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
273 | 273 | # > <type 'dict'> |
|
274 | 274 | # > >>> print type(__builtins__) |
|
275 | 275 | # > <type 'module'> |
|
276 | 276 | # > Is this difference in return value intentional? |
|
277 | 277 | |
|
278 | 278 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
279 | 279 | # or a module, and it's been that way for a long time. Whether it's |
|
280 | 280 | # intentional (or sensible), I don't know. In any case, the idea is |
|
281 | 281 | # that if you need to access the built-in namespace directly, you |
|
282 | 282 | # should start with "import __builtin__" (note, no 's') which will |
|
283 | 283 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
284 | 284 | |
|
285 | 285 | # These routines return properly built dicts as needed by the rest of |
|
286 | 286 | # the code, and can also be used by extension writers to generate |
|
287 | 287 | # properly initialized namespaces. |
|
288 | 288 | user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns, |
|
289 | 289 | user_global_ns) |
|
290 | 290 | |
|
291 | 291 | # Assign namespaces |
|
292 | 292 | # This is the namespace where all normal user variables live |
|
293 | 293 | self.user_ns = user_ns |
|
294 | 294 | self.user_global_ns = user_global_ns |
|
295 | 295 | # A namespace to keep track of internal data structures to prevent |
|
296 | 296 | # them from cluttering user-visible stuff. Will be updated later |
|
297 | 297 | self.internal_ns = {} |
|
298 | 298 | |
|
299 | 299 | # Namespace of system aliases. Each entry in the alias |
|
300 | 300 | # table must be a 2-tuple of the form (N,name), where N is the number |
|
301 | 301 | # of positional arguments of the alias. |
|
302 | 302 | self.alias_table = {} |
|
303 | 303 | |
|
304 | 304 | # A table holding all the namespaces IPython deals with, so that |
|
305 | 305 | # introspection facilities can search easily. |
|
306 | 306 | self.ns_table = {'user':user_ns, |
|
307 | 307 | 'user_global':user_global_ns, |
|
308 | 308 | 'alias':self.alias_table, |
|
309 | 309 | 'internal':self.internal_ns, |
|
310 | 310 | 'builtin':__builtin__.__dict__ |
|
311 | 311 | } |
|
312 | 312 | # The user namespace MUST have a pointer to the shell itself. |
|
313 | 313 | self.user_ns[name] = self |
|
314 | 314 | |
|
315 | 315 | # We need to insert into sys.modules something that looks like a |
|
316 | 316 | # module but which accesses the IPython namespace, for shelve and |
|
317 | 317 | # pickle to work interactively. Normally they rely on getting |
|
318 | 318 | # everything out of __main__, but for embedding purposes each IPython |
|
319 | 319 | # instance has its own private namespace, so we can't go shoving |
|
320 | 320 | # everything into __main__. |
|
321 | 321 | |
|
322 | 322 | # note, however, that we should only do this for non-embedded |
|
323 | 323 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
324 | 324 | # namespace. Embedded instances, on the other hand, should not do |
|
325 | 325 | # this because they need to manage the user local/global namespaces |
|
326 | 326 | # only, but they live within a 'normal' __main__ (meaning, they |
|
327 | 327 | # shouldn't overtake the execution environment of the script they're |
|
328 | 328 | # embedded in). |
|
329 | 329 | |
|
330 | 330 | if not embedded: |
|
331 | 331 | try: |
|
332 | 332 | main_name = self.user_ns['__name__'] |
|
333 | 333 | except KeyError: |
|
334 | 334 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' |
|
335 | 335 | else: |
|
336 | 336 | #print "pickle hack in place" # dbg |
|
337 | 337 | #print 'main_name:',main_name # dbg |
|
338 | 338 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
339 | 339 | |
|
340 | 340 | # Now that FakeModule produces a real module, we've run into a nasty |
|
341 | 341 | # problem: after script execution (via %run), the module where the user |
|
342 | 342 | # code ran is deleted. Now that this object is a true module (needed |
|
343 | 343 | # so docetst and other tools work correctly), the Python module |
|
344 | 344 | # teardown mechanism runs over it, and sets to None every variable |
|
345 | 345 | # present in that module. This means that later calls to functions |
|
346 | 346 | # defined in the script (which have become interactively visible after |
|
347 | 347 | # script exit) fail, because they hold references to objects that have |
|
348 | 348 | # become overwritten into None. The only solution I see right now is |
|
349 | 349 | # to protect every FakeModule used by %run by holding an internal |
|
350 | 350 | # reference to it. This private list will be used for that. The |
|
351 | 351 | # %reset command will flush it as well. |
|
352 | 352 | self._user_main_modules = [] |
|
353 | 353 | |
|
354 | 354 | # List of input with multi-line handling. |
|
355 | 355 | # Fill its zero entry, user counter starts at 1 |
|
356 | 356 | self.input_hist = InputList(['\n']) |
|
357 | 357 | # This one will hold the 'raw' input history, without any |
|
358 | 358 | # pre-processing. This will allow users to retrieve the input just as |
|
359 | 359 | # it was exactly typed in by the user, with %hist -r. |
|
360 | 360 | self.input_hist_raw = InputList(['\n']) |
|
361 | 361 | |
|
362 | 362 | # list of visited directories |
|
363 | 363 | try: |
|
364 | 364 | self.dir_hist = [os.getcwd()] |
|
365 | 365 | except OSError: |
|
366 | 366 | self.dir_hist = [] |
|
367 | 367 | |
|
368 | 368 | # dict of output history |
|
369 | 369 | self.output_hist = {} |
|
370 | 370 | |
|
371 | 371 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
372 | 372 | # under Win32 have it set to None, and we need to have a known valid |
|
373 | 373 | # encoding to use in the raw_input() method |
|
374 | 374 | try: |
|
375 | 375 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
376 | 376 | except AttributeError: |
|
377 | 377 | self.stdin_encoding = 'ascii' |
|
378 | 378 | |
|
379 | 379 | # dict of things NOT to alias (keywords, builtins and some magics) |
|
380 | 380 | no_alias = {} |
|
381 | 381 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] |
|
382 | 382 | for key in keyword.kwlist + no_alias_magics: |
|
383 | 383 | no_alias[key] = 1 |
|
384 | 384 | no_alias.update(__builtin__.__dict__) |
|
385 | 385 | self.no_alias = no_alias |
|
386 | 386 | |
|
387 | 387 | # make global variables for user access to these |
|
388 | 388 | self.user_ns['_ih'] = self.input_hist |
|
389 | 389 | self.user_ns['_oh'] = self.output_hist |
|
390 | 390 | self.user_ns['_dh'] = self.dir_hist |
|
391 | 391 | |
|
392 | 392 | # user aliases to input and output histories |
|
393 | 393 | self.user_ns['In'] = self.input_hist |
|
394 | 394 | self.user_ns['Out'] = self.output_hist |
|
395 | 395 | |
|
396 | 396 | self.user_ns['_sh'] = IPython.shadowns |
|
397 | 397 | # Object variable to store code object waiting execution. This is |
|
398 | 398 | # used mainly by the multithreaded shells, but it can come in handy in |
|
399 | 399 | # other situations. No need to use a Queue here, since it's a single |
|
400 | 400 | # item which gets cleared once run. |
|
401 | 401 | self.code_to_run = None |
|
402 | 402 | |
|
403 | 403 | # escapes for automatic behavior on the command line |
|
404 | 404 | self.ESC_SHELL = '!' |
|
405 | 405 | self.ESC_SH_CAP = '!!' |
|
406 | 406 | self.ESC_HELP = '?' |
|
407 | 407 | self.ESC_MAGIC = '%' |
|
408 | 408 | self.ESC_QUOTE = ',' |
|
409 | 409 | self.ESC_QUOTE2 = ';' |
|
410 | 410 | self.ESC_PAREN = '/' |
|
411 | 411 | |
|
412 | 412 | # And their associated handlers |
|
413 | 413 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, |
|
414 | 414 | self.ESC_QUOTE : self.handle_auto, |
|
415 | 415 | self.ESC_QUOTE2 : self.handle_auto, |
|
416 | 416 | self.ESC_MAGIC : self.handle_magic, |
|
417 | 417 | self.ESC_HELP : self.handle_help, |
|
418 | 418 | self.ESC_SHELL : self.handle_shell_escape, |
|
419 | 419 | self.ESC_SH_CAP : self.handle_shell_escape, |
|
420 | 420 | } |
|
421 | 421 | |
|
422 | 422 | # class initializations |
|
423 | 423 | Magic.__init__(self,self) |
|
424 | 424 | |
|
425 | 425 | # Python source parser/formatter for syntax highlighting |
|
426 | 426 | pyformat = PyColorize.Parser().format |
|
427 | 427 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) |
|
428 | 428 | |
|
429 | 429 | # hooks holds pointers used for user-side customizations |
|
430 | 430 | self.hooks = Struct() |
|
431 | 431 | |
|
432 | 432 | self.strdispatchers = {} |
|
433 | 433 | |
|
434 | 434 | # Set all default hooks, defined in the IPython.hooks module. |
|
435 | 435 | hooks = IPython.hooks |
|
436 | 436 | for hook_name in hooks.__all__: |
|
437 | 437 | # default hooks have priority 100, i.e. low; user hooks should have |
|
438 | 438 | # 0-100 priority |
|
439 | 439 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
440 | 440 | #print "bound hook",hook_name |
|
441 | 441 | |
|
442 | 442 | # Flag to mark unconditional exit |
|
443 | 443 | self.exit_now = False |
|
444 | 444 | |
|
445 | 445 | self.usage_min = """\ |
|
446 | 446 | An enhanced console for Python. |
|
447 | 447 | Some of its features are: |
|
448 | 448 | - Readline support if the readline library is present. |
|
449 | 449 | - Tab completion in the local namespace. |
|
450 | 450 | - Logging of input, see command-line options. |
|
451 | 451 | - System shell escape via ! , eg !ls. |
|
452 | 452 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) |
|
453 | 453 | - Keeps track of locally defined variables via %who, %whos. |
|
454 | 454 | - Show object information with a ? eg ?x or x? (use ?? for more info). |
|
455 | 455 | """ |
|
456 | 456 | if usage: self.usage = usage |
|
457 | 457 | else: self.usage = self.usage_min |
|
458 | 458 | |
|
459 | 459 | # Storage |
|
460 | 460 | self.rc = rc # This will hold all configuration information |
|
461 | 461 | self.pager = 'less' |
|
462 | 462 | # temporary files used for various purposes. Deleted at exit. |
|
463 | 463 | self.tempfiles = [] |
|
464 | 464 | |
|
465 | 465 | # Keep track of readline usage (later set by init_readline) |
|
466 | 466 | self.has_readline = False |
|
467 | 467 | |
|
468 | 468 | # template for logfile headers. It gets resolved at runtime by the |
|
469 | 469 | # logstart method. |
|
470 | 470 | self.loghead_tpl = \ |
|
471 | 471 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** |
|
472 | 472 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW |
|
473 | 473 | #log# opts = %s |
|
474 | 474 | #log# args = %s |
|
475 | 475 | #log# It is safe to make manual edits below here. |
|
476 | 476 | #log#----------------------------------------------------------------------- |
|
477 | 477 | """ |
|
478 | 478 | # for pushd/popd management |
|
479 | 479 | try: |
|
480 | 480 | self.home_dir = get_home_dir() |
|
481 | 481 | except HomeDirError,msg: |
|
482 | 482 | fatal(msg) |
|
483 | 483 | |
|
484 | 484 | self.dir_stack = [] |
|
485 | 485 | |
|
486 | 486 | # Functions to call the underlying shell. |
|
487 | 487 | |
|
488 | 488 | # The first is similar to os.system, but it doesn't return a value, |
|
489 | 489 | # and it allows interpolation of variables in the user's namespace. |
|
490 | 490 | self.system = lambda cmd: \ |
|
491 | 491 | self.hooks.shell_hook(self.var_expand(cmd,depth=2)) |
|
492 | 492 | |
|
493 | 493 | # These are for getoutput and getoutputerror: |
|
494 | 494 | self.getoutput = lambda cmd: \ |
|
495 | 495 | getoutput(self.var_expand(cmd,depth=2), |
|
496 | 496 | header=self.rc.system_header, |
|
497 | 497 | verbose=self.rc.system_verbose) |
|
498 | 498 | |
|
499 | 499 | self.getoutputerror = lambda cmd: \ |
|
500 | 500 | getoutputerror(self.var_expand(cmd,depth=2), |
|
501 | 501 | header=self.rc.system_header, |
|
502 | 502 | verbose=self.rc.system_verbose) |
|
503 | 503 | |
|
504 | 504 | |
|
505 | 505 | # keep track of where we started running (mainly for crash post-mortem) |
|
506 | 506 | self.starting_dir = os.getcwd() |
|
507 | 507 | |
|
508 | 508 | # Various switches which can be set |
|
509 | 509 | self.CACHELENGTH = 5000 # this is cheap, it's just text |
|
510 | 510 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ |
|
511 | 511 | self.banner2 = banner2 |
|
512 | 512 | |
|
513 | 513 | # TraceBack handlers: |
|
514 | 514 | |
|
515 | 515 | # Syntax error handler. |
|
516 | 516 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
517 | 517 | |
|
518 | 518 | # The interactive one is initialized with an offset, meaning we always |
|
519 | 519 | # want to remove the topmost item in the traceback, which is our own |
|
520 | 520 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
521 | 521 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', |
|
522 | 522 | color_scheme='NoColor', |
|
523 | 523 | tb_offset = 1) |
|
524 | 524 | |
|
525 | 525 | # IPython itself shouldn't crash. This will produce a detailed |
|
526 | 526 | # post-mortem if it does. But we only install the crash handler for |
|
527 | 527 | # non-threaded shells, the threaded ones use a normal verbose reporter |
|
528 | 528 | # and lose the crash handler. This is because exceptions in the main |
|
529 | 529 | # thread (such as in GUI code) propagate directly to sys.excepthook, |
|
530 | 530 | # and there's no point in printing crash dumps for every user exception. |
|
531 | 531 | if self.isthreaded: |
|
532 | 532 | ipCrashHandler = ultraTB.FormattedTB() |
|
533 | 533 | else: |
|
534 | 534 | from IPython import CrashHandler |
|
535 | 535 | ipCrashHandler = CrashHandler.IPythonCrashHandler(self) |
|
536 | 536 | self.set_crash_handler(ipCrashHandler) |
|
537 | 537 | |
|
538 | 538 | # and add any custom exception handlers the user may have specified |
|
539 | 539 | self.set_custom_exc(*custom_exceptions) |
|
540 | 540 | |
|
541 | 541 | # indentation management |
|
542 | 542 | self.autoindent = False |
|
543 | 543 | self.indent_current_nsp = 0 |
|
544 | 544 | |
|
545 | 545 | # Make some aliases automatically |
|
546 | 546 | # Prepare list of shell aliases to auto-define |
|
547 | 547 | if os.name == 'posix': |
|
548 | 548 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', |
|
549 | 549 | 'mv mv -i','rm rm -i','cp cp -i', |
|
550 | 550 | 'cat cat','less less','clear clear', |
|
551 | 551 | # a better ls |
|
552 | 552 | 'ls ls -F', |
|
553 | 553 | # long ls |
|
554 | 554 | 'll ls -lF') |
|
555 | 555 | # Extra ls aliases with color, which need special treatment on BSD |
|
556 | 556 | # variants |
|
557 | 557 | ls_extra = ( # color ls |
|
558 | 558 | 'lc ls -F -o --color', |
|
559 | 559 | # ls normal files only |
|
560 | 560 | 'lf ls -F -o --color %l | grep ^-', |
|
561 | 561 | # ls symbolic links |
|
562 | 562 | 'lk ls -F -o --color %l | grep ^l', |
|
563 | 563 | # directories or links to directories, |
|
564 | 564 | 'ldir ls -F -o --color %l | grep /$', |
|
565 | 565 | # things which are executable |
|
566 | 566 | 'lx ls -F -o --color %l | grep ^-..x', |
|
567 | 567 | ) |
|
568 | 568 | # The BSDs don't ship GNU ls, so they don't understand the |
|
569 | 569 | # --color switch out of the box |
|
570 | 570 | if 'bsd' in sys.platform: |
|
571 | 571 | ls_extra = ( # ls normal files only |
|
572 | 572 | 'lf ls -lF | grep ^-', |
|
573 | 573 | # ls symbolic links |
|
574 | 574 | 'lk ls -lF | grep ^l', |
|
575 | 575 | # directories or links to directories, |
|
576 | 576 | 'ldir ls -lF | grep /$', |
|
577 | 577 | # things which are executable |
|
578 | 578 | 'lx ls -lF | grep ^-..x', |
|
579 | 579 | ) |
|
580 | 580 | auto_alias = auto_alias + ls_extra |
|
581 | 581 | elif os.name in ['nt','dos']: |
|
582 | 582 | auto_alias = ('ls dir /on', |
|
583 | 583 | 'ddir dir /ad /on', 'ldir dir /ad /on', |
|
584 | 584 | 'mkdir mkdir','rmdir rmdir','echo echo', |
|
585 | 585 | 'ren ren','cls cls','copy copy') |
|
586 | 586 | else: |
|
587 | 587 | auto_alias = () |
|
588 | 588 | self.auto_alias = [s.split(None,1) for s in auto_alias] |
|
589 | 589 | |
|
590 | 590 | |
|
591 | 591 | # Produce a public API instance |
|
592 | 592 | self.api = IPython.ipapi.IPApi(self) |
|
593 | 593 | |
|
594 | 594 | # Call the actual (public) initializer |
|
595 | 595 | self.init_auto_alias() |
|
596 | 596 | |
|
597 | 597 | # track which builtins we add, so we can clean up later |
|
598 | 598 | self.builtins_added = {} |
|
599 | 599 | # This method will add the necessary builtins for operation, but |
|
600 | 600 | # tracking what it did via the builtins_added dict. |
|
601 | 601 | |
|
602 | 602 | #TODO: remove this, redundant |
|
603 | 603 | self.add_builtins() |
|
604 | 604 | |
|
605 | 605 | |
|
606 | 606 | |
|
607 | 607 | |
|
608 | 608 | # end __init__ |
|
609 | 609 | |
|
610 | 610 | def var_expand(self,cmd,depth=0): |
|
611 | 611 | """Expand python variables in a string. |
|
612 | 612 | |
|
613 | 613 | The depth argument indicates how many frames above the caller should |
|
614 | 614 | be walked to look for the local namespace where to expand variables. |
|
615 | 615 | |
|
616 | 616 | The global namespace for expansion is always the user's interactive |
|
617 | 617 | namespace. |
|
618 | 618 | """ |
|
619 | 619 | |
|
620 | 620 | return str(ItplNS(cmd, |
|
621 | 621 | self.user_ns, # globals |
|
622 | 622 | # Skip our own frame in searching for locals: |
|
623 | 623 | sys._getframe(depth+1).f_locals # locals |
|
624 | 624 | )) |
|
625 | 625 | |
|
626 | 626 | def pre_config_initialization(self): |
|
627 | 627 | """Pre-configuration init method |
|
628 | 628 | |
|
629 | 629 | This is called before the configuration files are processed to |
|
630 | 630 | prepare the services the config files might need. |
|
631 | 631 | |
|
632 | 632 | self.rc already has reasonable default values at this point. |
|
633 | 633 | """ |
|
634 | 634 | rc = self.rc |
|
635 | 635 | try: |
|
636 | 636 | self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db") |
|
637 | 637 | except exceptions.UnicodeDecodeError: |
|
638 | 638 | print "Your ipythondir can't be decoded to unicode!" |
|
639 | 639 | print "Please set HOME environment variable to something that" |
|
640 | 640 | print r"only has ASCII characters, e.g. c:\home" |
|
641 | 641 | print "Now it is",rc.ipythondir |
|
642 | 642 | sys.exit() |
|
643 | 643 | self.shadowhist = IPython.history.ShadowHist(self.db) |
|
644 | 644 | |
|
645 | 645 | |
|
646 | 646 | def post_config_initialization(self): |
|
647 | 647 | """Post configuration init method |
|
648 | 648 | |
|
649 | 649 | This is called after the configuration files have been processed to |
|
650 | 650 | 'finalize' the initialization.""" |
|
651 | 651 | |
|
652 | 652 | rc = self.rc |
|
653 | 653 | |
|
654 | 654 | # Object inspector |
|
655 | 655 | self.inspector = OInspect.Inspector(OInspect.InspectColors, |
|
656 | 656 | PyColorize.ANSICodeColors, |
|
657 | 657 | 'NoColor', |
|
658 | 658 | rc.object_info_string_level) |
|
659 | 659 | |
|
660 | 660 | self.rl_next_input = None |
|
661 | 661 | self.rl_do_indent = False |
|
662 | 662 | # Load readline proper |
|
663 | 663 | if rc.readline: |
|
664 | 664 | self.init_readline() |
|
665 | 665 | |
|
666 | 666 | |
|
667 | 667 | # local shortcut, this is used a LOT |
|
668 | 668 | self.log = self.logger.log |
|
669 | 669 | |
|
670 | 670 | # Initialize cache, set in/out prompts and printing system |
|
671 | 671 | self.outputcache = CachedOutput(self, |
|
672 | 672 | rc.cache_size, |
|
673 | 673 | rc.pprint, |
|
674 | 674 | input_sep = rc.separate_in, |
|
675 | 675 | output_sep = rc.separate_out, |
|
676 | 676 | output_sep2 = rc.separate_out2, |
|
677 | 677 | ps1 = rc.prompt_in1, |
|
678 | 678 | ps2 = rc.prompt_in2, |
|
679 | 679 | ps_out = rc.prompt_out, |
|
680 | 680 | pad_left = rc.prompts_pad_left) |
|
681 | 681 | |
|
682 | 682 | # user may have over-ridden the default print hook: |
|
683 | 683 | try: |
|
684 | 684 | self.outputcache.__class__.display = self.hooks.display |
|
685 | 685 | except AttributeError: |
|
686 | 686 | pass |
|
687 | 687 | |
|
688 | 688 | # I don't like assigning globally to sys, because it means when |
|
689 | 689 | # embedding instances, each embedded instance overrides the previous |
|
690 | 690 | # choice. But sys.displayhook seems to be called internally by exec, |
|
691 | 691 | # so I don't see a way around it. We first save the original and then |
|
692 | 692 | # overwrite it. |
|
693 | 693 | self.sys_displayhook = sys.displayhook |
|
694 | 694 | sys.displayhook = self.outputcache |
|
695 | 695 | |
|
696 | 696 | # Do a proper resetting of doctest, including the necessary displayhook |
|
697 | 697 | # monkeypatching |
|
698 | 698 | try: |
|
699 | 699 | doctest_reload() |
|
700 | 700 | except ImportError: |
|
701 | 701 | warn("doctest module does not exist.") |
|
702 | 702 | |
|
703 | 703 | # Set user colors (don't do it in the constructor above so that it |
|
704 | 704 | # doesn't crash if colors option is invalid) |
|
705 | 705 | self.magic_colors(rc.colors) |
|
706 | 706 | |
|
707 | 707 | # Set calling of pdb on exceptions |
|
708 | 708 | self.call_pdb = rc.pdb |
|
709 | 709 | |
|
710 | 710 | # Load user aliases |
|
711 | 711 | for alias in rc.alias: |
|
712 | 712 | self.magic_alias(alias) |
|
713 | 713 | |
|
714 | 714 | self.hooks.late_startup_hook() |
|
715 | 715 | |
|
716 | 716 | for cmd in self.rc.autoexec: |
|
717 | 717 | #print "autoexec>",cmd #dbg |
|
718 | 718 | self.api.runlines(cmd) |
|
719 | 719 | |
|
720 | 720 | batchrun = False |
|
721 | 721 | for batchfile in [path(arg) for arg in self.rc.args |
|
722 | 722 | if arg.lower().endswith('.ipy')]: |
|
723 | 723 | if not batchfile.isfile(): |
|
724 | 724 | print "No such batch file:", batchfile |
|
725 | 725 | continue |
|
726 | 726 | self.api.runlines(batchfile.text()) |
|
727 | 727 | batchrun = True |
|
728 | 728 | # without -i option, exit after running the batch file |
|
729 | 729 | if batchrun and not self.rc.interact: |
|
730 |
self. |
|
|
730 | self.ask_exit() | |
|
731 | 731 | |
|
732 | 732 | def add_builtins(self): |
|
733 | 733 | """Store ipython references into the builtin namespace. |
|
734 | 734 | |
|
735 | 735 | Some parts of ipython operate via builtins injected here, which hold a |
|
736 | 736 | reference to IPython itself.""" |
|
737 | 737 | |
|
738 | 738 | # TODO: deprecate all of these, they are unsafe |
|
739 | 739 | builtins_new = dict(__IPYTHON__ = self, |
|
740 | 740 | ip_set_hook = self.set_hook, |
|
741 | 741 | jobs = self.jobs, |
|
742 | 742 | ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'), |
|
743 | 743 | ipalias = wrap_deprecated(self.ipalias), |
|
744 | 744 | ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'), |
|
745 | 745 | #_ip = self.api |
|
746 | 746 | ) |
|
747 | 747 | for biname,bival in builtins_new.items(): |
|
748 | 748 | try: |
|
749 | 749 | # store the orignal value so we can restore it |
|
750 | 750 | self.builtins_added[biname] = __builtin__.__dict__[biname] |
|
751 | 751 | except KeyError: |
|
752 | 752 | # or mark that it wasn't defined, and we'll just delete it at |
|
753 | 753 | # cleanup |
|
754 | 754 | self.builtins_added[biname] = Undefined |
|
755 | 755 | __builtin__.__dict__[biname] = bival |
|
756 | 756 | |
|
757 | 757 | # Keep in the builtins a flag for when IPython is active. We set it |
|
758 | 758 | # with setdefault so that multiple nested IPythons don't clobber one |
|
759 | 759 | # another. Each will increase its value by one upon being activated, |
|
760 | 760 | # which also gives us a way to determine the nesting level. |
|
761 | 761 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) |
|
762 | 762 | |
|
763 | 763 | def clean_builtins(self): |
|
764 | 764 | """Remove any builtins which might have been added by add_builtins, or |
|
765 | 765 | restore overwritten ones to their previous values.""" |
|
766 | 766 | for biname,bival in self.builtins_added.items(): |
|
767 | 767 | if bival is Undefined: |
|
768 | 768 | del __builtin__.__dict__[biname] |
|
769 | 769 | else: |
|
770 | 770 | __builtin__.__dict__[biname] = bival |
|
771 | 771 | self.builtins_added.clear() |
|
772 | 772 | |
|
773 | 773 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
774 | 774 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
775 | 775 | |
|
776 | 776 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
777 | 777 | adding your function to one of these hooks, you can modify IPython's |
|
778 | 778 | behavior to call at runtime your own routines.""" |
|
779 | 779 | |
|
780 | 780 | # At some point in the future, this should validate the hook before it |
|
781 | 781 | # accepts it. Probably at least check that the hook takes the number |
|
782 | 782 | # of args it's supposed to. |
|
783 | 783 | |
|
784 | 784 | f = new.instancemethod(hook,self,self.__class__) |
|
785 | 785 | |
|
786 | 786 | # check if the hook is for strdispatcher first |
|
787 | 787 | if str_key is not None: |
|
788 | 788 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
789 | 789 | sdp.add_s(str_key, f, priority ) |
|
790 | 790 | self.strdispatchers[name] = sdp |
|
791 | 791 | return |
|
792 | 792 | if re_key is not None: |
|
793 | 793 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
794 | 794 | sdp.add_re(re.compile(re_key), f, priority ) |
|
795 | 795 | self.strdispatchers[name] = sdp |
|
796 | 796 | return |
|
797 | 797 | |
|
798 | 798 | dp = getattr(self.hooks, name, None) |
|
799 | 799 | if name not in IPython.hooks.__all__: |
|
800 | 800 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ ) |
|
801 | 801 | if not dp: |
|
802 | 802 | dp = IPython.hooks.CommandChainDispatcher() |
|
803 | 803 | |
|
804 | 804 | try: |
|
805 | 805 | dp.add(f,priority) |
|
806 | 806 | except AttributeError: |
|
807 | 807 | # it was not commandchain, plain old func - replace |
|
808 | 808 | dp = f |
|
809 | 809 | |
|
810 | 810 | setattr(self.hooks,name, dp) |
|
811 | 811 | |
|
812 | 812 | |
|
813 | 813 | #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) |
|
814 | 814 | |
|
815 | 815 | def set_crash_handler(self,crashHandler): |
|
816 | 816 | """Set the IPython crash handler. |
|
817 | 817 | |
|
818 | 818 | This must be a callable with a signature suitable for use as |
|
819 | 819 | sys.excepthook.""" |
|
820 | 820 | |
|
821 | 821 | # Install the given crash handler as the Python exception hook |
|
822 | 822 | sys.excepthook = crashHandler |
|
823 | 823 | |
|
824 | 824 | # The instance will store a pointer to this, so that runtime code |
|
825 | 825 | # (such as magics) can access it. This is because during the |
|
826 | 826 | # read-eval loop, it gets temporarily overwritten (to deal with GUI |
|
827 | 827 | # frameworks). |
|
828 | 828 | self.sys_excepthook = sys.excepthook |
|
829 | 829 | |
|
830 | 830 | |
|
831 | 831 | def set_custom_exc(self,exc_tuple,handler): |
|
832 | 832 | """set_custom_exc(exc_tuple,handler) |
|
833 | 833 | |
|
834 | 834 | Set a custom exception handler, which will be called if any of the |
|
835 | 835 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
836 | 836 | runcode() method. |
|
837 | 837 | |
|
838 | 838 | Inputs: |
|
839 | 839 | |
|
840 | 840 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
841 | 841 | handler for. It is very important that you use a tuple, and NOT A |
|
842 | 842 | LIST here, because of the way Python's except statement works. If |
|
843 | 843 | you only want to trap a single exception, use a singleton tuple: |
|
844 | 844 | |
|
845 | 845 | exc_tuple == (MyCustomException,) |
|
846 | 846 | |
|
847 | 847 | - handler: this must be defined as a function with the following |
|
848 | 848 | basic interface: def my_handler(self,etype,value,tb). |
|
849 | 849 | |
|
850 | 850 | This will be made into an instance method (via new.instancemethod) |
|
851 | 851 | of IPython itself, and it will be called if any of the exceptions |
|
852 | 852 | listed in the exc_tuple are caught. If the handler is None, an |
|
853 | 853 | internal basic one is used, which just prints basic info. |
|
854 | 854 | |
|
855 | 855 | WARNING: by putting in your own exception handler into IPython's main |
|
856 | 856 | execution loop, you run a very good chance of nasty crashes. This |
|
857 | 857 | facility should only be used if you really know what you are doing.""" |
|
858 | 858 | |
|
859 | 859 | assert type(exc_tuple)==type(()) , \ |
|
860 | 860 | "The custom exceptions must be given AS A TUPLE." |
|
861 | 861 | |
|
862 | 862 | def dummy_handler(self,etype,value,tb): |
|
863 | 863 | print '*** Simple custom exception handler ***' |
|
864 | 864 | print 'Exception type :',etype |
|
865 | 865 | print 'Exception value:',value |
|
866 | 866 | print 'Traceback :',tb |
|
867 | 867 | print 'Source code :','\n'.join(self.buffer) |
|
868 | 868 | |
|
869 | 869 | if handler is None: handler = dummy_handler |
|
870 | 870 | |
|
871 | 871 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
872 | 872 | self.custom_exceptions = exc_tuple |
|
873 | 873 | |
|
874 | 874 | def set_custom_completer(self,completer,pos=0): |
|
875 | 875 | """set_custom_completer(completer,pos=0) |
|
876 | 876 | |
|
877 | 877 | Adds a new custom completer function. |
|
878 | 878 | |
|
879 | 879 | The position argument (defaults to 0) is the index in the completers |
|
880 | 880 | list where you want the completer to be inserted.""" |
|
881 | 881 | |
|
882 | 882 | newcomp = new.instancemethod(completer,self.Completer, |
|
883 | 883 | self.Completer.__class__) |
|
884 | 884 | self.Completer.matchers.insert(pos,newcomp) |
|
885 | 885 | |
|
886 | 886 | def set_completer(self): |
|
887 | 887 | """reset readline's completer to be our own.""" |
|
888 | 888 | self.readline.set_completer(self.Completer.complete) |
|
889 | 889 | |
|
890 | 890 | def _get_call_pdb(self): |
|
891 | 891 | return self._call_pdb |
|
892 | 892 | |
|
893 | 893 | def _set_call_pdb(self,val): |
|
894 | 894 | |
|
895 | 895 | if val not in (0,1,False,True): |
|
896 | 896 | raise ValueError,'new call_pdb value must be boolean' |
|
897 | 897 | |
|
898 | 898 | # store value in instance |
|
899 | 899 | self._call_pdb = val |
|
900 | 900 | |
|
901 | 901 | # notify the actual exception handlers |
|
902 | 902 | self.InteractiveTB.call_pdb = val |
|
903 | 903 | if self.isthreaded: |
|
904 | 904 | try: |
|
905 | 905 | self.sys_excepthook.call_pdb = val |
|
906 | 906 | except: |
|
907 | 907 | warn('Failed to activate pdb for threaded exception handler') |
|
908 | 908 | |
|
909 | 909 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
910 | 910 | 'Control auto-activation of pdb at exceptions') |
|
911 | 911 | |
|
912 | 912 | |
|
913 | 913 | # These special functions get installed in the builtin namespace, to |
|
914 | 914 | # provide programmatic (pure python) access to magics, aliases and system |
|
915 | 915 | # calls. This is important for logging, user scripting, and more. |
|
916 | 916 | |
|
917 | 917 | # We are basically exposing, via normal python functions, the three |
|
918 | 918 | # mechanisms in which ipython offers special call modes (magics for |
|
919 | 919 | # internal control, aliases for direct system access via pre-selected |
|
920 | 920 | # names, and !cmd for calling arbitrary system commands). |
|
921 | 921 | |
|
922 | 922 | def ipmagic(self,arg_s): |
|
923 | 923 | """Call a magic function by name. |
|
924 | 924 | |
|
925 | 925 | Input: a string containing the name of the magic function to call and any |
|
926 | 926 | additional arguments to be passed to the magic. |
|
927 | 927 | |
|
928 | 928 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython |
|
929 | 929 | prompt: |
|
930 | 930 | |
|
931 | 931 | In[1]: %name -opt foo bar |
|
932 | 932 | |
|
933 | 933 | To call a magic without arguments, simply use ipmagic('name'). |
|
934 | 934 | |
|
935 | 935 | This provides a proper Python function to call IPython's magics in any |
|
936 | 936 | valid Python code you can type at the interpreter, including loops and |
|
937 | 937 | compound statements. It is added by IPython to the Python builtin |
|
938 | 938 | namespace upon initialization.""" |
|
939 | 939 | |
|
940 | 940 | args = arg_s.split(' ',1) |
|
941 | 941 | magic_name = args[0] |
|
942 | 942 | magic_name = magic_name.lstrip(self.ESC_MAGIC) |
|
943 | 943 | |
|
944 | 944 | try: |
|
945 | 945 | magic_args = args[1] |
|
946 | 946 | except IndexError: |
|
947 | 947 | magic_args = '' |
|
948 | 948 | fn = getattr(self,'magic_'+magic_name,None) |
|
949 | 949 | if fn is None: |
|
950 | 950 | error("Magic function `%s` not found." % magic_name) |
|
951 | 951 | else: |
|
952 | 952 | magic_args = self.var_expand(magic_args,1) |
|
953 | 953 | return fn(magic_args) |
|
954 | 954 | |
|
955 | 955 | def ipalias(self,arg_s): |
|
956 | 956 | """Call an alias by name. |
|
957 | 957 | |
|
958 | 958 | Input: a string containing the name of the alias to call and any |
|
959 | 959 | additional arguments to be passed to the magic. |
|
960 | 960 | |
|
961 | 961 | ipalias('name -opt foo bar') is equivalent to typing at the ipython |
|
962 | 962 | prompt: |
|
963 | 963 | |
|
964 | 964 | In[1]: name -opt foo bar |
|
965 | 965 | |
|
966 | 966 | To call an alias without arguments, simply use ipalias('name'). |
|
967 | 967 | |
|
968 | 968 | This provides a proper Python function to call IPython's aliases in any |
|
969 | 969 | valid Python code you can type at the interpreter, including loops and |
|
970 | 970 | compound statements. It is added by IPython to the Python builtin |
|
971 | 971 | namespace upon initialization.""" |
|
972 | 972 | |
|
973 | 973 | args = arg_s.split(' ',1) |
|
974 | 974 | alias_name = args[0] |
|
975 | 975 | try: |
|
976 | 976 | alias_args = args[1] |
|
977 | 977 | except IndexError: |
|
978 | 978 | alias_args = '' |
|
979 | 979 | if alias_name in self.alias_table: |
|
980 | 980 | self.call_alias(alias_name,alias_args) |
|
981 | 981 | else: |
|
982 | 982 | error("Alias `%s` not found." % alias_name) |
|
983 | 983 | |
|
984 | 984 | def ipsystem(self,arg_s): |
|
985 | 985 | """Make a system call, using IPython.""" |
|
986 | 986 | |
|
987 | 987 | self.system(arg_s) |
|
988 | 988 | |
|
989 | 989 | def complete(self,text): |
|
990 | 990 | """Return a sorted list of all possible completions on text. |
|
991 | 991 | |
|
992 | 992 | Inputs: |
|
993 | 993 | |
|
994 | 994 | - text: a string of text to be completed on. |
|
995 | 995 | |
|
996 | 996 | This is a wrapper around the completion mechanism, similar to what |
|
997 | 997 | readline does at the command line when the TAB key is hit. By |
|
998 | 998 | exposing it as a method, it can be used by other non-readline |
|
999 | 999 | environments (such as GUIs) for text completion. |
|
1000 | 1000 | |
|
1001 | 1001 | Simple usage example: |
|
1002 | 1002 | |
|
1003 | 1003 | In [7]: x = 'hello' |
|
1004 | 1004 | |
|
1005 | 1005 | In [8]: x |
|
1006 | 1006 | Out[8]: 'hello' |
|
1007 | 1007 | |
|
1008 | 1008 | In [9]: print x |
|
1009 | 1009 | hello |
|
1010 | 1010 | |
|
1011 | 1011 | In [10]: _ip.IP.complete('x.l') |
|
1012 | 1012 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] # randomX |
|
1013 | 1013 | """ |
|
1014 | 1014 | |
|
1015 | 1015 | complete = self.Completer.complete |
|
1016 | 1016 | state = 0 |
|
1017 | 1017 | # use a dict so we get unique keys, since ipyhton's multiple |
|
1018 | 1018 | # completers can return duplicates. When we make 2.4 a requirement, |
|
1019 | 1019 | # start using sets instead, which are faster. |
|
1020 | 1020 | comps = {} |
|
1021 | 1021 | while True: |
|
1022 | 1022 | newcomp = complete(text,state,line_buffer=text) |
|
1023 | 1023 | if newcomp is None: |
|
1024 | 1024 | break |
|
1025 | 1025 | comps[newcomp] = 1 |
|
1026 | 1026 | state += 1 |
|
1027 | 1027 | outcomps = comps.keys() |
|
1028 | 1028 | outcomps.sort() |
|
1029 | 1029 | #print "T:",text,"OC:",outcomps # dbg |
|
1030 | 1030 | #print "vars:",self.user_ns.keys() |
|
1031 | 1031 | return outcomps |
|
1032 | 1032 | |
|
1033 | 1033 | def set_completer_frame(self, frame=None): |
|
1034 | 1034 | if frame: |
|
1035 | 1035 | self.Completer.namespace = frame.f_locals |
|
1036 | 1036 | self.Completer.global_namespace = frame.f_globals |
|
1037 | 1037 | else: |
|
1038 | 1038 | self.Completer.namespace = self.user_ns |
|
1039 | 1039 | self.Completer.global_namespace = self.user_global_ns |
|
1040 | 1040 | |
|
1041 | 1041 | def init_auto_alias(self): |
|
1042 | 1042 | """Define some aliases automatically. |
|
1043 | 1043 | |
|
1044 | 1044 | These are ALL parameter-less aliases""" |
|
1045 | 1045 | |
|
1046 | 1046 | for alias,cmd in self.auto_alias: |
|
1047 | 1047 | self.getapi().defalias(alias,cmd) |
|
1048 | 1048 | |
|
1049 | 1049 | |
|
1050 | 1050 | def alias_table_validate(self,verbose=0): |
|
1051 | 1051 | """Update information about the alias table. |
|
1052 | 1052 | |
|
1053 | 1053 | In particular, make sure no Python keywords/builtins are in it.""" |
|
1054 | 1054 | |
|
1055 | 1055 | no_alias = self.no_alias |
|
1056 | 1056 | for k in self.alias_table.keys(): |
|
1057 | 1057 | if k in no_alias: |
|
1058 | 1058 | del self.alias_table[k] |
|
1059 | 1059 | if verbose: |
|
1060 | 1060 | print ("Deleting alias <%s>, it's a Python " |
|
1061 | 1061 | "keyword or builtin." % k) |
|
1062 | 1062 | |
|
1063 | 1063 | def set_autoindent(self,value=None): |
|
1064 | 1064 | """Set the autoindent flag, checking for readline support. |
|
1065 | 1065 | |
|
1066 | 1066 | If called with no arguments, it acts as a toggle.""" |
|
1067 | 1067 | |
|
1068 | 1068 | if not self.has_readline: |
|
1069 | 1069 | if os.name == 'posix': |
|
1070 | 1070 | warn("The auto-indent feature requires the readline library") |
|
1071 | 1071 | self.autoindent = 0 |
|
1072 | 1072 | return |
|
1073 | 1073 | if value is None: |
|
1074 | 1074 | self.autoindent = not self.autoindent |
|
1075 | 1075 | else: |
|
1076 | 1076 | self.autoindent = value |
|
1077 | 1077 | |
|
1078 | 1078 | def rc_set_toggle(self,rc_field,value=None): |
|
1079 | 1079 | """Set or toggle a field in IPython's rc config. structure. |
|
1080 | 1080 | |
|
1081 | 1081 | If called with no arguments, it acts as a toggle. |
|
1082 | 1082 | |
|
1083 | 1083 | If called with a non-existent field, the resulting AttributeError |
|
1084 | 1084 | exception will propagate out.""" |
|
1085 | 1085 | |
|
1086 | 1086 | rc_val = getattr(self.rc,rc_field) |
|
1087 | 1087 | if value is None: |
|
1088 | 1088 | value = not rc_val |
|
1089 | 1089 | setattr(self.rc,rc_field,value) |
|
1090 | 1090 | |
|
1091 | 1091 | def user_setup(self,ipythondir,rc_suffix,mode='install'): |
|
1092 | 1092 | """Install the user configuration directory. |
|
1093 | 1093 | |
|
1094 | 1094 | Can be called when running for the first time or to upgrade the user's |
|
1095 | 1095 | .ipython/ directory with the mode parameter. Valid modes are 'install' |
|
1096 | 1096 | and 'upgrade'.""" |
|
1097 | 1097 | |
|
1098 | 1098 | def wait(): |
|
1099 | 1099 | try: |
|
1100 | 1100 | raw_input("Please press <RETURN> to start IPython.") |
|
1101 | 1101 | except EOFError: |
|
1102 | 1102 | print >> Term.cout |
|
1103 | 1103 | print '*'*70 |
|
1104 | 1104 | |
|
1105 | 1105 | cwd = os.getcwd() # remember where we started |
|
1106 | 1106 | glb = glob.glob |
|
1107 | 1107 | print '*'*70 |
|
1108 | 1108 | if mode == 'install': |
|
1109 | 1109 | print \ |
|
1110 | 1110 | """Welcome to IPython. I will try to create a personal configuration directory |
|
1111 | 1111 | where you can customize many aspects of IPython's functionality in:\n""" |
|
1112 | 1112 | else: |
|
1113 | 1113 | print 'I am going to upgrade your configuration in:' |
|
1114 | 1114 | |
|
1115 | 1115 | print ipythondir |
|
1116 | 1116 | |
|
1117 | 1117 | rcdirend = os.path.join('IPython','UserConfig') |
|
1118 | 1118 | cfg = lambda d: os.path.join(d,rcdirend) |
|
1119 | 1119 | try: |
|
1120 | 1120 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] |
|
1121 | 1121 | print "Initializing from configuration",rcdir |
|
1122 | 1122 | except IndexError: |
|
1123 | 1123 | warning = """ |
|
1124 | 1124 | Installation error. IPython's directory was not found. |
|
1125 | 1125 | |
|
1126 | 1126 | Check the following: |
|
1127 | 1127 | |
|
1128 | 1128 | The ipython/IPython directory should be in a directory belonging to your |
|
1129 | 1129 | PYTHONPATH environment variable (that is, it should be in a directory |
|
1130 | 1130 | belonging to sys.path). You can copy it explicitly there or just link to it. |
|
1131 | 1131 | |
|
1132 | 1132 | IPython will create a minimal default configuration for you. |
|
1133 | 1133 | |
|
1134 | 1134 | """ |
|
1135 | 1135 | warn(warning) |
|
1136 | 1136 | wait() |
|
1137 | 1137 | |
|
1138 | 1138 | if sys.platform =='win32': |
|
1139 | 1139 | inif = 'ipythonrc.ini' |
|
1140 | 1140 | else: |
|
1141 | 1141 | inif = 'ipythonrc' |
|
1142 | 1142 | minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', inif : '# intentionally left blank' } |
|
1143 | 1143 | os.makedirs(ipythondir, mode = 0777) |
|
1144 | 1144 | for f, cont in minimal_setup.items(): |
|
1145 | 1145 | open(ipythondir + '/' + f,'w').write(cont) |
|
1146 | 1146 | |
|
1147 | 1147 | return |
|
1148 | 1148 | |
|
1149 | 1149 | if mode == 'install': |
|
1150 | 1150 | try: |
|
1151 | 1151 | shutil.copytree(rcdir,ipythondir) |
|
1152 | 1152 | os.chdir(ipythondir) |
|
1153 | 1153 | rc_files = glb("ipythonrc*") |
|
1154 | 1154 | for rc_file in rc_files: |
|
1155 | 1155 | os.rename(rc_file,rc_file+rc_suffix) |
|
1156 | 1156 | except: |
|
1157 | 1157 | warning = """ |
|
1158 | 1158 | |
|
1159 | 1159 | There was a problem with the installation: |
|
1160 | 1160 | %s |
|
1161 | 1161 | Try to correct it or contact the developers if you think it's a bug. |
|
1162 | 1162 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] |
|
1163 | 1163 | warn(warning) |
|
1164 | 1164 | wait() |
|
1165 | 1165 | return |
|
1166 | 1166 | |
|
1167 | 1167 | elif mode == 'upgrade': |
|
1168 | 1168 | try: |
|
1169 | 1169 | os.chdir(ipythondir) |
|
1170 | 1170 | except: |
|
1171 | 1171 | print """ |
|
1172 | 1172 | Can not upgrade: changing to directory %s failed. Details: |
|
1173 | 1173 | %s |
|
1174 | 1174 | """ % (ipythondir,sys.exc_info()[1]) |
|
1175 | 1175 | wait() |
|
1176 | 1176 | return |
|
1177 | 1177 | else: |
|
1178 | 1178 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) |
|
1179 | 1179 | for new_full_path in sources: |
|
1180 | 1180 | new_filename = os.path.basename(new_full_path) |
|
1181 | 1181 | if new_filename.startswith('ipythonrc'): |
|
1182 | 1182 | new_filename = new_filename + rc_suffix |
|
1183 | 1183 | # The config directory should only contain files, skip any |
|
1184 | 1184 | # directories which may be there (like CVS) |
|
1185 | 1185 | if os.path.isdir(new_full_path): |
|
1186 | 1186 | continue |
|
1187 | 1187 | if os.path.exists(new_filename): |
|
1188 | 1188 | old_file = new_filename+'.old' |
|
1189 | 1189 | if os.path.exists(old_file): |
|
1190 | 1190 | os.remove(old_file) |
|
1191 | 1191 | os.rename(new_filename,old_file) |
|
1192 | 1192 | shutil.copy(new_full_path,new_filename) |
|
1193 | 1193 | else: |
|
1194 | 1194 | raise ValueError,'unrecognized mode for install:',`mode` |
|
1195 | 1195 | |
|
1196 | 1196 | # Fix line-endings to those native to each platform in the config |
|
1197 | 1197 | # directory. |
|
1198 | 1198 | try: |
|
1199 | 1199 | os.chdir(ipythondir) |
|
1200 | 1200 | except: |
|
1201 | 1201 | print """ |
|
1202 | 1202 | Problem: changing to directory %s failed. |
|
1203 | 1203 | Details: |
|
1204 | 1204 | %s |
|
1205 | 1205 | |
|
1206 | 1206 | Some configuration files may have incorrect line endings. This should not |
|
1207 | 1207 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) |
|
1208 | 1208 | wait() |
|
1209 | 1209 | else: |
|
1210 | 1210 | for fname in glb('ipythonrc*'): |
|
1211 | 1211 | try: |
|
1212 | 1212 | native_line_ends(fname,backup=0) |
|
1213 | 1213 | except IOError: |
|
1214 | 1214 | pass |
|
1215 | 1215 | |
|
1216 | 1216 | if mode == 'install': |
|
1217 | 1217 | print """ |
|
1218 | 1218 | Successful installation! |
|
1219 | 1219 | |
|
1220 | 1220 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the |
|
1221 | 1221 | IPython manual (there are both HTML and PDF versions supplied with the |
|
1222 | 1222 | distribution) to make sure that your system environment is properly configured |
|
1223 | 1223 | to take advantage of IPython's features. |
|
1224 | 1224 | |
|
1225 | 1225 | Important note: the configuration system has changed! The old system is |
|
1226 | 1226 | still in place, but its setting may be partly overridden by the settings in |
|
1227 | 1227 | "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file |
|
1228 | 1228 | if some of the new settings bother you. |
|
1229 | 1229 | |
|
1230 | 1230 | """ |
|
1231 | 1231 | else: |
|
1232 | 1232 | print """ |
|
1233 | 1233 | Successful upgrade! |
|
1234 | 1234 | |
|
1235 | 1235 | All files in your directory: |
|
1236 | 1236 | %(ipythondir)s |
|
1237 | 1237 | which would have been overwritten by the upgrade were backed up with a .old |
|
1238 | 1238 | extension. If you had made particular customizations in those files you may |
|
1239 | 1239 | want to merge them back into the new files.""" % locals() |
|
1240 | 1240 | wait() |
|
1241 | 1241 | os.chdir(cwd) |
|
1242 | 1242 | # end user_setup() |
|
1243 | 1243 | |
|
1244 | 1244 | def atexit_operations(self): |
|
1245 | 1245 | """This will be executed at the time of exit. |
|
1246 | 1246 | |
|
1247 | 1247 | Saving of persistent data should be performed here. """ |
|
1248 | 1248 | |
|
1249 | 1249 | #print '*** IPython exit cleanup ***' # dbg |
|
1250 | 1250 | # input history |
|
1251 | 1251 | self.savehist() |
|
1252 | 1252 | |
|
1253 | 1253 | # Cleanup all tempfiles left around |
|
1254 | 1254 | for tfile in self.tempfiles: |
|
1255 | 1255 | try: |
|
1256 | 1256 | os.unlink(tfile) |
|
1257 | 1257 | except OSError: |
|
1258 | 1258 | pass |
|
1259 | 1259 | |
|
1260 | 1260 | self.hooks.shutdown_hook() |
|
1261 | 1261 | |
|
1262 | 1262 | def savehist(self): |
|
1263 | 1263 | """Save input history to a file (via readline library).""" |
|
1264 | 1264 | |
|
1265 | 1265 | if not self.has_readline: |
|
1266 | 1266 | return |
|
1267 | 1267 | |
|
1268 | 1268 | try: |
|
1269 | 1269 | self.readline.write_history_file(self.histfile) |
|
1270 | 1270 | except: |
|
1271 | 1271 | print 'Unable to save IPython command history to file: ' + \ |
|
1272 | 1272 | `self.histfile` |
|
1273 | 1273 | |
|
1274 | 1274 | def reloadhist(self): |
|
1275 | 1275 | """Reload the input history from disk file.""" |
|
1276 | 1276 | |
|
1277 | 1277 | if self.has_readline: |
|
1278 | 1278 | try: |
|
1279 | 1279 | self.readline.clear_history() |
|
1280 | 1280 | self.readline.read_history_file(self.shell.histfile) |
|
1281 | 1281 | except AttributeError: |
|
1282 | 1282 | pass |
|
1283 | 1283 | |
|
1284 | 1284 | |
|
1285 | 1285 | def history_saving_wrapper(self, func): |
|
1286 | 1286 | """ Wrap func for readline history saving |
|
1287 | 1287 | |
|
1288 | 1288 | Convert func into callable that saves & restores |
|
1289 | 1289 | history around the call """ |
|
1290 | 1290 | |
|
1291 | 1291 | if not self.has_readline: |
|
1292 | 1292 | return func |
|
1293 | 1293 | |
|
1294 | 1294 | def wrapper(): |
|
1295 | 1295 | self.savehist() |
|
1296 | 1296 | try: |
|
1297 | 1297 | func() |
|
1298 | 1298 | finally: |
|
1299 | 1299 | readline.read_history_file(self.histfile) |
|
1300 | 1300 | return wrapper |
|
1301 | 1301 | |
|
1302 | 1302 | |
|
1303 | 1303 | def pre_readline(self): |
|
1304 | 1304 | """readline hook to be used at the start of each line. |
|
1305 | 1305 | |
|
1306 | 1306 | Currently it handles auto-indent only.""" |
|
1307 | 1307 | |
|
1308 | 1308 | #debugx('self.indent_current_nsp','pre_readline:') |
|
1309 | 1309 | |
|
1310 | 1310 | if self.rl_do_indent: |
|
1311 | 1311 | self.readline.insert_text(self.indent_current_str()) |
|
1312 | 1312 | if self.rl_next_input is not None: |
|
1313 | 1313 | self.readline.insert_text(self.rl_next_input) |
|
1314 | 1314 | self.rl_next_input = None |
|
1315 | 1315 | |
|
1316 | 1316 | def init_readline(self): |
|
1317 | 1317 | """Command history completion/saving/reloading.""" |
|
1318 | 1318 | |
|
1319 | 1319 | |
|
1320 | 1320 | import IPython.rlineimpl as readline |
|
1321 | 1321 | |
|
1322 | 1322 | if not readline.have_readline: |
|
1323 | 1323 | self.has_readline = 0 |
|
1324 | 1324 | self.readline = None |
|
1325 | 1325 | # no point in bugging windows users with this every time: |
|
1326 | 1326 | warn('Readline services not available on this platform.') |
|
1327 | 1327 | else: |
|
1328 | 1328 | sys.modules['readline'] = readline |
|
1329 | 1329 | import atexit |
|
1330 | 1330 | from IPython.completer import IPCompleter |
|
1331 | 1331 | self.Completer = IPCompleter(self, |
|
1332 | 1332 | self.user_ns, |
|
1333 | 1333 | self.user_global_ns, |
|
1334 | 1334 | self.rc.readline_omit__names, |
|
1335 | 1335 | self.alias_table) |
|
1336 | 1336 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1337 | 1337 | self.strdispatchers['complete_command'] = sdisp |
|
1338 | 1338 | self.Completer.custom_completers = sdisp |
|
1339 | 1339 | # Platform-specific configuration |
|
1340 | 1340 | if os.name == 'nt': |
|
1341 | 1341 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1342 | 1342 | else: |
|
1343 | 1343 | self.readline_startup_hook = readline.set_startup_hook |
|
1344 | 1344 | |
|
1345 | 1345 | # Load user's initrc file (readline config) |
|
1346 | 1346 | # Or if libedit is used, load editrc. |
|
1347 | 1347 | inputrc_name = os.environ.get('INPUTRC') |
|
1348 | 1348 | if inputrc_name is None: |
|
1349 | 1349 | home_dir = get_home_dir() |
|
1350 | 1350 | if home_dir is not None: |
|
1351 | 1351 | inputrc_name = '.inputrc' |
|
1352 | 1352 | if readline.uses_libedit: |
|
1353 | 1353 | inputrc_name = '.editrc' |
|
1354 | 1354 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1355 | 1355 | if os.path.isfile(inputrc_name): |
|
1356 | 1356 | try: |
|
1357 | 1357 | readline.read_init_file(inputrc_name) |
|
1358 | 1358 | except: |
|
1359 | 1359 | warn('Problems reading readline initialization file <%s>' |
|
1360 | 1360 | % inputrc_name) |
|
1361 | 1361 | |
|
1362 | 1362 | self.has_readline = 1 |
|
1363 | 1363 | self.readline = readline |
|
1364 | 1364 | # save this in sys so embedded copies can restore it properly |
|
1365 | 1365 | sys.ipcompleter = self.Completer.complete |
|
1366 | 1366 | self.set_completer() |
|
1367 | 1367 | |
|
1368 | 1368 | # Configure readline according to user's prefs |
|
1369 | 1369 | # This is only done if GNU readline is being used. If libedit |
|
1370 | 1370 | # is being used (as on Leopard) the readline config is |
|
1371 | 1371 | # not run as the syntax for libedit is different. |
|
1372 | 1372 | if not readline.uses_libedit: |
|
1373 | 1373 | for rlcommand in self.rc.readline_parse_and_bind: |
|
1374 | 1374 | readline.parse_and_bind(rlcommand) |
|
1375 | 1375 | |
|
1376 | 1376 | # remove some chars from the delimiters list |
|
1377 | 1377 | delims = readline.get_completer_delims() |
|
1378 | 1378 | delims = delims.translate(string._idmap, |
|
1379 | 1379 | self.rc.readline_remove_delims) |
|
1380 | 1380 | readline.set_completer_delims(delims) |
|
1381 | 1381 | # otherwise we end up with a monster history after a while: |
|
1382 | 1382 | readline.set_history_length(1000) |
|
1383 | 1383 | try: |
|
1384 | 1384 | #print '*** Reading readline history' # dbg |
|
1385 | 1385 | readline.read_history_file(self.histfile) |
|
1386 | 1386 | except IOError: |
|
1387 | 1387 | pass # It doesn't exist yet. |
|
1388 | 1388 | |
|
1389 | 1389 | atexit.register(self.atexit_operations) |
|
1390 | 1390 | del atexit |
|
1391 | 1391 | |
|
1392 | 1392 | # Configure auto-indent for all platforms |
|
1393 | 1393 | self.set_autoindent(self.rc.autoindent) |
|
1394 | 1394 | |
|
1395 | 1395 | def ask_yes_no(self,prompt,default=True): |
|
1396 | 1396 | if self.rc.quiet: |
|
1397 | 1397 | return True |
|
1398 | 1398 | return ask_yes_no(prompt,default) |
|
1399 | 1399 | |
|
1400 | 1400 | def _should_recompile(self,e): |
|
1401 | 1401 | """Utility routine for edit_syntax_error""" |
|
1402 | 1402 | |
|
1403 | 1403 | if e.filename in ('<ipython console>','<input>','<string>', |
|
1404 | 1404 | '<console>','<BackgroundJob compilation>', |
|
1405 | 1405 | None): |
|
1406 | 1406 | |
|
1407 | 1407 | return False |
|
1408 | 1408 | try: |
|
1409 | 1409 | if (self.rc.autoedit_syntax and |
|
1410 | 1410 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
1411 | 1411 | '[Y/n] ','y')): |
|
1412 | 1412 | return False |
|
1413 | 1413 | except EOFError: |
|
1414 | 1414 | return False |
|
1415 | 1415 | |
|
1416 | 1416 | def int0(x): |
|
1417 | 1417 | try: |
|
1418 | 1418 | return int(x) |
|
1419 | 1419 | except TypeError: |
|
1420 | 1420 | return 0 |
|
1421 | 1421 | # always pass integer line and offset values to editor hook |
|
1422 | 1422 | self.hooks.fix_error_editor(e.filename, |
|
1423 | 1423 | int0(e.lineno),int0(e.offset),e.msg) |
|
1424 | 1424 | return True |
|
1425 | 1425 | |
|
1426 | 1426 | def edit_syntax_error(self): |
|
1427 | 1427 | """The bottom half of the syntax error handler called in the main loop. |
|
1428 | 1428 | |
|
1429 | 1429 | Loop until syntax error is fixed or user cancels. |
|
1430 | 1430 | """ |
|
1431 | 1431 | |
|
1432 | 1432 | while self.SyntaxTB.last_syntax_error: |
|
1433 | 1433 | # copy and clear last_syntax_error |
|
1434 | 1434 | err = self.SyntaxTB.clear_err_state() |
|
1435 | 1435 | if not self._should_recompile(err): |
|
1436 | 1436 | return |
|
1437 | 1437 | try: |
|
1438 | 1438 | # may set last_syntax_error again if a SyntaxError is raised |
|
1439 | 1439 | self.safe_execfile(err.filename,self.user_ns) |
|
1440 | 1440 | except: |
|
1441 | 1441 | self.showtraceback() |
|
1442 | 1442 | else: |
|
1443 | 1443 | try: |
|
1444 | 1444 | f = file(err.filename) |
|
1445 | 1445 | try: |
|
1446 | 1446 | sys.displayhook(f.read()) |
|
1447 | 1447 | finally: |
|
1448 | 1448 | f.close() |
|
1449 | 1449 | except: |
|
1450 | 1450 | self.showtraceback() |
|
1451 | 1451 | |
|
1452 | 1452 | def showsyntaxerror(self, filename=None): |
|
1453 | 1453 | """Display the syntax error that just occurred. |
|
1454 | 1454 | |
|
1455 | 1455 | This doesn't display a stack trace because there isn't one. |
|
1456 | 1456 | |
|
1457 | 1457 | If a filename is given, it is stuffed in the exception instead |
|
1458 | 1458 | of what was there before (because Python's parser always uses |
|
1459 | 1459 | "<string>" when reading from a string). |
|
1460 | 1460 | """ |
|
1461 | 1461 | etype, value, last_traceback = sys.exc_info() |
|
1462 | 1462 | |
|
1463 | 1463 | # See note about these variables in showtraceback() below |
|
1464 | 1464 | sys.last_type = etype |
|
1465 | 1465 | sys.last_value = value |
|
1466 | 1466 | sys.last_traceback = last_traceback |
|
1467 | 1467 | |
|
1468 | 1468 | if filename and etype is SyntaxError: |
|
1469 | 1469 | # Work hard to stuff the correct filename in the exception |
|
1470 | 1470 | try: |
|
1471 | 1471 | msg, (dummy_filename, lineno, offset, line) = value |
|
1472 | 1472 | except: |
|
1473 | 1473 | # Not the format we expect; leave it alone |
|
1474 | 1474 | pass |
|
1475 | 1475 | else: |
|
1476 | 1476 | # Stuff in the right filename |
|
1477 | 1477 | try: |
|
1478 | 1478 | # Assume SyntaxError is a class exception |
|
1479 | 1479 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1480 | 1480 | except: |
|
1481 | 1481 | # If that failed, assume SyntaxError is a string |
|
1482 | 1482 | value = msg, (filename, lineno, offset, line) |
|
1483 | 1483 | self.SyntaxTB(etype,value,[]) |
|
1484 | 1484 | |
|
1485 | 1485 | def debugger(self,force=False): |
|
1486 | 1486 | """Call the pydb/pdb debugger. |
|
1487 | 1487 | |
|
1488 | 1488 | Keywords: |
|
1489 | 1489 | |
|
1490 | 1490 | - force(False): by default, this routine checks the instance call_pdb |
|
1491 | 1491 | flag and does not actually invoke the debugger if the flag is false. |
|
1492 | 1492 | The 'force' option forces the debugger to activate even if the flag |
|
1493 | 1493 | is false. |
|
1494 | 1494 | """ |
|
1495 | 1495 | |
|
1496 | 1496 | if not (force or self.call_pdb): |
|
1497 | 1497 | return |
|
1498 | 1498 | |
|
1499 | 1499 | if not hasattr(sys,'last_traceback'): |
|
1500 | 1500 | error('No traceback has been produced, nothing to debug.') |
|
1501 | 1501 | return |
|
1502 | 1502 | |
|
1503 | 1503 | # use pydb if available |
|
1504 | 1504 | if Debugger.has_pydb: |
|
1505 | 1505 | from pydb import pm |
|
1506 | 1506 | else: |
|
1507 | 1507 | # fallback to our internal debugger |
|
1508 | 1508 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
1509 | 1509 | self.history_saving_wrapper(pm)() |
|
1510 | 1510 | |
|
1511 | 1511 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): |
|
1512 | 1512 | """Display the exception that just occurred. |
|
1513 | 1513 | |
|
1514 | 1514 | If nothing is known about the exception, this is the method which |
|
1515 | 1515 | should be used throughout the code for presenting user tracebacks, |
|
1516 | 1516 | rather than directly invoking the InteractiveTB object. |
|
1517 | 1517 | |
|
1518 | 1518 | A specific showsyntaxerror() also exists, but this method can take |
|
1519 | 1519 | care of calling it if needed, so unless you are explicitly catching a |
|
1520 | 1520 | SyntaxError exception, don't try to analyze the stack manually and |
|
1521 | 1521 | simply call this method.""" |
|
1522 | 1522 | |
|
1523 | 1523 | |
|
1524 | 1524 | # Though this won't be called by syntax errors in the input line, |
|
1525 | 1525 | # there may be SyntaxError cases whith imported code. |
|
1526 | 1526 | |
|
1527 | 1527 | try: |
|
1528 | 1528 | if exc_tuple is None: |
|
1529 | 1529 | etype, value, tb = sys.exc_info() |
|
1530 | 1530 | else: |
|
1531 | 1531 | etype, value, tb = exc_tuple |
|
1532 | 1532 | |
|
1533 | 1533 | if etype is SyntaxError: |
|
1534 | 1534 | self.showsyntaxerror(filename) |
|
1535 | 1535 | elif etype is IPython.ipapi.UsageError: |
|
1536 | 1536 | print "UsageError:", value |
|
1537 | 1537 | else: |
|
1538 | 1538 | # WARNING: these variables are somewhat deprecated and not |
|
1539 | 1539 | # necessarily safe to use in a threaded environment, but tools |
|
1540 | 1540 | # like pdb depend on their existence, so let's set them. If we |
|
1541 | 1541 | # find problems in the field, we'll need to revisit their use. |
|
1542 | 1542 | sys.last_type = etype |
|
1543 | 1543 | sys.last_value = value |
|
1544 | 1544 | sys.last_traceback = tb |
|
1545 | 1545 | |
|
1546 | 1546 | if etype in self.custom_exceptions: |
|
1547 | 1547 | self.CustomTB(etype,value,tb) |
|
1548 | 1548 | else: |
|
1549 | 1549 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) |
|
1550 | 1550 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1551 | 1551 | # pdb mucks up readline, fix it back |
|
1552 | 1552 | self.set_completer() |
|
1553 | 1553 | except KeyboardInterrupt: |
|
1554 | 1554 | self.write("\nKeyboardInterrupt\n") |
|
1555 | 1555 | |
|
1556 | 1556 | |
|
1557 | 1557 | |
|
1558 | 1558 | def mainloop(self,banner=None): |
|
1559 | 1559 | """Creates the local namespace and starts the mainloop. |
|
1560 | 1560 | |
|
1561 | 1561 | If an optional banner argument is given, it will override the |
|
1562 | 1562 | internally created default banner.""" |
|
1563 | 1563 | |
|
1564 | 1564 | if self.rc.c: # Emulate Python's -c option |
|
1565 | 1565 | self.exec_init_cmd() |
|
1566 | 1566 | if banner is None: |
|
1567 | 1567 | if not self.rc.banner: |
|
1568 | 1568 | banner = '' |
|
1569 | 1569 | # banner is string? Use it directly! |
|
1570 | 1570 | elif isinstance(self.rc.banner,basestring): |
|
1571 | 1571 | banner = self.rc.banner |
|
1572 | 1572 | else: |
|
1573 | 1573 | banner = self.BANNER+self.banner2 |
|
1574 | 1574 | |
|
1575 | 1575 | while 1: |
|
1576 | 1576 | try: |
|
1577 | 1577 | self.interact(banner) |
|
1578 | 1578 | #self.interact_with_readline() |
|
1579 | 1579 | # XXX for testing of a readline-decoupled repl loop, call interact_with_readline above |
|
1580 | 1580 | |
|
1581 | 1581 | break |
|
1582 | 1582 | except KeyboardInterrupt: |
|
1583 | 1583 | # this should not be necessary, but KeyboardInterrupt |
|
1584 | 1584 | # handling seems rather unpredictable... |
|
1585 | 1585 | self.write("\nKeyboardInterrupt in interact()\n") |
|
1586 | 1586 | |
|
1587 | 1587 | def exec_init_cmd(self): |
|
1588 | 1588 | """Execute a command given at the command line. |
|
1589 | 1589 | |
|
1590 | 1590 | This emulates Python's -c option.""" |
|
1591 | 1591 | |
|
1592 | 1592 | #sys.argv = ['-c'] |
|
1593 | 1593 | self.push(self.prefilter(self.rc.c, False)) |
|
1594 | 1594 | if not self.rc.interact: |
|
1595 |
self. |
|
|
1595 | self.ask_exit() | |
|
1596 | 1596 | |
|
1597 | 1597 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): |
|
1598 | 1598 | """Embeds IPython into a running python program. |
|
1599 | 1599 | |
|
1600 | 1600 | Input: |
|
1601 | 1601 | |
|
1602 | 1602 | - header: An optional header message can be specified. |
|
1603 | 1603 | |
|
1604 | 1604 | - local_ns, global_ns: working namespaces. If given as None, the |
|
1605 | 1605 | IPython-initialized one is updated with __main__.__dict__, so that |
|
1606 | 1606 | program variables become visible but user-specific configuration |
|
1607 | 1607 | remains possible. |
|
1608 | 1608 | |
|
1609 | 1609 | - stack_depth: specifies how many levels in the stack to go to |
|
1610 | 1610 | looking for namespaces (when local_ns and global_ns are None). This |
|
1611 | 1611 | allows an intermediate caller to make sure that this function gets |
|
1612 | 1612 | the namespace from the intended level in the stack. By default (0) |
|
1613 | 1613 | it will get its locals and globals from the immediate caller. |
|
1614 | 1614 | |
|
1615 | 1615 | Warning: it's possible to use this in a program which is being run by |
|
1616 | 1616 | IPython itself (via %run), but some funny things will happen (a few |
|
1617 | 1617 | globals get overwritten). In the future this will be cleaned up, as |
|
1618 | 1618 | there is no fundamental reason why it can't work perfectly.""" |
|
1619 | 1619 | |
|
1620 | 1620 | # Get locals and globals from caller |
|
1621 | 1621 | if local_ns is None or global_ns is None: |
|
1622 | 1622 | call_frame = sys._getframe(stack_depth).f_back |
|
1623 | 1623 | |
|
1624 | 1624 | if local_ns is None: |
|
1625 | 1625 | local_ns = call_frame.f_locals |
|
1626 | 1626 | if global_ns is None: |
|
1627 | 1627 | global_ns = call_frame.f_globals |
|
1628 | 1628 | |
|
1629 | 1629 | # Update namespaces and fire up interpreter |
|
1630 | 1630 | |
|
1631 | 1631 | # The global one is easy, we can just throw it in |
|
1632 | 1632 | self.user_global_ns = global_ns |
|
1633 | 1633 | |
|
1634 | 1634 | # but the user/local one is tricky: ipython needs it to store internal |
|
1635 | 1635 | # data, but we also need the locals. We'll copy locals in the user |
|
1636 | 1636 | # one, but will track what got copied so we can delete them at exit. |
|
1637 | 1637 | # This is so that a later embedded call doesn't see locals from a |
|
1638 | 1638 | # previous call (which most likely existed in a separate scope). |
|
1639 | 1639 | local_varnames = local_ns.keys() |
|
1640 | 1640 | self.user_ns.update(local_ns) |
|
1641 | 1641 | #self.user_ns['local_ns'] = local_ns # dbg |
|
1642 | 1642 | |
|
1643 | 1643 | # Patch for global embedding to make sure that things don't overwrite |
|
1644 | 1644 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> |
|
1645 | 1645 | # FIXME. Test this a bit more carefully (the if.. is new) |
|
1646 | 1646 | if local_ns is None and global_ns is None: |
|
1647 | 1647 | self.user_global_ns.update(__main__.__dict__) |
|
1648 | 1648 | |
|
1649 | 1649 | # make sure the tab-completer has the correct frame information, so it |
|
1650 | 1650 | # actually completes using the frame's locals/globals |
|
1651 | 1651 | self.set_completer_frame() |
|
1652 | 1652 | |
|
1653 | 1653 | # before activating the interactive mode, we need to make sure that |
|
1654 | 1654 | # all names in the builtin namespace needed by ipython point to |
|
1655 | 1655 | # ourselves, and not to other instances. |
|
1656 | 1656 | self.add_builtins() |
|
1657 | 1657 | |
|
1658 | 1658 | self.interact(header) |
|
1659 | 1659 | |
|
1660 | 1660 | # now, purge out the user namespace from anything we might have added |
|
1661 | 1661 | # from the caller's local namespace |
|
1662 | 1662 | delvar = self.user_ns.pop |
|
1663 | 1663 | for var in local_varnames: |
|
1664 | 1664 | delvar(var,None) |
|
1665 | 1665 | # and clean builtins we may have overridden |
|
1666 | 1666 | self.clean_builtins() |
|
1667 | 1667 | |
|
1668 | 1668 | def interact_prompt(self): |
|
1669 | 1669 | """ Print the prompt (in read-eval-print loop) |
|
1670 | 1670 | |
|
1671 | 1671 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1672 | 1672 | used in standard IPython flow. |
|
1673 | 1673 | """ |
|
1674 | 1674 | if self.more: |
|
1675 | 1675 | try: |
|
1676 | 1676 | prompt = self.hooks.generate_prompt(True) |
|
1677 | 1677 | except: |
|
1678 | 1678 | self.showtraceback() |
|
1679 | 1679 | if self.autoindent: |
|
1680 | 1680 | self.rl_do_indent = True |
|
1681 | 1681 | |
|
1682 | 1682 | else: |
|
1683 | 1683 | try: |
|
1684 | 1684 | prompt = self.hooks.generate_prompt(False) |
|
1685 | 1685 | except: |
|
1686 | 1686 | self.showtraceback() |
|
1687 | 1687 | self.write(prompt) |
|
1688 | 1688 | |
|
1689 | 1689 | def interact_handle_input(self,line): |
|
1690 | 1690 | """ Handle the input line (in read-eval-print loop) |
|
1691 | 1691 | |
|
1692 | 1692 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1693 | 1693 | used in standard IPython flow. |
|
1694 | 1694 | """ |
|
1695 | 1695 | if line.lstrip() == line: |
|
1696 | 1696 | self.shadowhist.add(line.strip()) |
|
1697 | 1697 | lineout = self.prefilter(line,self.more) |
|
1698 | 1698 | |
|
1699 | 1699 | if line.strip(): |
|
1700 | 1700 | if self.more: |
|
1701 | 1701 | self.input_hist_raw[-1] += '%s\n' % line |
|
1702 | 1702 | else: |
|
1703 | 1703 | self.input_hist_raw.append('%s\n' % line) |
|
1704 | 1704 | |
|
1705 | 1705 | |
|
1706 | 1706 | self.more = self.push(lineout) |
|
1707 | 1707 | if (self.SyntaxTB.last_syntax_error and |
|
1708 | 1708 | self.rc.autoedit_syntax): |
|
1709 | 1709 | self.edit_syntax_error() |
|
1710 | 1710 | |
|
1711 | 1711 | def interact_with_readline(self): |
|
1712 | 1712 | """ Demo of using interact_handle_input, interact_prompt |
|
1713 | 1713 | |
|
1714 | 1714 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), |
|
1715 | 1715 | it should work like this. |
|
1716 | 1716 | """ |
|
1717 | 1717 | self.readline_startup_hook(self.pre_readline) |
|
1718 | 1718 | while not self.exit_now: |
|
1719 | 1719 | self.interact_prompt() |
|
1720 | 1720 | if self.more: |
|
1721 | 1721 | self.rl_do_indent = True |
|
1722 | 1722 | else: |
|
1723 | 1723 | self.rl_do_indent = False |
|
1724 | 1724 | line = raw_input_original().decode(self.stdin_encoding) |
|
1725 | 1725 | self.interact_handle_input(line) |
|
1726 | 1726 | |
|
1727 | 1727 | |
|
1728 | 1728 | def interact(self, banner=None): |
|
1729 | 1729 | """Closely emulate the interactive Python console. |
|
1730 | 1730 | |
|
1731 | 1731 | The optional banner argument specify the banner to print |
|
1732 | 1732 | before the first interaction; by default it prints a banner |
|
1733 | 1733 | similar to the one printed by the real Python interpreter, |
|
1734 | 1734 | followed by the current class name in parentheses (so as not |
|
1735 | 1735 | to confuse this with the real interpreter -- since it's so |
|
1736 | 1736 | close!). |
|
1737 | 1737 | |
|
1738 | 1738 | """ |
|
1739 | 1739 | |
|
1740 | 1740 | if self.exit_now: |
|
1741 | 1741 | # batch run -> do not interact |
|
1742 | 1742 | return |
|
1743 | 1743 | cprt = 'Type "copyright", "credits" or "license" for more information.' |
|
1744 | 1744 | if banner is None: |
|
1745 | 1745 | self.write("Python %s on %s\n%s\n(%s)\n" % |
|
1746 | 1746 | (sys.version, sys.platform, cprt, |
|
1747 | 1747 | self.__class__.__name__)) |
|
1748 | 1748 | else: |
|
1749 | 1749 | self.write(banner) |
|
1750 | 1750 | |
|
1751 | 1751 | more = 0 |
|
1752 | 1752 | |
|
1753 | 1753 | # Mark activity in the builtins |
|
1754 | 1754 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1755 | 1755 | |
|
1756 | 1756 | if self.has_readline: |
|
1757 | 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 | 1761 | while not self.exit_now: |
|
1761 | 1762 | self.hooks.pre_prompt_hook() |
|
1762 | 1763 | if more: |
|
1763 | 1764 | try: |
|
1764 | 1765 | prompt = self.hooks.generate_prompt(True) |
|
1765 | 1766 | except: |
|
1766 | 1767 | self.showtraceback() |
|
1767 | 1768 | if self.autoindent: |
|
1768 | 1769 | self.rl_do_indent = True |
|
1769 | 1770 | |
|
1770 | 1771 | else: |
|
1771 | 1772 | try: |
|
1772 | 1773 | prompt = self.hooks.generate_prompt(False) |
|
1773 | 1774 | except: |
|
1774 | 1775 | self.showtraceback() |
|
1775 | 1776 | try: |
|
1776 | 1777 | line = self.raw_input(prompt,more) |
|
1777 | 1778 | if self.exit_now: |
|
1778 | 1779 | # quick exit on sys.std[in|out] close |
|
1779 | 1780 | break |
|
1780 | 1781 | if self.autoindent: |
|
1781 | 1782 | self.rl_do_indent = False |
|
1782 | 1783 | |
|
1783 | 1784 | except KeyboardInterrupt: |
|
1784 | 1785 | #double-guard against keyboardinterrupts during kbdint handling |
|
1785 | 1786 | try: |
|
1786 | 1787 | self.write('\nKeyboardInterrupt\n') |
|
1787 | 1788 | self.resetbuffer() |
|
1788 | 1789 | # keep cache in sync with the prompt counter: |
|
1789 | 1790 | self.outputcache.prompt_count -= 1 |
|
1790 | 1791 | |
|
1791 | 1792 | if self.autoindent: |
|
1792 | 1793 | self.indent_current_nsp = 0 |
|
1793 | 1794 | more = 0 |
|
1794 | 1795 | except KeyboardInterrupt: |
|
1795 | 1796 | pass |
|
1796 | 1797 | except EOFError: |
|
1797 | 1798 | if self.autoindent: |
|
1798 | 1799 | self.rl_do_indent = False |
|
1799 | 1800 | self.readline_startup_hook(None) |
|
1800 | 1801 | self.write('\n') |
|
1801 | 1802 | self.exit() |
|
1802 | 1803 | except bdb.BdbQuit: |
|
1803 | 1804 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
1804 | 1805 | 'Because of how pdb handles the stack, it is impossible\n' |
|
1805 | 1806 | 'for IPython to properly format this particular exception.\n' |
|
1806 | 1807 | 'IPython will resume normal operation.') |
|
1807 | 1808 | except: |
|
1808 | 1809 | # exceptions here are VERY RARE, but they can be triggered |
|
1809 | 1810 | # asynchronously by signal handlers, for example. |
|
1810 | 1811 | self.showtraceback() |
|
1811 | 1812 | else: |
|
1812 | 1813 | more = self.push(line) |
|
1813 | 1814 | if (self.SyntaxTB.last_syntax_error and |
|
1814 | 1815 | self.rc.autoedit_syntax): |
|
1815 | 1816 | self.edit_syntax_error() |
|
1816 | 1817 | |
|
1817 | 1818 | # We are off again... |
|
1818 | 1819 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
1819 | 1820 | |
|
1820 | 1821 | def excepthook(self, etype, value, tb): |
|
1821 | 1822 | """One more defense for GUI apps that call sys.excepthook. |
|
1822 | 1823 | |
|
1823 | 1824 | GUI frameworks like wxPython trap exceptions and call |
|
1824 | 1825 | sys.excepthook themselves. I guess this is a feature that |
|
1825 | 1826 | enables them to keep running after exceptions that would |
|
1826 | 1827 | otherwise kill their mainloop. This is a bother for IPython |
|
1827 | 1828 | which excepts to catch all of the program exceptions with a try: |
|
1828 | 1829 | except: statement. |
|
1829 | 1830 | |
|
1830 | 1831 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1831 | 1832 | any app directly invokes sys.excepthook, it will look to the user like |
|
1832 | 1833 | IPython crashed. In order to work around this, we can disable the |
|
1833 | 1834 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1834 | 1835 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1835 | 1836 | call sys.excepthook will generate a regular-looking exception from |
|
1836 | 1837 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1837 | 1838 | crashes. |
|
1838 | 1839 | |
|
1839 | 1840 | This hook should be used sparingly, only in places which are not likely |
|
1840 | 1841 | to be true IPython errors. |
|
1841 | 1842 | """ |
|
1842 | 1843 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1843 | 1844 | |
|
1844 | 1845 | def expand_aliases(self,fn,rest): |
|
1845 | 1846 | """ Expand multiple levels of aliases: |
|
1846 | 1847 | |
|
1847 | 1848 | if: |
|
1848 | 1849 | |
|
1849 | 1850 | alias foo bar /tmp |
|
1850 | 1851 | alias baz foo |
|
1851 | 1852 | |
|
1852 | 1853 | then: |
|
1853 | 1854 | |
|
1854 | 1855 | baz huhhahhei -> bar /tmp huhhahhei |
|
1855 | 1856 | |
|
1856 | 1857 | """ |
|
1857 | 1858 | line = fn + " " + rest |
|
1858 | 1859 | |
|
1859 | 1860 | done = Set() |
|
1860 | 1861 | while 1: |
|
1861 | 1862 | pre,fn,rest = prefilter.splitUserInput(line, |
|
1862 | 1863 | prefilter.shell_line_split) |
|
1863 | 1864 | if fn in self.alias_table: |
|
1864 | 1865 | if fn in done: |
|
1865 | 1866 | warn("Cyclic alias definition, repeated '%s'" % fn) |
|
1866 | 1867 | return "" |
|
1867 | 1868 | done.add(fn) |
|
1868 | 1869 | |
|
1869 | 1870 | l2 = self.transform_alias(fn,rest) |
|
1870 | 1871 | # dir -> dir |
|
1871 | 1872 | # print "alias",line, "->",l2 #dbg |
|
1872 | 1873 | if l2 == line: |
|
1873 | 1874 | break |
|
1874 | 1875 | # ls -> ls -F should not recurse forever |
|
1875 | 1876 | if l2.split(None,1)[0] == line.split(None,1)[0]: |
|
1876 | 1877 | line = l2 |
|
1877 | 1878 | break |
|
1878 | 1879 | |
|
1879 | 1880 | line=l2 |
|
1880 | 1881 | |
|
1881 | 1882 | |
|
1882 | 1883 | # print "al expand to",line #dbg |
|
1883 | 1884 | else: |
|
1884 | 1885 | break |
|
1885 | 1886 | |
|
1886 | 1887 | return line |
|
1887 | 1888 | |
|
1888 | 1889 | def transform_alias(self, alias,rest=''): |
|
1889 | 1890 | """ Transform alias to system command string. |
|
1890 | 1891 | """ |
|
1891 | 1892 | trg = self.alias_table[alias] |
|
1892 | 1893 | |
|
1893 | 1894 | nargs,cmd = trg |
|
1894 | 1895 | # print trg #dbg |
|
1895 | 1896 | if ' ' in cmd and os.path.isfile(cmd): |
|
1896 | 1897 | cmd = '"%s"' % cmd |
|
1897 | 1898 | |
|
1898 | 1899 | # Expand the %l special to be the user's input line |
|
1899 | 1900 | if cmd.find('%l') >= 0: |
|
1900 | 1901 | cmd = cmd.replace('%l',rest) |
|
1901 | 1902 | rest = '' |
|
1902 | 1903 | if nargs==0: |
|
1903 | 1904 | # Simple, argument-less aliases |
|
1904 | 1905 | cmd = '%s %s' % (cmd,rest) |
|
1905 | 1906 | else: |
|
1906 | 1907 | # Handle aliases with positional arguments |
|
1907 | 1908 | args = rest.split(None,nargs) |
|
1908 | 1909 | if len(args)< nargs: |
|
1909 | 1910 | error('Alias <%s> requires %s arguments, %s given.' % |
|
1910 | 1911 | (alias,nargs,len(args))) |
|
1911 | 1912 | return None |
|
1912 | 1913 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) |
|
1913 | 1914 | # Now call the macro, evaluating in the user's namespace |
|
1914 | 1915 | #print 'new command: <%r>' % cmd # dbg |
|
1915 | 1916 | return cmd |
|
1916 | 1917 | |
|
1917 | 1918 | def call_alias(self,alias,rest=''): |
|
1918 | 1919 | """Call an alias given its name and the rest of the line. |
|
1919 | 1920 | |
|
1920 | 1921 | This is only used to provide backwards compatibility for users of |
|
1921 | 1922 | ipalias(), use of which is not recommended for anymore.""" |
|
1922 | 1923 | |
|
1923 | 1924 | # Now call the macro, evaluating in the user's namespace |
|
1924 | 1925 | cmd = self.transform_alias(alias, rest) |
|
1925 | 1926 | try: |
|
1926 | 1927 | self.system(cmd) |
|
1927 | 1928 | except: |
|
1928 | 1929 | self.showtraceback() |
|
1929 | 1930 | |
|
1930 | 1931 | def indent_current_str(self): |
|
1931 | 1932 | """return the current level of indentation as a string""" |
|
1932 | 1933 | return self.indent_current_nsp * ' ' |
|
1933 | 1934 | |
|
1934 | 1935 | def autoindent_update(self,line): |
|
1935 | 1936 | """Keep track of the indent level.""" |
|
1936 | 1937 | |
|
1937 | 1938 | #debugx('line') |
|
1938 | 1939 | #debugx('self.indent_current_nsp') |
|
1939 | 1940 | if self.autoindent: |
|
1940 | 1941 | if line: |
|
1941 | 1942 | inisp = num_ini_spaces(line) |
|
1942 | 1943 | if inisp < self.indent_current_nsp: |
|
1943 | 1944 | self.indent_current_nsp = inisp |
|
1944 | 1945 | |
|
1945 | 1946 | if line[-1] == ':': |
|
1946 | 1947 | self.indent_current_nsp += 4 |
|
1947 | 1948 | elif dedent_re.match(line): |
|
1948 | 1949 | self.indent_current_nsp -= 4 |
|
1949 | 1950 | else: |
|
1950 | 1951 | self.indent_current_nsp = 0 |
|
1951 | 1952 | |
|
1952 | 1953 | def runlines(self,lines): |
|
1953 | 1954 | """Run a string of one or more lines of source. |
|
1954 | 1955 | |
|
1955 | 1956 | This method is capable of running a string containing multiple source |
|
1956 | 1957 | lines, as if they had been entered at the IPython prompt. Since it |
|
1957 | 1958 | exposes IPython's processing machinery, the given strings can contain |
|
1958 | 1959 | magic calls (%magic), special shell access (!cmd), etc.""" |
|
1959 | 1960 | |
|
1960 | 1961 | # We must start with a clean buffer, in case this is run from an |
|
1961 | 1962 | # interactive IPython session (via a magic, for example). |
|
1962 | 1963 | self.resetbuffer() |
|
1963 | 1964 | lines = lines.split('\n') |
|
1964 | 1965 | more = 0 |
|
1965 | 1966 | |
|
1966 | 1967 | for line in lines: |
|
1967 | 1968 | # skip blank lines so we don't mess up the prompt counter, but do |
|
1968 | 1969 | # NOT skip even a blank line if we are in a code block (more is |
|
1969 | 1970 | # true) |
|
1970 | 1971 | |
|
1971 | 1972 | |
|
1972 | 1973 | if line or more: |
|
1973 | 1974 | # push to raw history, so hist line numbers stay in sync |
|
1974 | 1975 | self.input_hist_raw.append("# " + line + "\n") |
|
1975 | 1976 | more = self.push(self.prefilter(line,more)) |
|
1976 | 1977 | # IPython's runsource returns None if there was an error |
|
1977 | 1978 | # compiling the code. This allows us to stop processing right |
|
1978 | 1979 | # away, so the user gets the error message at the right place. |
|
1979 | 1980 | if more is None: |
|
1980 | 1981 | break |
|
1981 | 1982 | else: |
|
1982 | 1983 | self.input_hist_raw.append("\n") |
|
1983 | 1984 | # final newline in case the input didn't have it, so that the code |
|
1984 | 1985 | # actually does get executed |
|
1985 | 1986 | if more: |
|
1986 | 1987 | self.push('\n') |
|
1987 | 1988 | |
|
1988 | 1989 | def runsource(self, source, filename='<input>', symbol='single'): |
|
1989 | 1990 | """Compile and run some source in the interpreter. |
|
1990 | 1991 | |
|
1991 | 1992 | Arguments are as for compile_command(). |
|
1992 | 1993 | |
|
1993 | 1994 | One several things can happen: |
|
1994 | 1995 | |
|
1995 | 1996 | 1) The input is incorrect; compile_command() raised an |
|
1996 | 1997 | exception (SyntaxError or OverflowError). A syntax traceback |
|
1997 | 1998 | will be printed by calling the showsyntaxerror() method. |
|
1998 | 1999 | |
|
1999 | 2000 | 2) The input is incomplete, and more input is required; |
|
2000 | 2001 | compile_command() returned None. Nothing happens. |
|
2001 | 2002 | |
|
2002 | 2003 | 3) The input is complete; compile_command() returned a code |
|
2003 | 2004 | object. The code is executed by calling self.runcode() (which |
|
2004 | 2005 | also handles run-time exceptions, except for SystemExit). |
|
2005 | 2006 | |
|
2006 | 2007 | The return value is: |
|
2007 | 2008 | |
|
2008 | 2009 | - True in case 2 |
|
2009 | 2010 | |
|
2010 | 2011 | - False in the other cases, unless an exception is raised, where |
|
2011 | 2012 | None is returned instead. This can be used by external callers to |
|
2012 | 2013 | know whether to continue feeding input or not. |
|
2013 | 2014 | |
|
2014 | 2015 | The return value can be used to decide whether to use sys.ps1 or |
|
2015 | 2016 | sys.ps2 to prompt the next line.""" |
|
2016 | 2017 | |
|
2017 | 2018 | # if the source code has leading blanks, add 'if 1:\n' to it |
|
2018 | 2019 | # this allows execution of indented pasted code. It is tempting |
|
2019 | 2020 | # to add '\n' at the end of source to run commands like ' a=1' |
|
2020 | 2021 | # directly, but this fails for more complicated scenarios |
|
2021 | 2022 | source=source.encode(self.stdin_encoding) |
|
2022 | 2023 | if source[:1] in [' ', '\t']: |
|
2023 | 2024 | source = 'if 1:\n%s' % source |
|
2024 | 2025 | |
|
2025 | 2026 | try: |
|
2026 | 2027 | code = self.compile(source,filename,symbol) |
|
2027 | 2028 | except (OverflowError, SyntaxError, ValueError, TypeError): |
|
2028 | 2029 | # Case 1 |
|
2029 | 2030 | self.showsyntaxerror(filename) |
|
2030 | 2031 | return None |
|
2031 | 2032 | |
|
2032 | 2033 | if code is None: |
|
2033 | 2034 | # Case 2 |
|
2034 | 2035 | return True |
|
2035 | 2036 | |
|
2036 | 2037 | # Case 3 |
|
2037 | 2038 | # We store the code object so that threaded shells and |
|
2038 | 2039 | # custom exception handlers can access all this info if needed. |
|
2039 | 2040 | # The source corresponding to this can be obtained from the |
|
2040 | 2041 | # buffer attribute as '\n'.join(self.buffer). |
|
2041 | 2042 | self.code_to_run = code |
|
2042 | 2043 | # now actually execute the code object |
|
2043 | 2044 | if self.runcode(code) == 0: |
|
2044 | 2045 | return False |
|
2045 | 2046 | else: |
|
2046 | 2047 | return None |
|
2047 | 2048 | |
|
2048 | 2049 | def runcode(self,code_obj): |
|
2049 | 2050 | """Execute a code object. |
|
2050 | 2051 | |
|
2051 | 2052 | When an exception occurs, self.showtraceback() is called to display a |
|
2052 | 2053 | traceback. |
|
2053 | 2054 | |
|
2054 | 2055 | Return value: a flag indicating whether the code to be run completed |
|
2055 | 2056 | successfully: |
|
2056 | 2057 | |
|
2057 | 2058 | - 0: successful execution. |
|
2058 | 2059 | - 1: an error occurred. |
|
2059 | 2060 | """ |
|
2060 | 2061 | |
|
2061 | 2062 | # Set our own excepthook in case the user code tries to call it |
|
2062 | 2063 | # directly, so that the IPython crash handler doesn't get triggered |
|
2063 | 2064 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2064 | 2065 | |
|
2065 | 2066 | # we save the original sys.excepthook in the instance, in case config |
|
2066 | 2067 | # code (such as magics) needs access to it. |
|
2067 | 2068 | self.sys_excepthook = old_excepthook |
|
2068 | 2069 | outflag = 1 # happens in more places, so it's easier as default |
|
2069 | 2070 | try: |
|
2070 | 2071 | try: |
|
2071 | 2072 | self.hooks.pre_runcode_hook() |
|
2072 | 2073 | exec code_obj in self.user_global_ns, self.user_ns |
|
2073 | 2074 | finally: |
|
2074 | 2075 | # Reset our crash handler in place |
|
2075 | 2076 | sys.excepthook = old_excepthook |
|
2076 | 2077 | except SystemExit: |
|
2077 | 2078 | self.resetbuffer() |
|
2078 | 2079 | self.showtraceback() |
|
2079 | 2080 | warn("Type %exit or %quit to exit IPython " |
|
2080 | 2081 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
2081 | 2082 | except self.custom_exceptions: |
|
2082 | 2083 | etype,value,tb = sys.exc_info() |
|
2083 | 2084 | self.CustomTB(etype,value,tb) |
|
2084 | 2085 | except: |
|
2085 | 2086 | self.showtraceback() |
|
2086 | 2087 | else: |
|
2087 | 2088 | outflag = 0 |
|
2088 | 2089 | if softspace(sys.stdout, 0): |
|
2089 | 2090 | |
|
2090 | 2091 | # Flush out code object which has been run (and source) |
|
2091 | 2092 | self.code_to_run = None |
|
2092 | 2093 | return outflag |
|
2093 | 2094 | |
|
2094 | 2095 | def push(self, line): |
|
2095 | 2096 | """Push a line to the interpreter. |
|
2096 | 2097 | |
|
2097 | 2098 | The line should not have a trailing newline; it may have |
|
2098 | 2099 | internal newlines. The line is appended to a buffer and the |
|
2099 | 2100 | interpreter's runsource() method is called with the |
|
2100 | 2101 | concatenated contents of the buffer as source. If this |
|
2101 | 2102 | indicates that the command was executed or invalid, the buffer |
|
2102 | 2103 | is reset; otherwise, the command is incomplete, and the buffer |
|
2103 | 2104 | is left as it was after the line was appended. The return |
|
2104 | 2105 | value is 1 if more input is required, 0 if the line was dealt |
|
2105 | 2106 | with in some way (this is the same as runsource()). |
|
2106 | 2107 | """ |
|
2107 | 2108 | |
|
2108 | 2109 | # autoindent management should be done here, and not in the |
|
2109 | 2110 | # interactive loop, since that one is only seen by keyboard input. We |
|
2110 | 2111 | # need this done correctly even for code run via runlines (which uses |
|
2111 | 2112 | # push). |
|
2112 | 2113 | |
|
2113 | 2114 | #print 'push line: <%s>' % line # dbg |
|
2114 | 2115 | for subline in line.splitlines(): |
|
2115 | 2116 | self.autoindent_update(subline) |
|
2116 | 2117 | self.buffer.append(line) |
|
2117 | 2118 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
2118 | 2119 | if not more: |
|
2119 | 2120 | self.resetbuffer() |
|
2120 | 2121 | return more |
|
2121 | 2122 | |
|
2122 | 2123 | def split_user_input(self, line): |
|
2123 | 2124 | # This is really a hold-over to support ipapi and some extensions |
|
2124 | 2125 | return prefilter.splitUserInput(line) |
|
2125 | 2126 | |
|
2126 | 2127 | def resetbuffer(self): |
|
2127 | 2128 | """Reset the input buffer.""" |
|
2128 | 2129 | self.buffer[:] = [] |
|
2129 | 2130 | |
|
2130 | 2131 | def raw_input(self,prompt='',continue_prompt=False): |
|
2131 | 2132 | """Write a prompt and read a line. |
|
2132 | 2133 | |
|
2133 | 2134 | The returned line does not include the trailing newline. |
|
2134 | 2135 | When the user enters the EOF key sequence, EOFError is raised. |
|
2135 | 2136 | |
|
2136 | 2137 | Optional inputs: |
|
2137 | 2138 | |
|
2138 | 2139 | - prompt(''): a string to be printed to prompt the user. |
|
2139 | 2140 | |
|
2140 | 2141 | - continue_prompt(False): whether this line is the first one or a |
|
2141 | 2142 | continuation in a sequence of inputs. |
|
2142 | 2143 | """ |
|
2143 | 2144 | |
|
2144 | 2145 | # Code run by the user may have modified the readline completer state. |
|
2145 | 2146 | # We must ensure that our completer is back in place. |
|
2146 | 2147 | if self.has_readline: |
|
2147 | 2148 | self.set_completer() |
|
2148 | 2149 | |
|
2149 | 2150 | try: |
|
2150 | 2151 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
2151 | 2152 | except ValueError: |
|
2152 | 2153 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
2153 | 2154 | " or sys.stdout.close()!\nExiting IPython!") |
|
2154 |
self. |
|
|
2155 | self.ask_exit() | |
|
2155 | 2156 | return "" |
|
2156 | 2157 | |
|
2157 | 2158 | # Try to be reasonably smart about not re-indenting pasted input more |
|
2158 | 2159 | # than necessary. We do this by trimming out the auto-indent initial |
|
2159 | 2160 | # spaces, if the user's actual input started itself with whitespace. |
|
2160 | 2161 | #debugx('self.buffer[-1]') |
|
2161 | 2162 | |
|
2162 | 2163 | if self.autoindent: |
|
2163 | 2164 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
2164 | 2165 | line = line[self.indent_current_nsp:] |
|
2165 | 2166 | self.indent_current_nsp = 0 |
|
2166 | 2167 | |
|
2167 | 2168 | # store the unfiltered input before the user has any chance to modify |
|
2168 | 2169 | # it. |
|
2169 | 2170 | if line.strip(): |
|
2170 | 2171 | if continue_prompt: |
|
2171 | 2172 | self.input_hist_raw[-1] += '%s\n' % line |
|
2172 | 2173 | if self.has_readline: # and some config option is set? |
|
2173 | 2174 | try: |
|
2174 | 2175 | histlen = self.readline.get_current_history_length() |
|
2175 | 2176 | if histlen > 1: |
|
2176 | 2177 | newhist = self.input_hist_raw[-1].rstrip() |
|
2177 | 2178 | self.readline.remove_history_item(histlen-1) |
|
2178 | 2179 | self.readline.replace_history_item(histlen-2, |
|
2179 | 2180 | newhist.encode(self.stdin_encoding)) |
|
2180 | 2181 | except AttributeError: |
|
2181 | 2182 | pass # re{move,place}_history_item are new in 2.4. |
|
2182 | 2183 | else: |
|
2183 | 2184 | self.input_hist_raw.append('%s\n' % line) |
|
2184 | 2185 | # only entries starting at first column go to shadow history |
|
2185 | 2186 | if line.lstrip() == line: |
|
2186 | 2187 | self.shadowhist.add(line.strip()) |
|
2187 | 2188 | elif not continue_prompt: |
|
2188 | 2189 | self.input_hist_raw.append('\n') |
|
2189 | 2190 | try: |
|
2190 | 2191 | lineout = self.prefilter(line,continue_prompt) |
|
2191 | 2192 | except: |
|
2192 | 2193 | # blanket except, in case a user-defined prefilter crashes, so it |
|
2193 | 2194 | # can't take all of ipython with it. |
|
2194 | 2195 | self.showtraceback() |
|
2195 | 2196 | return '' |
|
2196 | 2197 | else: |
|
2197 | 2198 | return lineout |
|
2198 | 2199 | |
|
2199 | 2200 | def _prefilter(self, line, continue_prompt): |
|
2200 | 2201 | """Calls different preprocessors, depending on the form of line.""" |
|
2201 | 2202 | |
|
2202 | 2203 | # All handlers *must* return a value, even if it's blank (''). |
|
2203 | 2204 | |
|
2204 | 2205 | # Lines are NOT logged here. Handlers should process the line as |
|
2205 | 2206 | # needed, update the cache AND log it (so that the input cache array |
|
2206 | 2207 | # stays synced). |
|
2207 | 2208 | |
|
2208 | 2209 | #..................................................................... |
|
2209 | 2210 | # Code begins |
|
2210 | 2211 | |
|
2211 | 2212 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg |
|
2212 | 2213 | |
|
2213 | 2214 | # save the line away in case we crash, so the post-mortem handler can |
|
2214 | 2215 | # record it |
|
2215 | 2216 | self._last_input_line = line |
|
2216 | 2217 | |
|
2217 | 2218 | #print '***line: <%s>' % line # dbg |
|
2218 | 2219 | |
|
2219 | 2220 | if not line: |
|
2220 | 2221 | # Return immediately on purely empty lines, so that if the user |
|
2221 | 2222 | # previously typed some whitespace that started a continuation |
|
2222 | 2223 | # prompt, he can break out of that loop with just an empty line. |
|
2223 | 2224 | # This is how the default python prompt works. |
|
2224 | 2225 | |
|
2225 | 2226 | # Only return if the accumulated input buffer was just whitespace! |
|
2226 | 2227 | if ''.join(self.buffer).isspace(): |
|
2227 | 2228 | self.buffer[:] = [] |
|
2228 | 2229 | return '' |
|
2229 | 2230 | |
|
2230 | 2231 | line_info = prefilter.LineInfo(line, continue_prompt) |
|
2231 | 2232 | |
|
2232 | 2233 | # the input history needs to track even empty lines |
|
2233 | 2234 | stripped = line.strip() |
|
2234 | 2235 | |
|
2235 | 2236 | if not stripped: |
|
2236 | 2237 | if not continue_prompt: |
|
2237 | 2238 | self.outputcache.prompt_count -= 1 |
|
2238 | 2239 | return self.handle_normal(line_info) |
|
2239 | 2240 | |
|
2240 | 2241 | # print '***cont',continue_prompt # dbg |
|
2241 | 2242 | # special handlers are only allowed for single line statements |
|
2242 | 2243 | if continue_prompt and not self.rc.multi_line_specials: |
|
2243 | 2244 | return self.handle_normal(line_info) |
|
2244 | 2245 | |
|
2245 | 2246 | |
|
2246 | 2247 | # See whether any pre-existing handler can take care of it |
|
2247 | 2248 | rewritten = self.hooks.input_prefilter(stripped) |
|
2248 | 2249 | if rewritten != stripped: # ok, some prefilter did something |
|
2249 | 2250 | rewritten = line_info.pre + rewritten # add indentation |
|
2250 | 2251 | return self.handle_normal(prefilter.LineInfo(rewritten, |
|
2251 | 2252 | continue_prompt)) |
|
2252 | 2253 | |
|
2253 | 2254 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2254 | 2255 | |
|
2255 | 2256 | return prefilter.prefilter(line_info, self) |
|
2256 | 2257 | |
|
2257 | 2258 | |
|
2258 | 2259 | def _prefilter_dumb(self, line, continue_prompt): |
|
2259 | 2260 | """simple prefilter function, for debugging""" |
|
2260 | 2261 | return self.handle_normal(line,continue_prompt) |
|
2261 | 2262 | |
|
2262 | 2263 | |
|
2263 | 2264 | def multiline_prefilter(self, line, continue_prompt): |
|
2264 | 2265 | """ Run _prefilter for each line of input |
|
2265 | 2266 | |
|
2266 | 2267 | Covers cases where there are multiple lines in the user entry, |
|
2267 | 2268 | which is the case when the user goes back to a multiline history |
|
2268 | 2269 | entry and presses enter. |
|
2269 | 2270 | |
|
2270 | 2271 | """ |
|
2271 | 2272 | out = [] |
|
2272 | 2273 | for l in line.rstrip('\n').split('\n'): |
|
2273 | 2274 | out.append(self._prefilter(l, continue_prompt)) |
|
2274 | 2275 | return '\n'.join(out) |
|
2275 | 2276 | |
|
2276 | 2277 | # Set the default prefilter() function (this can be user-overridden) |
|
2277 | 2278 | prefilter = multiline_prefilter |
|
2278 | 2279 | |
|
2279 | 2280 | def handle_normal(self,line_info): |
|
2280 | 2281 | """Handle normal input lines. Use as a template for handlers.""" |
|
2281 | 2282 | |
|
2282 | 2283 | # With autoindent on, we need some way to exit the input loop, and I |
|
2283 | 2284 | # don't want to force the user to have to backspace all the way to |
|
2284 | 2285 | # clear the line. The rule will be in this case, that either two |
|
2285 | 2286 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
2286 | 2287 | # of a size different to the indent level, will exit the input loop. |
|
2287 | 2288 | line = line_info.line |
|
2288 | 2289 | continue_prompt = line_info.continue_prompt |
|
2289 | 2290 | |
|
2290 | 2291 | if (continue_prompt and self.autoindent and line.isspace() and |
|
2291 | 2292 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or |
|
2292 | 2293 | (self.buffer[-1]).isspace() )): |
|
2293 | 2294 | line = '' |
|
2294 | 2295 | |
|
2295 | 2296 | self.log(line,line,continue_prompt) |
|
2296 | 2297 | return line |
|
2297 | 2298 | |
|
2298 | 2299 | def handle_alias(self,line_info): |
|
2299 | 2300 | """Handle alias input lines. """ |
|
2300 | 2301 | tgt = self.alias_table[line_info.iFun] |
|
2301 | 2302 | # print "=>",tgt #dbg |
|
2302 | 2303 | if callable(tgt): |
|
2303 | 2304 | if '$' in line_info.line: |
|
2304 | 2305 | call_meth = '(_ip, _ip.itpl(%s))' |
|
2305 | 2306 | else: |
|
2306 | 2307 | call_meth = '(_ip,%s)' |
|
2307 | 2308 | line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace, |
|
2308 | 2309 | line_info.iFun, |
|
2309 | 2310 | make_quoted_expr(line_info.line)) |
|
2310 | 2311 | else: |
|
2311 | 2312 | transformed = self.expand_aliases(line_info.iFun,line_info.theRest) |
|
2312 | 2313 | |
|
2313 | 2314 | # pre is needed, because it carries the leading whitespace. Otherwise |
|
2314 | 2315 | # aliases won't work in indented sections. |
|
2315 | 2316 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2316 | 2317 | make_quoted_expr( transformed )) |
|
2317 | 2318 | |
|
2318 | 2319 | self.log(line_info.line,line_out,line_info.continue_prompt) |
|
2319 | 2320 | #print 'line out:',line_out # dbg |
|
2320 | 2321 | return line_out |
|
2321 | 2322 | |
|
2322 | 2323 | def handle_shell_escape(self, line_info): |
|
2323 | 2324 | """Execute the line in a shell, empty return value""" |
|
2324 | 2325 | #print 'line in :', `line` # dbg |
|
2325 | 2326 | line = line_info.line |
|
2326 | 2327 | if line.lstrip().startswith('!!'): |
|
2327 | 2328 | # rewrite LineInfo's line, iFun and theRest to properly hold the |
|
2328 | 2329 | # call to %sx and the actual command to be executed, so |
|
2329 | 2330 | # handle_magic can work correctly. Note that this works even if |
|
2330 | 2331 | # the line is indented, so it handles multi_line_specials |
|
2331 | 2332 | # properly. |
|
2332 | 2333 | new_rest = line.lstrip()[2:] |
|
2333 | 2334 | line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest) |
|
2334 | 2335 | line_info.iFun = 'sx' |
|
2335 | 2336 | line_info.theRest = new_rest |
|
2336 | 2337 | return self.handle_magic(line_info) |
|
2337 | 2338 | else: |
|
2338 | 2339 | cmd = line.lstrip().lstrip('!') |
|
2339 | 2340 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2340 | 2341 | make_quoted_expr(cmd)) |
|
2341 | 2342 | # update cache/log and return |
|
2342 | 2343 | self.log(line,line_out,line_info.continue_prompt) |
|
2343 | 2344 | return line_out |
|
2344 | 2345 | |
|
2345 | 2346 | def handle_magic(self, line_info): |
|
2346 | 2347 | """Execute magic functions.""" |
|
2347 | 2348 | iFun = line_info.iFun |
|
2348 | 2349 | theRest = line_info.theRest |
|
2349 | 2350 | cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace, |
|
2350 | 2351 | make_quoted_expr(iFun + " " + theRest)) |
|
2351 | 2352 | self.log(line_info.line,cmd,line_info.continue_prompt) |
|
2352 | 2353 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg |
|
2353 | 2354 | return cmd |
|
2354 | 2355 | |
|
2355 | 2356 | def handle_auto(self, line_info): |
|
2356 | 2357 | """Hande lines which can be auto-executed, quoting if requested.""" |
|
2357 | 2358 | |
|
2358 | 2359 | line = line_info.line |
|
2359 | 2360 | iFun = line_info.iFun |
|
2360 | 2361 | theRest = line_info.theRest |
|
2361 | 2362 | pre = line_info.pre |
|
2362 | 2363 | continue_prompt = line_info.continue_prompt |
|
2363 | 2364 | obj = line_info.ofind(self)['obj'] |
|
2364 | 2365 | |
|
2365 | 2366 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2366 | 2367 | |
|
2367 | 2368 | # This should only be active for single-line input! |
|
2368 | 2369 | if continue_prompt: |
|
2369 | 2370 | self.log(line,line,continue_prompt) |
|
2370 | 2371 | return line |
|
2371 | 2372 | |
|
2372 | 2373 | force_auto = isinstance(obj, IPython.ipapi.IPyAutocall) |
|
2373 | 2374 | auto_rewrite = True |
|
2374 | 2375 | |
|
2375 | 2376 | if pre == self.ESC_QUOTE: |
|
2376 | 2377 | # Auto-quote splitting on whitespace |
|
2377 | 2378 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) |
|
2378 | 2379 | elif pre == self.ESC_QUOTE2: |
|
2379 | 2380 | # Auto-quote whole string |
|
2380 | 2381 | newcmd = '%s("%s")' % (iFun,theRest) |
|
2381 | 2382 | elif pre == self.ESC_PAREN: |
|
2382 | 2383 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) |
|
2383 | 2384 | else: |
|
2384 | 2385 | # Auto-paren. |
|
2385 | 2386 | # We only apply it to argument-less calls if the autocall |
|
2386 | 2387 | # parameter is set to 2. We only need to check that autocall is < |
|
2387 | 2388 | # 2, since this function isn't called unless it's at least 1. |
|
2388 | 2389 | if not theRest and (self.rc.autocall < 2) and not force_auto: |
|
2389 | 2390 | newcmd = '%s %s' % (iFun,theRest) |
|
2390 | 2391 | auto_rewrite = False |
|
2391 | 2392 | else: |
|
2392 | 2393 | if not force_auto and theRest.startswith('['): |
|
2393 | 2394 | if hasattr(obj,'__getitem__'): |
|
2394 | 2395 | # Don't autocall in this case: item access for an object |
|
2395 | 2396 | # which is BOTH callable and implements __getitem__. |
|
2396 | 2397 | newcmd = '%s %s' % (iFun,theRest) |
|
2397 | 2398 | auto_rewrite = False |
|
2398 | 2399 | else: |
|
2399 | 2400 | # if the object doesn't support [] access, go ahead and |
|
2400 | 2401 | # autocall |
|
2401 | 2402 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) |
|
2402 | 2403 | elif theRest.endswith(';'): |
|
2403 | 2404 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) |
|
2404 | 2405 | else: |
|
2405 | 2406 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) |
|
2406 | 2407 | |
|
2407 | 2408 | if auto_rewrite: |
|
2408 | 2409 | rw = self.outputcache.prompt1.auto_rewrite() + newcmd |
|
2409 | 2410 | |
|
2410 | 2411 | try: |
|
2411 | 2412 | # plain ascii works better w/ pyreadline, on some machines, so |
|
2412 | 2413 | # we use it and only print uncolored rewrite if we have unicode |
|
2413 | 2414 | rw = str(rw) |
|
2414 | 2415 | print >>Term.cout, rw |
|
2415 | 2416 | except UnicodeEncodeError: |
|
2416 | 2417 | print "-------------->" + newcmd |
|
2417 | 2418 | |
|
2418 | 2419 | # log what is now valid Python, not the actual user input (without the |
|
2419 | 2420 | # final newline) |
|
2420 | 2421 | self.log(line,newcmd,continue_prompt) |
|
2421 | 2422 | return newcmd |
|
2422 | 2423 | |
|
2423 | 2424 | def handle_help(self, line_info): |
|
2424 | 2425 | """Try to get some help for the object. |
|
2425 | 2426 | |
|
2426 | 2427 | obj? or ?obj -> basic information. |
|
2427 | 2428 | obj?? or ??obj -> more details. |
|
2428 | 2429 | """ |
|
2429 | 2430 | |
|
2430 | 2431 | line = line_info.line |
|
2431 | 2432 | # We need to make sure that we don't process lines which would be |
|
2432 | 2433 | # otherwise valid python, such as "x=1 # what?" |
|
2433 | 2434 | try: |
|
2434 | 2435 | codeop.compile_command(line) |
|
2435 | 2436 | except SyntaxError: |
|
2436 | 2437 | # We should only handle as help stuff which is NOT valid syntax |
|
2437 | 2438 | if line[0]==self.ESC_HELP: |
|
2438 | 2439 | line = line[1:] |
|
2439 | 2440 | elif line[-1]==self.ESC_HELP: |
|
2440 | 2441 | line = line[:-1] |
|
2441 | 2442 | self.log(line,'#?'+line,line_info.continue_prompt) |
|
2442 | 2443 | if line: |
|
2443 | 2444 | #print 'line:<%r>' % line # dbg |
|
2444 | 2445 | self.magic_pinfo(line) |
|
2445 | 2446 | else: |
|
2446 | 2447 | page(self.usage,screen_lines=self.rc.screen_length) |
|
2447 | 2448 | return '' # Empty string is needed here! |
|
2448 | 2449 | except: |
|
2449 | 2450 | # Pass any other exceptions through to the normal handler |
|
2450 | 2451 | return self.handle_normal(line_info) |
|
2451 | 2452 | else: |
|
2452 | 2453 | # If the code compiles ok, we should handle it normally |
|
2453 | 2454 | return self.handle_normal(line_info) |
|
2454 | 2455 | |
|
2455 | 2456 | def getapi(self): |
|
2456 | 2457 | """ Get an IPApi object for this shell instance |
|
2457 | 2458 | |
|
2458 | 2459 | Getting an IPApi object is always preferable to accessing the shell |
|
2459 | 2460 | directly, but this holds true especially for extensions. |
|
2460 | 2461 | |
|
2461 | 2462 | It should always be possible to implement an extension with IPApi |
|
2462 | 2463 | alone. If not, contact maintainer to request an addition. |
|
2463 | 2464 | |
|
2464 | 2465 | """ |
|
2465 | 2466 | return self.api |
|
2466 | 2467 | |
|
2467 | 2468 | def handle_emacs(self, line_info): |
|
2468 | 2469 | """Handle input lines marked by python-mode.""" |
|
2469 | 2470 | |
|
2470 | 2471 | # Currently, nothing is done. Later more functionality can be added |
|
2471 | 2472 | # here if needed. |
|
2472 | 2473 | |
|
2473 | 2474 | # The input cache shouldn't be updated |
|
2474 | 2475 | return line_info.line |
|
2475 | 2476 | |
|
2476 | 2477 | |
|
2477 | 2478 | def mktempfile(self,data=None): |
|
2478 | 2479 | """Make a new tempfile and return its filename. |
|
2479 | 2480 | |
|
2480 | 2481 | This makes a call to tempfile.mktemp, but it registers the created |
|
2481 | 2482 | filename internally so ipython cleans it up at exit time. |
|
2482 | 2483 | |
|
2483 | 2484 | Optional inputs: |
|
2484 | 2485 | |
|
2485 | 2486 | - data(None): if data is given, it gets written out to the temp file |
|
2486 | 2487 | immediately, and the file is closed again.""" |
|
2487 | 2488 | |
|
2488 | 2489 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2489 | 2490 | self.tempfiles.append(filename) |
|
2490 | 2491 | |
|
2491 | 2492 | if data: |
|
2492 | 2493 | tmp_file = open(filename,'w') |
|
2493 | 2494 | tmp_file.write(data) |
|
2494 | 2495 | tmp_file.close() |
|
2495 | 2496 | return filename |
|
2496 | 2497 | |
|
2497 | 2498 | def write(self,data): |
|
2498 | 2499 | """Write a string to the default output""" |
|
2499 | 2500 | Term.cout.write(data) |
|
2500 | 2501 | |
|
2501 | 2502 | def write_err(self,data): |
|
2502 | 2503 | """Write a string to the default error output""" |
|
2503 | 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 | 2510 | def exit(self): |
|
2506 | 2511 | """Handle interactive exit. |
|
2507 | 2512 | |
|
2508 |
This method |
|
|
2513 | This method calls the ask_exit callback.""" | |
|
2509 | 2514 | |
|
2510 | 2515 | if self.rc.confirm_exit: |
|
2511 | 2516 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
2512 |
self. |
|
|
2517 | self.ask_exit() | |
|
2513 | 2518 | else: |
|
2514 |
self. |
|
|
2519 | self.ask_exit() | |
|
2515 | 2520 | |
|
2516 | 2521 | def safe_execfile(self,fname,*where,**kw): |
|
2517 | 2522 | """A safe version of the builtin execfile(). |
|
2518 | 2523 | |
|
2519 | 2524 | This version will never throw an exception, and knows how to handle |
|
2520 | 2525 | ipython logs as well. |
|
2521 | 2526 | |
|
2522 | 2527 | :Parameters: |
|
2523 | 2528 | fname : string |
|
2524 | 2529 | Name of the file to be executed. |
|
2525 | 2530 | |
|
2526 | 2531 | where : tuple |
|
2527 | 2532 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2528 | 2533 | If only one is given, it is passed as both. |
|
2529 | 2534 | |
|
2530 | 2535 | :Keywords: |
|
2531 | 2536 | islog : boolean (False) |
|
2532 | 2537 | |
|
2533 | 2538 | quiet : boolean (True) |
|
2534 | 2539 | |
|
2535 | 2540 | exit_ignore : boolean (False) |
|
2536 | 2541 | """ |
|
2537 | 2542 | |
|
2538 | 2543 | def syspath_cleanup(): |
|
2539 | 2544 | """Internal cleanup routine for sys.path.""" |
|
2540 | 2545 | if add_dname: |
|
2541 | 2546 | try: |
|
2542 | 2547 | sys.path.remove(dname) |
|
2543 | 2548 | except ValueError: |
|
2544 | 2549 | # For some reason the user has already removed it, ignore. |
|
2545 | 2550 | pass |
|
2546 | 2551 | |
|
2547 | 2552 | fname = os.path.expanduser(fname) |
|
2548 | 2553 | |
|
2549 | 2554 | # Find things also in current directory. This is needed to mimic the |
|
2550 | 2555 | # behavior of running a script from the system command line, where |
|
2551 | 2556 | # Python inserts the script's directory into sys.path |
|
2552 | 2557 | dname = os.path.dirname(os.path.abspath(fname)) |
|
2553 | 2558 | add_dname = False |
|
2554 | 2559 | if dname not in sys.path: |
|
2555 | 2560 | sys.path.insert(0,dname) |
|
2556 | 2561 | add_dname = True |
|
2557 | 2562 | |
|
2558 | 2563 | try: |
|
2559 | 2564 | xfile = open(fname) |
|
2560 | 2565 | except: |
|
2561 | 2566 | print >> Term.cerr, \ |
|
2562 | 2567 | 'Could not open file <%s> for safe execution.' % fname |
|
2563 | 2568 | syspath_cleanup() |
|
2564 | 2569 | return None |
|
2565 | 2570 | |
|
2566 | 2571 | kw.setdefault('islog',0) |
|
2567 | 2572 | kw.setdefault('quiet',1) |
|
2568 | 2573 | kw.setdefault('exit_ignore',0) |
|
2569 | 2574 | |
|
2570 | 2575 | first = xfile.readline() |
|
2571 | 2576 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() |
|
2572 | 2577 | xfile.close() |
|
2573 | 2578 | # line by line execution |
|
2574 | 2579 | if first.startswith(loghead) or kw['islog']: |
|
2575 | 2580 | print 'Loading log file <%s> one line at a time...' % fname |
|
2576 | 2581 | if kw['quiet']: |
|
2577 | 2582 | stdout_save = sys.stdout |
|
2578 | 2583 | sys.stdout = StringIO.StringIO() |
|
2579 | 2584 | try: |
|
2580 | 2585 | globs,locs = where[0:2] |
|
2581 | 2586 | except: |
|
2582 | 2587 | try: |
|
2583 | 2588 | globs = locs = where[0] |
|
2584 | 2589 | except: |
|
2585 | 2590 | globs = locs = globals() |
|
2586 | 2591 | badblocks = [] |
|
2587 | 2592 | |
|
2588 | 2593 | # we also need to identify indented blocks of code when replaying |
|
2589 | 2594 | # logs and put them together before passing them to an exec |
|
2590 | 2595 | # statement. This takes a bit of regexp and look-ahead work in the |
|
2591 | 2596 | # file. It's easiest if we swallow the whole thing in memory |
|
2592 | 2597 | # first, and manually walk through the lines list moving the |
|
2593 | 2598 | # counter ourselves. |
|
2594 | 2599 | indent_re = re.compile('\s+\S') |
|
2595 | 2600 | xfile = open(fname) |
|
2596 | 2601 | filelines = xfile.readlines() |
|
2597 | 2602 | xfile.close() |
|
2598 | 2603 | nlines = len(filelines) |
|
2599 | 2604 | lnum = 0 |
|
2600 | 2605 | while lnum < nlines: |
|
2601 | 2606 | line = filelines[lnum] |
|
2602 | 2607 | lnum += 1 |
|
2603 | 2608 | # don't re-insert logger status info into cache |
|
2604 | 2609 | if line.startswith('#log#'): |
|
2605 | 2610 | continue |
|
2606 | 2611 | else: |
|
2607 | 2612 | # build a block of code (maybe a single line) for execution |
|
2608 | 2613 | block = line |
|
2609 | 2614 | try: |
|
2610 | 2615 | next = filelines[lnum] # lnum has already incremented |
|
2611 | 2616 | except: |
|
2612 | 2617 | next = None |
|
2613 | 2618 | while next and indent_re.match(next): |
|
2614 | 2619 | block += next |
|
2615 | 2620 | lnum += 1 |
|
2616 | 2621 | try: |
|
2617 | 2622 | next = filelines[lnum] |
|
2618 | 2623 | except: |
|
2619 | 2624 | next = None |
|
2620 | 2625 | # now execute the block of one or more lines |
|
2621 | 2626 | try: |
|
2622 | 2627 | exec block in globs,locs |
|
2623 | 2628 | except SystemExit: |
|
2624 | 2629 | pass |
|
2625 | 2630 | except: |
|
2626 | 2631 | badblocks.append(block.rstrip()) |
|
2627 | 2632 | if kw['quiet']: # restore stdout |
|
2628 | 2633 | sys.stdout.close() |
|
2629 | 2634 | sys.stdout = stdout_save |
|
2630 | 2635 | print 'Finished replaying log file <%s>' % fname |
|
2631 | 2636 | if badblocks: |
|
2632 | 2637 | print >> sys.stderr, ('\nThe following lines/blocks in file ' |
|
2633 | 2638 | '<%s> reported errors:' % fname) |
|
2634 | 2639 | |
|
2635 | 2640 | for badline in badblocks: |
|
2636 | 2641 | print >> sys.stderr, badline |
|
2637 | 2642 | else: # regular file execution |
|
2638 | 2643 | try: |
|
2639 | 2644 | if sys.platform == 'win32' and sys.version_info < (2,5,1): |
|
2640 | 2645 | # Work around a bug in Python for Windows. The bug was |
|
2641 | 2646 | # fixed in in Python 2.5 r54159 and 54158, but that's still |
|
2642 | 2647 | # SVN Python as of March/07. For details, see: |
|
2643 | 2648 | # http://projects.scipy.org/ipython/ipython/ticket/123 |
|
2644 | 2649 | try: |
|
2645 | 2650 | globs,locs = where[0:2] |
|
2646 | 2651 | except: |
|
2647 | 2652 | try: |
|
2648 | 2653 | globs = locs = where[0] |
|
2649 | 2654 | except: |
|
2650 | 2655 | globs = locs = globals() |
|
2651 | 2656 | exec file(fname) in globs,locs |
|
2652 | 2657 | else: |
|
2653 | 2658 | execfile(fname,*where) |
|
2654 | 2659 | except SyntaxError: |
|
2655 | 2660 | self.showsyntaxerror() |
|
2656 | 2661 | warn('Failure executing file: <%s>' % fname) |
|
2657 | 2662 | except SystemExit,status: |
|
2658 | 2663 | # Code that correctly sets the exit status flag to success (0) |
|
2659 | 2664 | # shouldn't be bothered with a traceback. Note that a plain |
|
2660 | 2665 | # sys.exit() does NOT set the message to 0 (it's empty) so that |
|
2661 | 2666 | # will still get a traceback. Note that the structure of the |
|
2662 | 2667 | # SystemExit exception changed between Python 2.4 and 2.5, so |
|
2663 | 2668 | # the checks must be done in a version-dependent way. |
|
2664 | 2669 | show = False |
|
2665 | 2670 | |
|
2666 | 2671 | if sys.version_info[:2] > (2,5): |
|
2667 | 2672 | if status.message!=0 and not kw['exit_ignore']: |
|
2668 | 2673 | show = True |
|
2669 | 2674 | else: |
|
2670 | 2675 | if status.code and not kw['exit_ignore']: |
|
2671 | 2676 | show = True |
|
2672 | 2677 | if show: |
|
2673 | 2678 | self.showtraceback() |
|
2674 | 2679 | warn('Failure executing file: <%s>' % fname) |
|
2675 | 2680 | except: |
|
2676 | 2681 | self.showtraceback() |
|
2677 | 2682 | warn('Failure executing file: <%s>' % fname) |
|
2678 | 2683 | |
|
2679 | 2684 | syspath_cleanup() |
|
2680 | 2685 | |
|
2681 | 2686 | #************************* end of file <iplib.py> ***************************** |
@@ -1,137 +1,137 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | |
|
3 | 3 | """ Manage the input and output history of the interpreter and the |
|
4 | 4 | frontend. |
|
5 | 5 | |
|
6 | 6 | There are 2 different history objects, one that lives in the interpreter, |
|
7 | 7 | and one that lives in the frontend. They are synced with a diff at each |
|
8 | 8 | execution of a command, as the interpreter history is a real stack, its |
|
9 | 9 | existing entries are not mutable. |
|
10 | 10 | """ |
|
11 | 11 | |
|
12 | 12 | __docformat__ = "restructuredtext en" |
|
13 | 13 | |
|
14 | 14 | #------------------------------------------------------------------------------- |
|
15 | 15 | # Copyright (C) 2008 The IPython Development Team |
|
16 | 16 | # |
|
17 | 17 | # Distributed under the terms of the BSD License. The full license is in |
|
18 | 18 | # the file COPYING, distributed as part of this software. |
|
19 | 19 | #------------------------------------------------------------------------------- |
|
20 | 20 | |
|
21 | 21 | #------------------------------------------------------------------------------- |
|
22 | 22 | # Imports |
|
23 | 23 | #------------------------------------------------------------------------------- |
|
24 | 24 | |
|
25 | 25 | from copy import copy |
|
26 | 26 | |
|
27 | 27 | # Local imports. |
|
28 | 28 | from util import InputList |
|
29 | 29 | |
|
30 | 30 | |
|
31 | 31 | ############################################################################## |
|
32 | 32 | class History(object): |
|
33 | 33 | """ An object managing the input and output history. |
|
34 | 34 | """ |
|
35 | 35 | |
|
36 | 36 | def __init__(self, input_cache=None, output_cache=None): |
|
37 | 37 | |
|
38 | 38 | # Stuff that IPython adds to the namespace. |
|
39 | 39 | self.namespace_additions = dict( |
|
40 | 40 | _ = None, |
|
41 | 41 | __ = None, |
|
42 | 42 | ___ = None, |
|
43 | 43 | ) |
|
44 | 44 | |
|
45 | 45 | # A list to store input commands. |
|
46 | 46 | if input_cache is None: |
|
47 | 47 | input_cache =InputList([]) |
|
48 | 48 | self.input_cache = input_cache |
|
49 | 49 | |
|
50 | 50 | # A dictionary to store trapped output. |
|
51 | 51 | if output_cache is None: |
|
52 | 52 | output_cache = {} |
|
53 | 53 | self.output_cache = output_cache |
|
54 | 54 | |
|
55 | 55 | def get_history_item(self, index): |
|
56 | 56 | """ Returns the history string at index, where index is the |
|
57 | 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 | 60 | return self.input_cache[index] |
|
61 | 61 | |
|
62 | 62 | |
|
63 | 63 | ############################################################################## |
|
64 | 64 | class InterpreterHistory(History): |
|
65 | 65 | """ An object managing the input and output history at the interpreter |
|
66 | 66 | level. |
|
67 | 67 | """ |
|
68 | 68 | |
|
69 | 69 | def setup_namespace(self, namespace): |
|
70 | 70 | """ Add the input and output caches into the interpreter's namespace |
|
71 | 71 | with IPython-conventional names. |
|
72 | 72 | |
|
73 | 73 | Parameters |
|
74 | 74 | ---------- |
|
75 | 75 | namespace : dict |
|
76 | 76 | """ |
|
77 | 77 | |
|
78 | 78 | namespace['In'] = self.input_cache |
|
79 | 79 | namespace['_ih'] = self.input_cache |
|
80 | 80 | namespace['Out'] = self.output_cache |
|
81 | 81 | namespace['_oh'] = self.output_cache |
|
82 | 82 | |
|
83 | 83 | def update_history(self, interpreter, python): |
|
84 | 84 | """ Update the history objects that this object maintains and the |
|
85 | 85 | interpreter's namespace. |
|
86 | 86 | |
|
87 | 87 | Parameters |
|
88 | 88 | ---------- |
|
89 | 89 | interpreter : Interpreter |
|
90 | 90 | python : str |
|
91 | 91 | The real Python code that was translated and actually executed. |
|
92 | 92 | """ |
|
93 | 93 | |
|
94 | 94 | number = interpreter.current_cell_number |
|
95 | 95 | |
|
96 | 96 | new_obj = interpreter.display_trap.obj |
|
97 | 97 | if new_obj is not None: |
|
98 | 98 | self.namespace_additions['___'] = self.namespace_additions['__'] |
|
99 | 99 | self.namespace_additions['__'] = self.namespace_additions['_'] |
|
100 | 100 | self.namespace_additions['_'] = new_obj |
|
101 | 101 | self.output_cache[number] = new_obj |
|
102 | 102 | |
|
103 | 103 | interpreter.user_ns.update(self.namespace_additions) |
|
104 | 104 | self.input_cache.add(number, python) |
|
105 | 105 | |
|
106 | 106 | |
|
107 | 107 | def get_history_item(self, index): |
|
108 | 108 | """ Returns the history string at index, where index is the |
|
109 | 109 | distance from the end (positive). |
|
110 | 110 | """ |
|
111 | 111 | if index>0 and index<(len(self.input_cache)-1): |
|
112 | 112 | return self.input_cache[-index] |
|
113 | 113 | |
|
114 | 114 | def get_input_cache(self): |
|
115 | 115 | return copy(self.input_cache) |
|
116 | 116 | |
|
117 | 117 | def get_input_after(self, index): |
|
118 | 118 | """ Returns the list of the commands entered after index. |
|
119 | 119 | """ |
|
120 | 120 | # We need to call directly list.__getslice__, because this object |
|
121 | 121 | # is not a real list. |
|
122 | 122 | return list.__getslice__(self.input_cache, index, |
|
123 | 123 | len(self.input_cache)) |
|
124 | 124 | |
|
125 | 125 | |
|
126 | 126 | ############################################################################## |
|
127 | 127 | class FrontEndHistory(History): |
|
128 | 128 | """ An object managing the input and output history at the frontend. |
|
129 | 129 | It is used as a local cache to reduce network latency problems |
|
130 | 130 | and multiple users editing the same thing. |
|
131 | 131 | """ |
|
132 | 132 | |
|
133 | 133 | def add_items(self, item_list): |
|
134 | 134 | """ Adds the given command list to the stack of executed |
|
135 | 135 | commands. |
|
136 | 136 | """ |
|
137 | 137 | self.input_cache.extend(item_list) |
@@ -1,749 +1,747 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | |
|
3 | 3 | """Central interpreter object for an IPython engine. |
|
4 | 4 | |
|
5 | 5 | The interpreter is the object whose job is to process lines of user input and |
|
6 | 6 | actually execute them in the user's namespace. |
|
7 | 7 | """ |
|
8 | 8 | |
|
9 | 9 | __docformat__ = "restructuredtext en" |
|
10 | 10 | |
|
11 | 11 | #------------------------------------------------------------------------------- |
|
12 | 12 | # Copyright (C) 2008 The IPython Development Team |
|
13 | 13 | # |
|
14 | 14 | # Distributed under the terms of the BSD License. The full license is in |
|
15 | 15 | # the file COPYING, distributed as part of this software. |
|
16 | 16 | #------------------------------------------------------------------------------- |
|
17 | 17 | |
|
18 | 18 | #------------------------------------------------------------------------------- |
|
19 | 19 | # Imports |
|
20 | 20 | #------------------------------------------------------------------------------- |
|
21 | 21 | |
|
22 | 22 | # Standard library imports. |
|
23 | from compiler.ast import Discard | |
|
24 | 23 | from types import FunctionType |
|
25 | 24 | |
|
26 | 25 | import __builtin__ |
|
27 | 26 | import codeop |
|
28 | 27 | import compiler |
|
29 | import pprint | |
|
30 | 28 | import sys |
|
31 | 29 | import traceback |
|
32 | 30 | |
|
33 | 31 | # Local imports. |
|
34 | 32 | from IPython.kernel.core import ultraTB |
|
35 | 33 | from IPython.kernel.core.display_trap import DisplayTrap |
|
36 | 34 | from IPython.kernel.core.macro import Macro |
|
37 | 35 | from IPython.kernel.core.prompts import CachedOutput |
|
38 | 36 | from IPython.kernel.core.traceback_trap import TracebackTrap |
|
39 | 37 | from IPython.kernel.core.util import Bunch, system_shell |
|
40 | 38 | from IPython.external.Itpl import ItplNS |
|
41 | 39 | |
|
42 | 40 | # Global constants |
|
43 | 41 | COMPILER_ERROR = 'error' |
|
44 | 42 | INCOMPLETE_INPUT = 'incomplete' |
|
45 | 43 | COMPLETE_INPUT = 'complete' |
|
46 | 44 | |
|
47 | 45 | ############################################################################## |
|
48 | 46 | # TEMPORARY!!! fake configuration, while we decide whether to use tconfig or |
|
49 | 47 | # not |
|
50 | 48 | |
|
51 | 49 | rc = Bunch() |
|
52 | 50 | rc.cache_size = 100 |
|
53 | 51 | rc.pprint = True |
|
54 | 52 | rc.separate_in = '\n' |
|
55 | 53 | rc.separate_out = '\n' |
|
56 | 54 | rc.separate_out2 = '' |
|
57 | 55 | rc.prompt_in1 = r'In [\#]: ' |
|
58 | 56 | rc.prompt_in2 = r' .\\D.: ' |
|
59 | 57 | rc.prompt_out = '' |
|
60 | 58 | rc.prompts_pad_left = False |
|
61 | 59 | |
|
62 | 60 | ############################################################################## |
|
63 | 61 | |
|
64 | 62 | # Top-level utilities |
|
65 | 63 | def default_display_formatters(): |
|
66 | 64 | """ Return a list of default display formatters. |
|
67 | 65 | """ |
|
68 | 66 | |
|
69 | 67 | from display_formatter import PPrintDisplayFormatter, ReprDisplayFormatter |
|
70 | 68 | return [PPrintDisplayFormatter(), ReprDisplayFormatter()] |
|
71 | 69 | |
|
72 | 70 | def default_traceback_formatters(): |
|
73 | 71 | """ Return a list of default traceback formatters. |
|
74 | 72 | """ |
|
75 | 73 | |
|
76 | 74 | from traceback_formatter import PlainTracebackFormatter |
|
77 | 75 | return [PlainTracebackFormatter()] |
|
78 | 76 | |
|
79 | 77 | # Top-level classes |
|
80 | 78 | class NotDefined(object): pass |
|
81 | 79 | |
|
82 | 80 | class Interpreter(object): |
|
83 | 81 | """ An interpreter object. |
|
84 | 82 | |
|
85 | 83 | fixme: needs to negotiate available formatters with frontends. |
|
86 | 84 | |
|
87 | 85 | Important: the interpeter should be built so that it exposes a method |
|
88 | 86 | for each attribute/method of its sub-object. This way it can be |
|
89 | 87 | replaced by a network adapter. |
|
90 | 88 | """ |
|
91 | 89 | |
|
92 | 90 | def __init__(self, user_ns=None, global_ns=None,translator=None, |
|
93 | 91 | magic=None, display_formatters=None, |
|
94 | 92 | traceback_formatters=None, output_trap=None, history=None, |
|
95 | 93 | message_cache=None, filename='<string>', config=None): |
|
96 | 94 | |
|
97 | 95 | # The local/global namespaces for code execution |
|
98 | 96 | local_ns = user_ns # compatibility name |
|
99 | 97 | if local_ns is None: |
|
100 | 98 | local_ns = {} |
|
101 | 99 | self.user_ns = local_ns |
|
102 | 100 | # The local namespace |
|
103 | 101 | if global_ns is None: |
|
104 | 102 | global_ns = {} |
|
105 | 103 | self.user_global_ns = global_ns |
|
106 | 104 | |
|
107 | 105 | # An object that will translate commands into executable Python. |
|
108 | 106 | # The current translator does not work properly so for now we are going |
|
109 | 107 | # without! |
|
110 | 108 | # if translator is None: |
|
111 | 109 | # from IPython.kernel.core.translator import IPythonTranslator |
|
112 | 110 | # translator = IPythonTranslator() |
|
113 | 111 | self.translator = translator |
|
114 | 112 | |
|
115 | 113 | # An object that maintains magic commands. |
|
116 | 114 | if magic is None: |
|
117 | 115 | from IPython.kernel.core.magic import Magic |
|
118 | 116 | magic = Magic(self) |
|
119 | 117 | self.magic = magic |
|
120 | 118 | |
|
121 | 119 | # A list of formatters for the displayhook. |
|
122 | 120 | if display_formatters is None: |
|
123 | 121 | display_formatters = default_display_formatters() |
|
124 | 122 | self.display_formatters = display_formatters |
|
125 | 123 | |
|
126 | 124 | # A list of formatters for tracebacks. |
|
127 | 125 | if traceback_formatters is None: |
|
128 | 126 | traceback_formatters = default_traceback_formatters() |
|
129 | 127 | self.traceback_formatters = traceback_formatters |
|
130 | 128 | |
|
131 | 129 | # The object trapping stdout/stderr. |
|
132 | 130 | if output_trap is None: |
|
133 | 131 | from IPython.kernel.core.output_trap import OutputTrap |
|
134 | 132 | output_trap = OutputTrap() |
|
135 | 133 | self.output_trap = output_trap |
|
136 | 134 | |
|
137 | 135 | # An object that manages the history. |
|
138 | 136 | if history is None: |
|
139 | 137 | from IPython.kernel.core.history import InterpreterHistory |
|
140 | 138 | history = InterpreterHistory() |
|
141 | 139 | self.history = history |
|
142 | 140 | self.get_history_item = history.get_history_item |
|
143 | 141 | self.get_history_input_cache = history.get_input_cache |
|
144 | 142 | self.get_history_input_after = history.get_input_after |
|
145 | 143 | |
|
146 | 144 | # An object that caches all of the return messages. |
|
147 | 145 | if message_cache is None: |
|
148 | 146 | from IPython.kernel.core.message_cache import SimpleMessageCache |
|
149 | 147 | message_cache = SimpleMessageCache() |
|
150 | 148 | self.message_cache = message_cache |
|
151 | 149 | |
|
152 | 150 | # The "filename" of the code that is executed in this interpreter. |
|
153 | 151 | self.filename = filename |
|
154 | 152 | |
|
155 | 153 | # An object that contains much configuration information. |
|
156 | 154 | if config is None: |
|
157 | 155 | # fixme: Move this constant elsewhere! |
|
158 | 156 | config = Bunch(ESC_MAGIC='%') |
|
159 | 157 | self.config = config |
|
160 | 158 | |
|
161 | 159 | # Hook managers. |
|
162 | 160 | # fixme: make the display callbacks configurable. In the meantime, |
|
163 | 161 | # enable macros. |
|
164 | 162 | self.display_trap = DisplayTrap( |
|
165 | 163 | formatters=self.display_formatters, |
|
166 | 164 | callbacks=[self._possible_macro], |
|
167 | 165 | ) |
|
168 | 166 | self.traceback_trap = TracebackTrap( |
|
169 | 167 | formatters=self.traceback_formatters) |
|
170 | 168 | |
|
171 | 169 | # This is used temporarily for reformating exceptions in certain |
|
172 | 170 | # cases. It will go away once the ultraTB stuff is ported |
|
173 | 171 | # to ipython1 |
|
174 | 172 | self.tbHandler = ultraTB.FormattedTB(color_scheme='NoColor', |
|
175 | 173 | mode='Context', |
|
176 | 174 | tb_offset=2) |
|
177 | 175 | |
|
178 | 176 | # An object that can compile commands and remember __future__ |
|
179 | 177 | # statements. |
|
180 | 178 | self.command_compiler = codeop.CommandCompiler() |
|
181 | 179 | |
|
182 | 180 | # A replacement for the raw_input() and input() builtins. Change these |
|
183 | 181 | # attributes later to configure them. |
|
184 | 182 | self.raw_input_builtin = raw_input |
|
185 | 183 | self.input_builtin = input |
|
186 | 184 | |
|
187 | 185 | # The number of the current cell. |
|
188 | 186 | self.current_cell_number = 1 |
|
189 | 187 | |
|
190 | 188 | # Initialize cache, set in/out prompts and printing system |
|
191 | 189 | self.outputcache = CachedOutput(self, |
|
192 | 190 | rc.cache_size, |
|
193 | 191 | rc.pprint, |
|
194 | 192 | input_sep = rc.separate_in, |
|
195 | 193 | output_sep = rc.separate_out, |
|
196 | 194 | output_sep2 = rc.separate_out2, |
|
197 | 195 | ps1 = rc.prompt_in1, |
|
198 | 196 | ps2 = rc.prompt_in2, |
|
199 | 197 | ps_out = rc.prompt_out, |
|
200 | 198 | pad_left = rc.prompts_pad_left) |
|
201 | 199 | |
|
202 | 200 | # Need to decide later if this is the right approach, but clients |
|
203 | 201 | # commonly use sys.ps1/2, so it may be best to just set them here |
|
204 | 202 | sys.ps1 = self.outputcache.prompt1.p_str |
|
205 | 203 | sys.ps2 = self.outputcache.prompt2.p_str |
|
206 | 204 | |
|
207 | 205 | # This is the message dictionary assigned temporarily when running the |
|
208 | 206 | # code. |
|
209 | 207 | self.message = None |
|
210 | 208 | |
|
211 | 209 | self.setup_namespace() |
|
212 | 210 | |
|
213 | 211 | |
|
214 | 212 | #### Public 'Interpreter' interface ######################################## |
|
215 | 213 | |
|
216 | 214 | def formatTraceback(self, et, ev, tb, message=''): |
|
217 | 215 | """Put a formatted version of the traceback into value and reraise. |
|
218 | 216 | |
|
219 | 217 | When exceptions have to be sent over the network, the traceback |
|
220 | 218 | needs to be put into the value of the exception in a nicely |
|
221 | 219 | formatted way. The method takes the type, value and tb of an |
|
222 | 220 | exception and puts a string representation of the tb into the |
|
223 | 221 | value of the exception and reraises it. |
|
224 | 222 | |
|
225 | 223 | Currently this method uses the ultraTb formatter from IPython trunk. |
|
226 | 224 | Eventually it should simply use the traceback formatters in core |
|
227 | 225 | that are loaded into self.tracback_trap.formatters. |
|
228 | 226 | """ |
|
229 | 227 | tbinfo = self.tbHandler.text(et,ev,tb) |
|
230 | 228 | ev._ipython_traceback_text = tbinfo |
|
231 | 229 | return et, ev, tb |
|
232 | 230 | |
|
233 | 231 | def execute(self, commands, raiseException=True): |
|
234 | 232 | """ Execute some IPython commands. |
|
235 | 233 | |
|
236 | 234 | 1. Translate them into Python. |
|
237 | 235 | 2. Run them. |
|
238 | 236 | 3. Trap stdout/stderr. |
|
239 | 237 | 4. Trap sys.displayhook(). |
|
240 | 238 | 5. Trap exceptions. |
|
241 | 239 | 6. Return a message object. |
|
242 | 240 | |
|
243 | 241 | Parameters |
|
244 | 242 | ---------- |
|
245 | 243 | commands : str |
|
246 | 244 | The raw commands that the user typed into the prompt. |
|
247 | 245 | |
|
248 | 246 | Returns |
|
249 | 247 | ------- |
|
250 | 248 | message : dict |
|
251 | 249 | The dictionary of responses. See the README.txt in this directory |
|
252 | 250 | for an explanation of the format. |
|
253 | 251 | """ |
|
254 | 252 | |
|
255 | 253 | # Create a message dictionary with all of the information we will be |
|
256 | 254 | # returning to the frontend and other listeners. |
|
257 | 255 | message = self.setup_message() |
|
258 | 256 | |
|
259 | 257 | # Massage the input and store the raw and translated commands into |
|
260 | 258 | # a dict. |
|
261 | 259 | user_input = dict(raw=commands) |
|
262 | 260 | if self.translator is not None: |
|
263 | 261 | python = self.translator(commands, message) |
|
264 | 262 | if python is None: |
|
265 | 263 | # Something went wrong with the translation. The translator |
|
266 | 264 | # should have added an appropriate entry to the message object. |
|
267 | 265 | return message |
|
268 | 266 | else: |
|
269 | 267 | python = commands |
|
270 | 268 | user_input['translated'] = python |
|
271 | 269 | message['input'] = user_input |
|
272 | 270 | |
|
273 | 271 | # Set the message object so that any magics executed in the code have |
|
274 | 272 | # access. |
|
275 | 273 | self.message = message |
|
276 | 274 | |
|
277 | 275 | # Set all of the output/exception traps. |
|
278 | 276 | self.set_traps() |
|
279 | 277 | |
|
280 | 278 | # Actually execute the Python code. |
|
281 | 279 | status = self.execute_python(python) |
|
282 | 280 | |
|
283 | 281 | # Unset all of the traps. |
|
284 | 282 | self.unset_traps() |
|
285 | 283 | |
|
286 | 284 | # Unset the message object. |
|
287 | 285 | self.message = None |
|
288 | 286 | |
|
289 | 287 | # Update the history variables in the namespace. |
|
290 | 288 | # E.g. In, Out, _, __, ___ |
|
291 | 289 | if self.history is not None: |
|
292 | 290 | self.history.update_history(self, python) |
|
293 | 291 | |
|
294 | 292 | # Let all of the traps contribute to the message and then clear their |
|
295 | 293 | # stored information. |
|
296 | 294 | self.output_trap.add_to_message(message) |
|
297 | 295 | self.output_trap.clear() |
|
298 | 296 | self.display_trap.add_to_message(message) |
|
299 | 297 | self.display_trap.clear() |
|
300 | 298 | self.traceback_trap.add_to_message(message) |
|
301 | 299 | # Pull out the type, value and tb of the current exception |
|
302 | 300 | # before clearing it. |
|
303 | 301 | einfo = self.traceback_trap.args |
|
304 | 302 | self.traceback_trap.clear() |
|
305 | 303 | |
|
306 | 304 | # Cache the message. |
|
307 | 305 | self.message_cache.add_message(self.current_cell_number, message) |
|
308 | 306 | |
|
309 | 307 | # Bump the number. |
|
310 | 308 | self.current_cell_number += 1 |
|
311 | 309 | |
|
312 | 310 | # This conditional lets the execute method either raise any |
|
313 | 311 | # exception that has occured in user code OR return the message |
|
314 | 312 | # dict containing the traceback and other useful info. |
|
315 | 313 | if raiseException and einfo: |
|
316 | 314 | raise einfo[0],einfo[1],einfo[2] |
|
317 | 315 | else: |
|
318 | 316 | return message |
|
319 | 317 | |
|
320 | 318 | def generate_prompt(self, is_continuation): |
|
321 | 319 | """Calculate and return a string with the prompt to display. |
|
322 | 320 | |
|
323 | 321 | :Parameters: |
|
324 | 322 | is_continuation : bool |
|
325 | 323 | Whether the input line is continuing multiline input or not, so |
|
326 | 324 | that a proper continuation prompt can be computed.""" |
|
327 | 325 | |
|
328 | 326 | if is_continuation: |
|
329 | 327 | return str(self.outputcache.prompt2) |
|
330 | 328 | else: |
|
331 | 329 | return str(self.outputcache.prompt1) |
|
332 | 330 | |
|
333 | 331 | def execute_python(self, python): |
|
334 | 332 | """ Actually run the Python code in the namespace. |
|
335 | 333 | |
|
336 | 334 | :Parameters: |
|
337 | 335 | |
|
338 | 336 | python : str |
|
339 | 337 | Pure, exec'able Python code. Special IPython commands should have |
|
340 | 338 | already been translated into pure Python. |
|
341 | 339 | """ |
|
342 | 340 | |
|
343 | 341 | # We use a CommandCompiler instance to compile the code so as to keep |
|
344 | 342 | # track of __future__ imports. |
|
345 | 343 | try: |
|
346 | 344 | commands = self.split_commands(python) |
|
347 | 345 | except (SyntaxError, IndentationError), e: |
|
348 | 346 | # Save the exc_info so compilation related exceptions can be |
|
349 | 347 | # reraised |
|
350 | 348 | self.traceback_trap.args = sys.exc_info() |
|
351 | 349 | self.pack_exception(self.message,e) |
|
352 | 350 | return None |
|
353 | 351 | |
|
354 | 352 | for cmd in commands: |
|
355 | 353 | try: |
|
356 | 354 | code = self.command_compiler(cmd, self.filename, 'single') |
|
357 | 355 | except (SyntaxError, OverflowError, ValueError), e: |
|
358 | 356 | self.traceback_trap.args = sys.exc_info() |
|
359 | 357 | self.pack_exception(self.message,e) |
|
360 | 358 | # No point in continuing if one block raised |
|
361 | 359 | return None |
|
362 | 360 | else: |
|
363 | 361 | self.execute_block(code) |
|
364 | 362 | |
|
365 | 363 | def execute_block(self,code): |
|
366 | 364 | """Execute a single block of code in the user namespace. |
|
367 | 365 | |
|
368 | 366 | Return value: a flag indicating whether the code to be run completed |
|
369 | 367 | successfully: |
|
370 | 368 | |
|
371 | 369 | - 0: successful execution. |
|
372 | 370 | - 1: an error occurred. |
|
373 | 371 | """ |
|
374 | 372 | |
|
375 | 373 | outflag = 1 # start by assuming error, success will reset it |
|
376 | 374 | try: |
|
377 | 375 | exec code in self.user_ns |
|
378 | 376 | outflag = 0 |
|
379 | 377 | except SystemExit: |
|
380 | 378 | self.resetbuffer() |
|
381 | 379 | self.traceback_trap.args = sys.exc_info() |
|
382 | 380 | except: |
|
383 | 381 | self.traceback_trap.args = sys.exc_info() |
|
384 | 382 | |
|
385 | 383 | return outflag |
|
386 | 384 | |
|
387 | 385 | def execute_macro(self, macro): |
|
388 | 386 | """ Execute the value of a macro. |
|
389 | 387 | |
|
390 | 388 | Parameters |
|
391 | 389 | ---------- |
|
392 | 390 | macro : Macro |
|
393 | 391 | """ |
|
394 | 392 | |
|
395 | 393 | python = macro.value |
|
396 | 394 | if self.translator is not None: |
|
397 | 395 | python = self.translator(python) |
|
398 | 396 | self.execute_python(python) |
|
399 | 397 | |
|
400 | 398 | def getCommand(self, i=None): |
|
401 | 399 | """Gets the ith message in the message_cache. |
|
402 | 400 | |
|
403 | 401 | This is implemented here for compatibility with the old ipython1 shell |
|
404 | 402 | I am not sure we need this though. I even seem to remember that we |
|
405 | 403 | were going to get rid of it. |
|
406 | 404 | """ |
|
407 | 405 | return self.message_cache.get_message(i) |
|
408 | 406 | |
|
409 | 407 | def reset(self): |
|
410 | 408 | """Reset the interpreter. |
|
411 | 409 | |
|
412 | 410 | Currently this only resets the users variables in the namespace. |
|
413 | 411 | In the future we might want to also reset the other stateful |
|
414 | 412 | things like that the Interpreter has, like In, Out, etc. |
|
415 | 413 | """ |
|
416 | 414 | self.user_ns.clear() |
|
417 | 415 | self.setup_namespace() |
|
418 | 416 | |
|
419 | 417 | def complete(self,line,text=None, pos=None): |
|
420 | 418 | """Complete the given text. |
|
421 | 419 | |
|
422 | 420 | :Parameters: |
|
423 | 421 | |
|
424 | 422 | text : str |
|
425 | 423 | Text fragment to be completed on. Typically this is |
|
426 | 424 | """ |
|
427 | 425 | # fixme: implement |
|
428 | 426 | raise NotImplementedError |
|
429 | 427 | |
|
430 | 428 | def push(self, ns): |
|
431 | 429 | """ Put value into the namespace with name key. |
|
432 | 430 | |
|
433 | 431 | Parameters |
|
434 | 432 | ---------- |
|
435 | 433 | **kwds |
|
436 | 434 | """ |
|
437 | 435 | |
|
438 | 436 | self.user_ns.update(ns) |
|
439 | 437 | |
|
440 | 438 | def push_function(self, ns): |
|
441 | 439 | # First set the func_globals for all functions to self.user_ns |
|
442 | 440 | new_kwds = {} |
|
443 | 441 | for k, v in ns.iteritems(): |
|
444 | 442 | if not isinstance(v, FunctionType): |
|
445 | 443 | raise TypeError("function object expected") |
|
446 | 444 | new_kwds[k] = FunctionType(v.func_code, self.user_ns) |
|
447 | 445 | self.user_ns.update(new_kwds) |
|
448 | 446 | |
|
449 | 447 | def pack_exception(self,message,exc): |
|
450 | 448 | message['exception'] = exc.__class__ |
|
451 | 449 | message['exception_value'] = \ |
|
452 | 450 | traceback.format_exception_only(exc.__class__, exc) |
|
453 | 451 | |
|
454 | 452 | def feed_block(self, source, filename='<input>', symbol='single'): |
|
455 | 453 | """Compile some source in the interpreter. |
|
456 | 454 | |
|
457 | 455 | One several things can happen: |
|
458 | 456 | |
|
459 | 457 | 1) The input is incorrect; compile_command() raised an |
|
460 | 458 | exception (SyntaxError or OverflowError). |
|
461 | 459 | |
|
462 | 460 | 2) The input is incomplete, and more input is required; |
|
463 | 461 | compile_command() returned None. Nothing happens. |
|
464 | 462 | |
|
465 | 463 | 3) The input is complete; compile_command() returned a code |
|
466 | 464 | object. The code is executed by calling self.runcode() (which |
|
467 | 465 | also handles run-time exceptions, except for SystemExit). |
|
468 | 466 | |
|
469 | 467 | The return value is: |
|
470 | 468 | |
|
471 | 469 | - True in case 2 |
|
472 | 470 | |
|
473 | 471 | - False in the other cases, unless an exception is raised, where |
|
474 | 472 | None is returned instead. This can be used by external callers to |
|
475 | 473 | know whether to continue feeding input or not. |
|
476 | 474 | |
|
477 | 475 | The return value can be used to decide whether to use sys.ps1 or |
|
478 | 476 | sys.ps2 to prompt the next line.""" |
|
479 | 477 | |
|
480 | 478 | self.message = self.setup_message() |
|
481 | 479 | |
|
482 | 480 | try: |
|
483 | 481 | code = self.command_compiler(source,filename,symbol) |
|
484 | 482 | except (OverflowError, SyntaxError, IndentationError, ValueError ), e: |
|
485 | 483 | # Case 1 |
|
486 | 484 | self.traceback_trap.args = sys.exc_info() |
|
487 | 485 | self.pack_exception(self.message,e) |
|
488 | 486 | return COMPILER_ERROR,False |
|
489 | 487 | |
|
490 | 488 | if code is None: |
|
491 | 489 | # Case 2: incomplete input. This means that the input can span |
|
492 | 490 | # multiple lines. But we still need to decide when to actually |
|
493 | 491 | # stop taking user input. Later we'll add auto-indentation support |
|
494 | 492 | # somehow. In the meantime, we'll just stop if there are two lines |
|
495 | 493 | # of pure whitespace at the end. |
|
496 | 494 | last_two = source.rsplit('\n',2)[-2:] |
|
497 | 495 | print 'last two:',last_two # dbg |
|
498 | 496 | if len(last_two)==2 and all(s.isspace() for s in last_two): |
|
499 | 497 | return COMPLETE_INPUT,False |
|
500 | 498 | else: |
|
501 | 499 | return INCOMPLETE_INPUT, True |
|
502 | 500 | else: |
|
503 | 501 | # Case 3 |
|
504 | 502 | return COMPLETE_INPUT, False |
|
505 | 503 | |
|
506 | 504 | def pull(self, keys): |
|
507 | 505 | """ Get an item out of the namespace by key. |
|
508 | 506 | |
|
509 | 507 | Parameters |
|
510 | 508 | ---------- |
|
511 | 509 | key : str |
|
512 | 510 | |
|
513 | 511 | Returns |
|
514 | 512 | ------- |
|
515 | 513 | value : object |
|
516 | 514 | |
|
517 | 515 | Raises |
|
518 | 516 | ------ |
|
519 | 517 | TypeError if the key is not a string. |
|
520 | 518 | NameError if the object doesn't exist. |
|
521 | 519 | """ |
|
522 | 520 | |
|
523 | 521 | if isinstance(keys, str): |
|
524 | 522 | result = self.user_ns.get(keys, NotDefined()) |
|
525 | 523 | if isinstance(result, NotDefined): |
|
526 | 524 | raise NameError('name %s is not defined' % keys) |
|
527 | 525 | elif isinstance(keys, (list, tuple)): |
|
528 | 526 | result = [] |
|
529 | 527 | for key in keys: |
|
530 | 528 | if not isinstance(key, str): |
|
531 | 529 | raise TypeError("objects must be keyed by strings.") |
|
532 | 530 | else: |
|
533 | 531 | r = self.user_ns.get(key, NotDefined()) |
|
534 | 532 | if isinstance(r, NotDefined): |
|
535 | 533 | raise NameError('name %s is not defined' % key) |
|
536 | 534 | else: |
|
537 | 535 | result.append(r) |
|
538 | 536 | if len(keys)==1: |
|
539 | 537 | result = result[0] |
|
540 | 538 | else: |
|
541 | 539 | raise TypeError("keys must be a strong or a list/tuple of strings") |
|
542 | 540 | return result |
|
543 | 541 | |
|
544 | 542 | def pull_function(self, keys): |
|
545 | 543 | return self.pull(keys) |
|
546 | 544 | |
|
547 | 545 | #### Interactive user API ################################################## |
|
548 | 546 | |
|
549 | 547 | def ipsystem(self, command): |
|
550 | 548 | """ Execute a command in a system shell while expanding variables in the |
|
551 | 549 | current namespace. |
|
552 | 550 | |
|
553 | 551 | Parameters |
|
554 | 552 | ---------- |
|
555 | 553 | command : str |
|
556 | 554 | """ |
|
557 | 555 | |
|
558 | 556 | # Expand $variables. |
|
559 | 557 | command = self.var_expand(command) |
|
560 | 558 | |
|
561 | 559 | system_shell(command, |
|
562 | 560 | header='IPython system call: ', |
|
563 | 561 | verbose=self.rc.system_verbose, |
|
564 | 562 | ) |
|
565 | 563 | |
|
566 | 564 | def ipmagic(self, arg_string): |
|
567 | 565 | """ Call a magic function by name. |
|
568 | 566 | |
|
569 | 567 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython |
|
570 | 568 | prompt: |
|
571 | 569 | |
|
572 | 570 | In[1]: %name -opt foo bar |
|
573 | 571 | |
|
574 | 572 | To call a magic without arguments, simply use ipmagic('name'). |
|
575 | 573 | |
|
576 | 574 | This provides a proper Python function to call IPython's magics in any |
|
577 | 575 | valid Python code you can type at the interpreter, including loops and |
|
578 | 576 | compound statements. It is added by IPython to the Python builtin |
|
579 | 577 | namespace upon initialization. |
|
580 | 578 | |
|
581 | 579 | Parameters |
|
582 | 580 | ---------- |
|
583 | 581 | arg_string : str |
|
584 | 582 | A string containing the name of the magic function to call and any |
|
585 | 583 | additional arguments to be passed to the magic. |
|
586 | 584 | |
|
587 | 585 | Returns |
|
588 | 586 | ------- |
|
589 | 587 | something : object |
|
590 | 588 | The return value of the actual object. |
|
591 | 589 | """ |
|
592 | 590 | |
|
593 | 591 | # Taken from IPython. |
|
594 | 592 | raise NotImplementedError('Not ported yet') |
|
595 | 593 | |
|
596 | 594 | args = arg_string.split(' ', 1) |
|
597 | 595 | magic_name = args[0] |
|
598 | 596 | magic_name = magic_name.lstrip(self.config.ESC_MAGIC) |
|
599 | 597 | |
|
600 | 598 | try: |
|
601 | 599 | magic_args = args[1] |
|
602 | 600 | except IndexError: |
|
603 | 601 | magic_args = '' |
|
604 | 602 | fn = getattr(self.magic, 'magic_'+magic_name, None) |
|
605 | 603 | if fn is None: |
|
606 | 604 | self.error("Magic function `%s` not found." % magic_name) |
|
607 | 605 | else: |
|
608 | 606 | magic_args = self.var_expand(magic_args) |
|
609 | 607 | return fn(magic_args) |
|
610 | 608 | |
|
611 | 609 | |
|
612 | 610 | #### Private 'Interpreter' interface ####################################### |
|
613 | 611 | |
|
614 | 612 | def setup_message(self): |
|
615 | 613 | """Return a message object. |
|
616 | 614 | |
|
617 | 615 | This method prepares and returns a message dictionary. This dict |
|
618 | 616 | contains the various fields that are used to transfer information about |
|
619 | 617 | execution, results, tracebacks, etc, to clients (either in or out of |
|
620 | 618 | process ones). Because of the need to work with possibly out of |
|
621 | 619 | process clients, this dict MUST contain strictly pickle-safe values. |
|
622 | 620 | """ |
|
623 | 621 | |
|
624 | 622 | return dict(number=self.current_cell_number) |
|
625 | 623 | |
|
626 | 624 | def setup_namespace(self): |
|
627 | 625 | """ Add things to the namespace. |
|
628 | 626 | """ |
|
629 | 627 | |
|
630 | 628 | self.user_ns.setdefault('__name__', '__main__') |
|
631 | 629 | self.user_ns.setdefault('__builtins__', __builtin__) |
|
632 | 630 | self.user_ns['__IP'] = self |
|
633 | 631 | if self.raw_input_builtin is not None: |
|
634 | 632 | self.user_ns['raw_input'] = self.raw_input_builtin |
|
635 | 633 | if self.input_builtin is not None: |
|
636 | 634 | self.user_ns['input'] = self.input_builtin |
|
637 | 635 | |
|
638 | 636 | builtin_additions = dict( |
|
639 | 637 | ipmagic=self.ipmagic, |
|
640 | 638 | ) |
|
641 | 639 | __builtin__.__dict__.update(builtin_additions) |
|
642 | 640 | |
|
643 | 641 | if self.history is not None: |
|
644 | 642 | self.history.setup_namespace(self.user_ns) |
|
645 | 643 | |
|
646 | 644 | def set_traps(self): |
|
647 | 645 | """ Set all of the output, display, and traceback traps. |
|
648 | 646 | """ |
|
649 | 647 | |
|
650 | 648 | self.output_trap.set() |
|
651 | 649 | self.display_trap.set() |
|
652 | 650 | self.traceback_trap.set() |
|
653 | 651 | |
|
654 | 652 | def unset_traps(self): |
|
655 | 653 | """ Unset all of the output, display, and traceback traps. |
|
656 | 654 | """ |
|
657 | 655 | |
|
658 | 656 | self.output_trap.unset() |
|
659 | 657 | self.display_trap.unset() |
|
660 | 658 | self.traceback_trap.unset() |
|
661 | 659 | |
|
662 | 660 | def split_commands(self, python): |
|
663 | 661 | """ Split multiple lines of code into discrete commands that can be |
|
664 | 662 | executed singly. |
|
665 | 663 | |
|
666 | 664 | Parameters |
|
667 | 665 | ---------- |
|
668 | 666 | python : str |
|
669 | 667 | Pure, exec'able Python code. |
|
670 | 668 | |
|
671 | 669 | Returns |
|
672 | 670 | ------- |
|
673 | 671 | commands : list of str |
|
674 | 672 | Separate commands that can be exec'ed independently. |
|
675 | 673 | """ |
|
676 | 674 | |
|
677 | 675 | # compiler.parse treats trailing spaces after a newline as a |
|
678 | 676 | # SyntaxError. This is different than codeop.CommandCompiler, which |
|
679 | 677 | # will compile the trailng spaces just fine. We simply strip any |
|
680 | 678 | # trailing whitespace off. Passing a string with trailing whitespace |
|
681 | 679 | # to exec will fail however. There seems to be some inconsistency in |
|
682 | 680 | # how trailing whitespace is handled, but this seems to work. |
|
683 | 681 | python = python.strip() |
|
684 | 682 | |
|
685 | 683 | # The compiler module will parse the code into an abstract syntax tree. |
|
686 | 684 | ast = compiler.parse(python) |
|
687 | 685 | |
|
688 | 686 | # Uncomment to help debug the ast tree |
|
689 | 687 | # for n in ast.node: |
|
690 | 688 | # print n.lineno,'->',n |
|
691 | 689 | |
|
692 | 690 | # Each separate command is available by iterating over ast.node. The |
|
693 | 691 | # lineno attribute is the line number (1-indexed) beginning the commands |
|
694 | 692 | # suite. |
|
695 | 693 | # lines ending with ";" yield a Discard Node that doesn't have a lineno |
|
696 | 694 | # attribute. These nodes can and should be discarded. But there are |
|
697 | 695 | # other situations that cause Discard nodes that shouldn't be discarded. |
|
698 | 696 | # We might eventually discover other cases where lineno is None and have |
|
699 | 697 | # to put in a more sophisticated test. |
|
700 | 698 | linenos = [x.lineno-1 for x in ast.node if x.lineno is not None] |
|
701 | 699 | |
|
702 | 700 | # When we finally get the slices, we will need to slice all the way to |
|
703 | 701 | # the end even though we don't have a line number for it. Fortunately, |
|
704 | 702 | # None does the job nicely. |
|
705 | 703 | linenos.append(None) |
|
706 | 704 | lines = python.splitlines() |
|
707 | 705 | |
|
708 | 706 | # Create a list of atomic commands. |
|
709 | 707 | cmds = [] |
|
710 | 708 | for i, j in zip(linenos[:-1], linenos[1:]): |
|
711 | 709 | cmd = lines[i:j] |
|
712 | 710 | if cmd: |
|
713 | 711 | cmds.append('\n'.join(cmd)+'\n') |
|
714 | 712 | |
|
715 | 713 | return cmds |
|
716 | 714 | |
|
717 | 715 | def error(self, text): |
|
718 | 716 | """ Pass an error message back to the shell. |
|
719 | 717 | |
|
720 | 718 | Preconditions |
|
721 | 719 | ------------- |
|
722 | 720 | This should only be called when self.message is set. In other words, |
|
723 | 721 | when code is being executed. |
|
724 | 722 | |
|
725 | 723 | Parameters |
|
726 | 724 | ---------- |
|
727 | 725 | text : str |
|
728 | 726 | """ |
|
729 | 727 | |
|
730 | 728 | errors = self.message.get('IPYTHON_ERROR', []) |
|
731 | 729 | errors.append(text) |
|
732 | 730 | |
|
733 | 731 | def var_expand(self, template): |
|
734 | 732 | """ Expand $variables in the current namespace using Itpl. |
|
735 | 733 | |
|
736 | 734 | Parameters |
|
737 | 735 | ---------- |
|
738 | 736 | template : str |
|
739 | 737 | """ |
|
740 | 738 | |
|
741 | 739 | return str(ItplNS(template, self.user_ns)) |
|
742 | 740 | |
|
743 | 741 | def _possible_macro(self, obj): |
|
744 | 742 | """ If the object is a macro, execute it. |
|
745 | 743 | """ |
|
746 | 744 | |
|
747 | 745 | if isinstance(obj, Macro): |
|
748 | 746 | self.execute_macro(obj) |
|
749 | 747 |
@@ -1,99 +1,107 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | |
|
3 | 3 | """ Trap stdout/stderr.""" |
|
4 | 4 | |
|
5 | 5 | __docformat__ = "restructuredtext en" |
|
6 | 6 | |
|
7 | 7 | #------------------------------------------------------------------------------- |
|
8 | 8 | # Copyright (C) 2008 The IPython Development Team |
|
9 | 9 | # |
|
10 | 10 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | 11 | # the file COPYING, distributed as part of this software. |
|
12 | 12 | #------------------------------------------------------------------------------- |
|
13 | 13 | |
|
14 | 14 | #------------------------------------------------------------------------------- |
|
15 | 15 | # Imports |
|
16 | 16 | #------------------------------------------------------------------------------- |
|
17 | 17 | |
|
18 | 18 | import sys |
|
19 | 19 | from cStringIO import StringIO |
|
20 | 20 | |
|
21 | 21 | |
|
22 | 22 | class OutputTrap(object): |
|
23 | 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 | 27 | # Filelike objects to store stdout/stderr text. |
|
28 | self.out = StringIO() | |
|
29 |
self. |
|
|
28 | if out is None: | |
|
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 | 37 | # Boolean to check if the stdout/stderr hook is set. |
|
32 | 38 | self.out_set = False |
|
33 | 39 | self.err_set = False |
|
34 | 40 | |
|
35 | 41 | @property |
|
36 | 42 | def out_text(self): |
|
37 | 43 | """ Return the text currently in the stdout buffer. |
|
38 | 44 | """ |
|
39 | 45 | return self.out.getvalue() |
|
40 | 46 | |
|
41 | 47 | @property |
|
42 | 48 | def err_text(self): |
|
43 | 49 | """ Return the text currently in the stderr buffer. |
|
44 | 50 | """ |
|
45 | 51 | return self.err.getvalue() |
|
46 | 52 | |
|
47 | 53 | def set(self): |
|
48 | 54 | """ Set the hooks. |
|
49 | 55 | """ |
|
50 | 56 | |
|
51 | 57 | if sys.stdout is not self.out: |
|
52 | 58 | self._out_save = sys.stdout |
|
53 | 59 | sys.stdout = self.out |
|
54 | 60 | self.out_set = True |
|
55 | 61 | |
|
56 | 62 | if sys.stderr is not self.err: |
|
57 | 63 | self._err_save = sys.stderr |
|
58 | 64 | sys.stderr = self.err |
|
59 | 65 | self.err_set = True |
|
60 | 66 | |
|
61 | 67 | def unset(self): |
|
62 | 68 | """ Remove the hooks. |
|
63 | 69 | """ |
|
64 | 70 | |
|
65 |
|
|
|
71 | if self.out_set: | |
|
72 | sys.stdout = self._out_save | |
|
66 | 73 | self.out_set = False |
|
67 | 74 | |
|
68 |
|
|
|
75 | if self.err_set: | |
|
76 | sys.stderr = self._err_save | |
|
69 | 77 | self.err_set = False |
|
70 | 78 | |
|
71 | 79 | def clear(self): |
|
72 | 80 | """ Clear out the buffers. |
|
73 | 81 | """ |
|
74 | 82 | |
|
75 |
self.out. |
|
|
76 |
self.out |
|
|
83 | self.out.reset() | |
|
84 | self.out.truncate() | |
|
77 | 85 | |
|
78 |
self.err. |
|
|
79 |
self.err |
|
|
86 | self.err.reset() | |
|
87 | self.err.truncate() | |
|
80 | 88 | |
|
81 | 89 | def add_to_message(self, message): |
|
82 | 90 | """ Add the text from stdout and stderr to the message from the |
|
83 | 91 | interpreter to its listeners. |
|
84 | 92 | |
|
85 | 93 | Parameters |
|
86 | 94 | ---------- |
|
87 | 95 | message : dict |
|
88 | 96 | """ |
|
89 | 97 | |
|
90 | 98 | out_text = self.out_text |
|
91 | 99 | if out_text: |
|
92 | 100 | message['stdout'] = out_text |
|
93 | 101 | |
|
94 | 102 | err_text = self.err_text |
|
95 | 103 | if err_text: |
|
96 | 104 | message['stderr'] = err_text |
|
97 | 105 | |
|
98 | 106 | |
|
99 | 107 |
@@ -1,83 +1,85 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | |
|
3 | 3 | """Object to manage sys.excepthook().""" |
|
4 | 4 | |
|
5 | 5 | __docformat__ = "restructuredtext en" |
|
6 | 6 | |
|
7 | 7 | #------------------------------------------------------------------------------- |
|
8 | 8 | # Copyright (C) 2008 The IPython Development Team |
|
9 | 9 | # |
|
10 | 10 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | 11 | # the file COPYING, distributed as part of this software. |
|
12 | 12 | #------------------------------------------------------------------------------- |
|
13 | 13 | |
|
14 | 14 | #------------------------------------------------------------------------------- |
|
15 | 15 | # Imports |
|
16 | 16 | #------------------------------------------------------------------------------- |
|
17 | ||
|
18 | 17 | import sys |
|
19 | ||
|
18 | from traceback import format_list | |
|
20 | 19 | |
|
21 | 20 | class TracebackTrap(object): |
|
22 | 21 | """ Object to trap and format tracebacks. |
|
23 | 22 | """ |
|
24 | 23 | |
|
25 | 24 | def __init__(self, formatters=None): |
|
26 | 25 | # A list of formatters to apply. |
|
27 | 26 | if formatters is None: |
|
28 | 27 | formatters = [] |
|
29 | 28 | self.formatters = formatters |
|
30 | 29 | |
|
31 | 30 | # All of the traceback information provided to sys.excepthook(). |
|
32 | 31 | self.args = None |
|
33 | 32 | |
|
34 | 33 | # The previous hook before we replace it. |
|
35 | 34 | self.old_hook = None |
|
36 | 35 | |
|
37 | 36 | |
|
38 | 37 | def hook(self, *args): |
|
39 | 38 | """ This method actually implements the hook. |
|
40 | 39 | """ |
|
41 | ||
|
42 | 40 | self.args = args |
|
43 | 41 | |
|
44 | 42 | def set(self): |
|
45 | 43 | """ Set the hook. |
|
46 | 44 | """ |
|
47 | 45 | |
|
48 | 46 | if sys.excepthook is not self.hook: |
|
49 | 47 | self.old_hook = sys.excepthook |
|
50 | 48 | sys.excepthook = self.hook |
|
51 | 49 | |
|
52 | 50 | def unset(self): |
|
53 | 51 | """ Unset the hook. |
|
54 | 52 | """ |
|
55 | 53 | |
|
56 | 54 | sys.excepthook = self.old_hook |
|
57 | 55 | |
|
58 | 56 | def clear(self): |
|
59 | 57 | """ Remove the stored traceback. |
|
60 | 58 | """ |
|
61 | 59 | |
|
62 | 60 | self.args = None |
|
63 | 61 | |
|
64 | 62 | def add_to_message(self, message): |
|
65 | 63 | """ Add the formatted display of the traceback to the message dictionary |
|
66 | 64 | being returned from the interpreter to its listeners. |
|
67 | 65 | |
|
68 | 66 | Parameters |
|
69 | 67 | ---------- |
|
70 | 68 | message : dict |
|
71 | 69 | """ |
|
72 | 70 | |
|
73 | 71 | # If there was no traceback, then don't add anything. |
|
74 | 72 | if self.args is None: |
|
75 | 73 | return |
|
76 | 74 | |
|
77 | 75 | # Go through the list of formatters and let them add their formatting. |
|
78 | 76 | traceback = {} |
|
79 | for formatter in self.formatters: | |
|
80 | traceback[formatter.identifier] = formatter(*self.args) | |
|
81 | ||
|
77 | try: | |
|
78 | for formatter in self.formatters: | |
|
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 | 84 | message['traceback'] = traceback |
|
83 | 85 |
@@ -1,133 +1,135 b'' | |||
|
1 | 1 | """Decorators for labeling test objects. |
|
2 | 2 | |
|
3 | 3 | Decorators that merely return a modified version of the original |
|
4 | 4 | function object are straightforward. Decorators that return a new |
|
5 | 5 | function object need to use |
|
6 | 6 | nose.tools.make_decorator(original_function)(decorator) in returning |
|
7 | 7 | the decorator, in order to preserve metadata such as function name, |
|
8 | 8 | setup and teardown functions and so on - see nose.tools for more |
|
9 | 9 | information. |
|
10 | 10 | |
|
11 | 11 | NOTE: This file contains IPython-specific decorators and imports the |
|
12 | 12 | numpy.testing.decorators file, which we've copied verbatim. Any of our own |
|
13 | 13 | code will be added at the bottom if we end up extending this. |
|
14 | 14 | """ |
|
15 | 15 | |
|
16 | 16 | # Stdlib imports |
|
17 | 17 | import inspect |
|
18 | 18 | |
|
19 | 19 | # Third-party imports |
|
20 | 20 | |
|
21 | 21 | # This is Michele Simionato's decorator module, also kept verbatim. |
|
22 | 22 | from decorator_msim import decorator, update_wrapper |
|
23 | 23 | |
|
24 | 24 | # Grab the numpy-specific decorators which we keep in a file that we |
|
25 | 25 | # occasionally update from upstream: decorators_numpy.py is an IDENTICAL copy |
|
26 | 26 | # of numpy.testing.decorators. |
|
27 | 27 | from decorators_numpy import * |
|
28 | 28 | |
|
29 | 29 | ############################################################################## |
|
30 | 30 | # Local code begins |
|
31 | 31 | |
|
32 | 32 | # Utility functions |
|
33 | 33 | |
|
34 | 34 | def apply_wrapper(wrapper,func): |
|
35 | 35 | """Apply a wrapper to a function for decoration. |
|
36 | 36 | |
|
37 | 37 | This mixes Michele Simionato's decorator tool with nose's make_decorator, |
|
38 | 38 | to apply a wrapper in a decorator so that all nose attributes, as well as |
|
39 | 39 | function signature and other properties, survive the decoration cleanly. |
|
40 | 40 | This will ensure that wrapped functions can still be well introspected via |
|
41 | 41 | IPython, for example. |
|
42 | 42 | """ |
|
43 | 43 | import nose.tools |
|
44 | 44 | |
|
45 | 45 | return decorator(wrapper,nose.tools.make_decorator(func)(wrapper)) |
|
46 | 46 | |
|
47 | 47 | |
|
48 | 48 | def make_label_dec(label,ds=None): |
|
49 | 49 | """Factory function to create a decorator that applies one or more labels. |
|
50 | 50 | |
|
51 | 51 | :Parameters: |
|
52 | 52 | label : string or sequence |
|
53 | 53 | One or more labels that will be applied by the decorator to the functions |
|
54 | 54 | it decorates. Labels are attributes of the decorated function with their |
|
55 | 55 | value set to True. |
|
56 | 56 | |
|
57 | 57 | :Keywords: |
|
58 | 58 | ds : string |
|
59 | 59 | An optional docstring for the resulting decorator. If not given, a |
|
60 | 60 | default docstring is auto-generated. |
|
61 | 61 | |
|
62 | 62 | :Returns: |
|
63 | 63 | A decorator. |
|
64 | 64 | |
|
65 | 65 | :Examples: |
|
66 | 66 | |
|
67 | 67 | A simple labeling decorator: |
|
68 | 68 | >>> slow = make_label_dec('slow') |
|
69 | 69 | >>> print slow.__doc__ |
|
70 | 70 | Labels a test as 'slow'. |
|
71 | 71 | |
|
72 | 72 | And one that uses multiple labels and a custom docstring: |
|
73 | 73 | >>> rare = make_label_dec(['slow','hard'], |
|
74 | 74 | ... "Mix labels 'slow' and 'hard' for rare tests.") |
|
75 | 75 | >>> print rare.__doc__ |
|
76 | 76 | Mix labels 'slow' and 'hard' for rare tests. |
|
77 | 77 | |
|
78 | 78 | Now, let's test using this one: |
|
79 | 79 | >>> @rare |
|
80 | 80 | ... def f(): pass |
|
81 | 81 | ... |
|
82 | 82 | >>> |
|
83 | 83 | >>> f.slow |
|
84 | 84 | True |
|
85 | 85 | >>> f.hard |
|
86 | 86 | True |
|
87 | 87 | """ |
|
88 | 88 | |
|
89 | 89 | if isinstance(label,basestring): |
|
90 | 90 | labels = [label] |
|
91 | 91 | else: |
|
92 | 92 | labels = label |
|
93 | 93 | |
|
94 | 94 | # Validate that the given label(s) are OK for use in setattr() by doing a |
|
95 | 95 | # dry run on a dummy function. |
|
96 | 96 | tmp = lambda : None |
|
97 | 97 | for label in labels: |
|
98 | 98 | setattr(tmp,label,True) |
|
99 | 99 | |
|
100 | 100 | # This is the actual decorator we'll return |
|
101 | 101 | def decor(f): |
|
102 | 102 | for label in labels: |
|
103 | 103 | setattr(f,label,True) |
|
104 | 104 | return f |
|
105 | 105 | |
|
106 | 106 | # Apply the user's docstring, or autogenerate a basic one |
|
107 | 107 | if ds is None: |
|
108 | 108 | ds = "Labels a test as %r." % label |
|
109 | 109 | decor.__doc__ = ds |
|
110 | 110 | |
|
111 | 111 | return decor |
|
112 | 112 | |
|
113 | 113 | #----------------------------------------------------------------------------- |
|
114 | 114 | # Decorators for public use |
|
115 | 115 | |
|
116 | 116 | skip_doctest = make_label_dec('skip_doctest', |
|
117 | 117 | """Decorator - mark a function or method for skipping its doctest. |
|
118 | 118 | |
|
119 | 119 | This decorator allows you to mark a function whose docstring you wish to |
|
120 | 120 | omit from testing, while preserving the docstring for introspection, help, |
|
121 | 121 | etc.""") |
|
122 | 122 | |
|
123 | 123 | |
|
124 | 124 | def skip(func): |
|
125 | 125 | """Decorator - mark a test function for skipping from test suite.""" |
|
126 | 126 | |
|
127 | 127 | import nose |
|
128 | 128 | |
|
129 | 129 | def wrapper(*a,**k): |
|
130 | 130 | raise nose.SkipTest("Skipping test for function: %s" % |
|
131 | 131 | func.__name__) |
|
132 | 132 | |
|
133 | 133 | return apply_wrapper(wrapper,func) |
|
134 | ||
|
135 |
@@ -1,66 +1,66 b'' | |||
|
1 | 1 | # Set this prefix to where you want to install the plugin |
|
2 | 2 | PREFIX=~/usr/local |
|
3 | 3 | PREFIX=~/tmp/local |
|
4 | 4 | |
|
5 | NOSE0=nosetests -vs --with-doctest --doctest-tests | |
|
6 | NOSE=nosetests -vvs --with-ipdoctest --doctest-tests --doctest-extension=txt | |
|
5 | NOSE0=nosetests -vs --with-doctest --doctest-tests --detailed-errors | |
|
6 | NOSE=nosetests -vvs --with-ipdoctest --doctest-tests --doctest-extension=txt --detailed-errors | |
|
7 | 7 | |
|
8 | 8 | SRC=ipdoctest.py setup.py ../decorators.py |
|
9 | 9 | |
|
10 | 10 | # Default target for clean 'make' |
|
11 | 11 | default: iplib |
|
12 | 12 | |
|
13 | 13 | # The actual plugin installation |
|
14 | 14 | plugin: IPython_doctest_plugin.egg-info |
|
15 | 15 | |
|
16 | 16 | # Simple targets that test one thing |
|
17 | 17 | simple: plugin simple.py |
|
18 | 18 | $(NOSE) simple.py |
|
19 | 19 | |
|
20 | 20 | dtest: plugin dtexample.py |
|
21 | 21 | $(NOSE) dtexample.py |
|
22 | 22 | |
|
23 | 23 | rtest: plugin test_refs.py |
|
24 | 24 | $(NOSE) test_refs.py |
|
25 | 25 | |
|
26 | 26 | test: plugin dtexample.py |
|
27 | 27 | $(NOSE) dtexample.py test*.py test*.txt |
|
28 | 28 | |
|
29 | 29 | deb: plugin dtexample.py |
|
30 | 30 | $(NOSE) test_combo.txt |
|
31 | 31 | |
|
32 | 32 | # IPython tests |
|
33 | 33 | deco: |
|
34 | 34 | $(NOSE0) -x IPython.testing.decorators |
|
35 | 35 | |
|
36 | 36 | magic: plugin |
|
37 | 37 | $(NOSE) -x IPython.Magic |
|
38 | 38 | |
|
39 | 39 | ipipe: plugin |
|
40 | 40 | $(NOSE) -x IPython.Extensions.ipipe |
|
41 | 41 | |
|
42 | 42 | iplib: plugin |
|
43 | 43 | $(NOSE) -x IPython.iplib |
|
44 | 44 | |
|
45 | 45 | strd: plugin |
|
46 | 46 | nosetests -vs --with-doctest --doctest-tests IPython.strdispatch |
|
47 | 47 | $(NOSE) IPython.strdispatch |
|
48 | 48 | |
|
49 | 49 | # All of ipython itself |
|
50 | 50 | ipython: plugin |
|
51 | 51 | $(NOSE) IPython |
|
52 | 52 | |
|
53 | 53 | # Combined targets |
|
54 | 54 | sr: rtest strd |
|
55 | 55 | |
|
56 | 56 | base: dtest rtest test strd deco |
|
57 | 57 | |
|
58 | 58 | all: base ipython |
|
59 | 59 | |
|
60 | 60 | # Main plugin and cleanup |
|
61 | 61 | IPython_doctest_plugin.egg-info: $(SRC) |
|
62 | 62 | python setup.py install --prefix=$(PREFIX) |
|
63 | 63 | touch $@ |
|
64 | 64 | |
|
65 | 65 | clean: |
|
66 | 66 | rm -rf IPython_doctest_plugin.egg-info *~ *pyc build/ dist/ |
@@ -1,174 +1,175 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # -*- coding: utf-8 -*- |
|
3 | 3 | """Setup script for IPython. |
|
4 | 4 | |
|
5 | 5 | Under Posix environments it works like a typical setup.py script. |
|
6 | 6 | Under Windows, the command sdist is not supported, since IPython |
|
7 | 7 | requires utilities which are not available under Windows.""" |
|
8 | 8 | |
|
9 | 9 | #------------------------------------------------------------------------------- |
|
10 | 10 | # Copyright (C) 2008 The IPython Development Team |
|
11 | 11 | # |
|
12 | 12 | # Distributed under the terms of the BSD License. The full license is in |
|
13 | 13 | # the file COPYING, distributed as part of this software. |
|
14 | 14 | #------------------------------------------------------------------------------- |
|
15 | 15 | |
|
16 | 16 | #------------------------------------------------------------------------------- |
|
17 | 17 | # Imports |
|
18 | 18 | #------------------------------------------------------------------------------- |
|
19 | 19 | |
|
20 | 20 | # Stdlib imports |
|
21 | 21 | import os |
|
22 | 22 | import sys |
|
23 | 23 | |
|
24 | 24 | from glob import glob |
|
25 | 25 | |
|
26 | 26 | # BEFORE importing distutils, remove MANIFEST. distutils doesn't properly |
|
27 | 27 | # update it when the contents of directories change. |
|
28 | 28 | if os.path.exists('MANIFEST'): os.remove('MANIFEST') |
|
29 | 29 | |
|
30 | 30 | from distutils.core import setup |
|
31 | 31 | |
|
32 | 32 | # Local imports |
|
33 | 33 | from IPython.genutils import target_update |
|
34 | 34 | |
|
35 | 35 | from setupbase import ( |
|
36 | 36 | setup_args, |
|
37 | 37 | find_packages, |
|
38 | 38 | find_package_data, |
|
39 | 39 | find_scripts, |
|
40 | 40 | find_data_files, |
|
41 | 41 | check_for_dependencies |
|
42 | 42 | ) |
|
43 | 43 | |
|
44 | 44 | isfile = os.path.isfile |
|
45 | 45 | |
|
46 | 46 | #------------------------------------------------------------------------------- |
|
47 | 47 | # Handle OS specific things |
|
48 | 48 | #------------------------------------------------------------------------------- |
|
49 | 49 | |
|
50 | 50 | if os.name == 'posix': |
|
51 | 51 | os_name = 'posix' |
|
52 | 52 | elif os.name in ['nt','dos']: |
|
53 | 53 | os_name = 'windows' |
|
54 | 54 | else: |
|
55 | 55 | print 'Unsupported operating system:',os.name |
|
56 | 56 | sys.exit(1) |
|
57 | 57 | |
|
58 | 58 | # Under Windows, 'sdist' has not been supported. Now that the docs build with |
|
59 | 59 | # Sphinx it might work, but let's not turn it on until someone confirms that it |
|
60 | 60 | # actually works. |
|
61 | 61 | if os_name == 'windows' and 'sdist' in sys.argv: |
|
62 | 62 | print 'The sdist command is not available under Windows. Exiting.' |
|
63 | 63 | sys.exit(1) |
|
64 | 64 | |
|
65 | 65 | #------------------------------------------------------------------------------- |
|
66 | 66 | # Things related to the IPython documentation |
|
67 | 67 | #------------------------------------------------------------------------------- |
|
68 | 68 | |
|
69 | 69 | # update the manuals when building a source dist |
|
70 | 70 | if len(sys.argv) >= 2 and sys.argv[1] in ('sdist','bdist_rpm'): |
|
71 | 71 | import textwrap |
|
72 | 72 | |
|
73 | 73 | # List of things to be updated. Each entry is a triplet of args for |
|
74 | 74 | # target_update() |
|
75 | 75 | to_update = [ |
|
76 | 76 | # FIXME - Disabled for now: we need to redo an automatic way |
|
77 | 77 | # of generating the magic info inside the rst. |
|
78 | 78 | #('doc/magic.tex', |
|
79 | 79 | #['IPython/Magic.py'], |
|
80 | 80 | #"cd doc && ./update_magic.sh" ), |
|
81 | 81 | |
|
82 | 82 | ('doc/ipython.1.gz', |
|
83 | 83 | ['doc/ipython.1'], |
|
84 | 84 | "cd doc && gzip -9c ipython.1 > ipython.1.gz"), |
|
85 | 85 | |
|
86 | 86 | ('doc/pycolor.1.gz', |
|
87 | 87 | ['doc/pycolor.1'], |
|
88 | 88 | "cd doc && gzip -9c pycolor.1 > pycolor.1.gz"), |
|
89 | 89 | ] |
|
90 | 90 | |
|
91 | 91 | # Only build the docs is sphinx is present |
|
92 | 92 | try: |
|
93 | 93 | import sphinx |
|
94 | 94 | except ImportError: |
|
95 | 95 | pass |
|
96 | 96 | else: |
|
97 | 97 | pass |
|
98 | 98 | # BEG: This is disabled as I am not sure what to depend on. |
|
99 | 99 | # I actually don't think we should be automatically building |
|
100 | 100 | # the docs for people. |
|
101 | 101 | # The do_sphinx scripts builds html and pdf, so just one |
|
102 | 102 | # target is enough to cover all manual generation |
|
103 | 103 | # to_update.append( |
|
104 | 104 | # ('doc/manual/ipython.pdf', |
|
105 | 105 | # ['IPython/Release.py','doc/source/ipython.rst'], |
|
106 | 106 | # "cd docs && python do_sphinx.py") |
|
107 | 107 | # ) |
|
108 | 108 | [ target_update(*t) for t in to_update ] |
|
109 | 109 | |
|
110 | 110 | #--------------------------------------------------------------------------- |
|
111 | 111 | # Find all the packages, package data, scripts and data_files |
|
112 | 112 | #--------------------------------------------------------------------------- |
|
113 | 113 | |
|
114 | 114 | packages = find_packages() |
|
115 | 115 | package_data = find_package_data() |
|
116 | 116 | scripts = find_scripts() |
|
117 | 117 | data_files = find_data_files() |
|
118 | 118 | |
|
119 | 119 | #--------------------------------------------------------------------------- |
|
120 | 120 | # Handle dependencies and setuptools specific things |
|
121 | 121 | #--------------------------------------------------------------------------- |
|
122 | 122 | |
|
123 | 123 | # This dict is used for passing extra arguments that are setuptools |
|
124 | 124 | # specific to setup |
|
125 | 125 | setuptools_extra_args = {} |
|
126 | 126 | |
|
127 | 127 | if 'setuptools' in sys.modules: |
|
128 | 128 | setuptools_extra_args['zip_safe'] = False |
|
129 | 129 | setuptools_extra_args['entry_points'] = { |
|
130 | 130 | 'console_scripts': [ |
|
131 | 131 | 'ipython = IPython.ipapi:launch_new_instance', |
|
132 | 132 | 'pycolor = IPython.PyColorize:main', |
|
133 | 133 | 'ipcontroller = IPython.kernel.scripts.ipcontroller:main', |
|
134 | 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 | 139 | setup_args["extras_require"] = dict( |
|
139 | 140 | kernel = [ |
|
140 | 141 | "zope.interface>=3.4.1", |
|
141 | 142 | "Twisted>=8.0.1", |
|
142 | 143 | "foolscap>=0.2.6" |
|
143 | 144 | ], |
|
144 | 145 | doc=['Sphinx>=0.3','pygments'], |
|
145 | 146 | test='nose>=0.10.1', |
|
146 | 147 | security=["pyOpenSSL>=0.6"] |
|
147 | 148 | ) |
|
148 | 149 | # Allow setuptools to handle the scripts |
|
149 | 150 | scripts = [] |
|
150 | 151 | # eggs will lack docs, examples |
|
151 | 152 | data_files = [] |
|
152 | 153 | else: |
|
153 | 154 | # package_data of setuptools was introduced to distutils in 2.4 |
|
154 | 155 | cfgfiles = filter(isfile, glob('IPython/UserConfig/*')) |
|
155 | 156 | if sys.version_info < (2,4): |
|
156 | 157 | data_files.append(('lib', 'IPython/UserConfig', cfgfiles)) |
|
157 | 158 | # If we are running without setuptools, call this function which will |
|
158 | 159 | # check for dependencies an inform the user what is needed. This is |
|
159 | 160 | # just to make life easy for users. |
|
160 | 161 | check_for_dependencies() |
|
161 | 162 | |
|
162 | 163 | |
|
163 | 164 | #--------------------------------------------------------------------------- |
|
164 | 165 | # Do the actual setup now |
|
165 | 166 | #--------------------------------------------------------------------------- |
|
166 | 167 | |
|
167 | 168 | setup_args['packages'] = packages |
|
168 | 169 | setup_args['package_data'] = package_data |
|
169 | 170 | setup_args['scripts'] = scripts |
|
170 | 171 | setup_args['data_files'] = data_files |
|
171 | 172 | setup_args.update(setuptools_extra_args) |
|
172 | 173 | |
|
173 | 174 | if __name__ == '__main__': |
|
174 | 175 | setup(**setup_args) |
@@ -1,232 +1,237 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | |
|
3 | 3 | """ |
|
4 | 4 | This module defines the things that are used in setup.py for building IPython |
|
5 | 5 | |
|
6 | 6 | This includes: |
|
7 | 7 | |
|
8 | 8 | * The basic arguments to setup |
|
9 | 9 | * Functions for finding things like packages, package data, etc. |
|
10 | 10 | * A function for checking dependencies. |
|
11 | 11 | """ |
|
12 | 12 | |
|
13 | 13 | __docformat__ = "restructuredtext en" |
|
14 | 14 | |
|
15 | 15 | #------------------------------------------------------------------------------- |
|
16 | 16 | # Copyright (C) 2008 The IPython Development Team |
|
17 | 17 | # |
|
18 | 18 | # Distributed under the terms of the BSD License. The full license is in |
|
19 | 19 | # the file COPYING, distributed as part of this software. |
|
20 | 20 | #------------------------------------------------------------------------------- |
|
21 | 21 | |
|
22 | 22 | #------------------------------------------------------------------------------- |
|
23 | 23 | # Imports |
|
24 | 24 | #------------------------------------------------------------------------------- |
|
25 | 25 | |
|
26 | 26 | import os, sys |
|
27 | 27 | |
|
28 | 28 | from glob import glob |
|
29 | 29 | |
|
30 | 30 | from setupext import install_data_ext |
|
31 | 31 | |
|
32 | 32 | #------------------------------------------------------------------------------- |
|
33 | 33 | # Useful globals and utility functions |
|
34 | 34 | #------------------------------------------------------------------------------- |
|
35 | 35 | |
|
36 | 36 | # A few handy globals |
|
37 | 37 | isfile = os.path.isfile |
|
38 | 38 | pjoin = os.path.join |
|
39 | 39 | |
|
40 | 40 | def oscmd(s): |
|
41 | 41 | print ">", s |
|
42 | 42 | os.system(s) |
|
43 | 43 | |
|
44 | 44 | # A little utility we'll need below, since glob() does NOT allow you to do |
|
45 | 45 | # exclusion on multiple endings! |
|
46 | 46 | def file_doesnt_endwith(test,endings): |
|
47 | 47 | """Return true if test is a file and its name does NOT end with any |
|
48 | 48 | of the strings listed in endings.""" |
|
49 | 49 | if not isfile(test): |
|
50 | 50 | return False |
|
51 | 51 | for e in endings: |
|
52 | 52 | if test.endswith(e): |
|
53 | 53 | return False |
|
54 | 54 | return True |
|
55 | 55 | |
|
56 | 56 | #--------------------------------------------------------------------------- |
|
57 | 57 | # Basic project information |
|
58 | 58 | #--------------------------------------------------------------------------- |
|
59 | 59 | |
|
60 | 60 | # Release.py contains version, authors, license, url, keywords, etc. |
|
61 | 61 | execfile(pjoin('IPython','Release.py')) |
|
62 | 62 | |
|
63 | 63 | # Create a dict with the basic information |
|
64 | 64 | # This dict is eventually passed to setup after additional keys are added. |
|
65 | 65 | setup_args = dict( |
|
66 | 66 | name = name, |
|
67 | 67 | version = version, |
|
68 | 68 | description = description, |
|
69 | 69 | long_description = long_description, |
|
70 | 70 | author = author, |
|
71 | 71 | author_email = author_email, |
|
72 | 72 | url = url, |
|
73 | 73 | download_url = download_url, |
|
74 | 74 | license = license, |
|
75 | 75 | platforms = platforms, |
|
76 | 76 | keywords = keywords, |
|
77 | 77 | cmdclass = {'install_data': install_data_ext}, |
|
78 | 78 | ) |
|
79 | 79 | |
|
80 | 80 | |
|
81 | 81 | #--------------------------------------------------------------------------- |
|
82 | 82 | # Find packages |
|
83 | 83 | #--------------------------------------------------------------------------- |
|
84 | 84 | |
|
85 | 85 | def add_package(packages, pname, config=False, tests=False, scripts=False, others=None): |
|
86 | 86 | """ |
|
87 | 87 | Add a package to the list of packages, including certain subpackages. |
|
88 | 88 | """ |
|
89 | 89 | packages.append('.'.join(['IPython',pname])) |
|
90 | 90 | if config: |
|
91 | 91 | packages.append('.'.join(['IPython',pname,'config'])) |
|
92 | 92 | if tests: |
|
93 | 93 | packages.append('.'.join(['IPython',pname,'tests'])) |
|
94 | 94 | if scripts: |
|
95 | 95 | packages.append('.'.join(['IPython',pname,'scripts'])) |
|
96 | 96 | if others is not None: |
|
97 | 97 | for o in others: |
|
98 | 98 | packages.append('.'.join(['IPython',pname,o])) |
|
99 | 99 | |
|
100 | 100 | def find_packages(): |
|
101 | 101 | """ |
|
102 | 102 | Find all of IPython's packages. |
|
103 | 103 | """ |
|
104 | 104 | packages = ['IPython'] |
|
105 | 105 | add_package(packages, 'config', tests=True) |
|
106 | 106 | add_package(packages , 'Extensions') |
|
107 | 107 | add_package(packages, 'external') |
|
108 | 108 | add_package(packages, 'gui') |
|
109 | 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 | 114 | add_package(packages, 'kernel', config=True, tests=True, scripts=True) |
|
111 | 115 | add_package(packages, 'kernel.core', config=True, tests=True) |
|
112 | 116 | add_package(packages, 'testing', tests=True) |
|
113 | 117 | add_package(packages, 'tools', tests=True) |
|
114 | 118 | add_package(packages, 'UserConfig') |
|
115 | 119 | return packages |
|
116 | 120 | |
|
117 | 121 | #--------------------------------------------------------------------------- |
|
118 | 122 | # Find package data |
|
119 | 123 | #--------------------------------------------------------------------------- |
|
120 | 124 | |
|
121 | 125 | def find_package_data(): |
|
122 | 126 | """ |
|
123 | 127 | Find IPython's package_data. |
|
124 | 128 | """ |
|
125 | 129 | # This is not enough for these things to appear in an sdist. |
|
126 | 130 | # We need to muck with the MANIFEST to get this to work |
|
127 | 131 | package_data = { |
|
128 | 132 | 'IPython.UserConfig' : ['*'], |
|
129 | 133 | 'IPython.tools.tests' : ['*.txt'], |
|
130 | 134 | 'IPython.testing' : ['*.txt'] |
|
131 | 135 | } |
|
132 | 136 | return package_data |
|
133 | 137 | |
|
134 | 138 | |
|
135 | 139 | #--------------------------------------------------------------------------- |
|
136 | 140 | # Find data files |
|
137 | 141 | #--------------------------------------------------------------------------- |
|
138 | 142 | |
|
139 | 143 | def find_data_files(): |
|
140 | 144 | """ |
|
141 | 145 | Find IPython's data_files. |
|
142 | 146 | """ |
|
143 | 147 | |
|
144 | 148 | # I can't find how to make distutils create a nested dir. structure, so |
|
145 | 149 | # in the meantime do it manually. Butt ugly. |
|
146 | 150 | # Note that http://www.redbrick.dcu.ie/~noel/distutils.html, ex. 2/3, contain |
|
147 | 151 | # information on how to do this more cleanly once python 2.4 can be assumed. |
|
148 | 152 | # Thanks to Noel for the tip. |
|
149 | 153 | docdirbase = 'share/doc/ipython' |
|
150 | 154 | manpagebase = 'share/man/man1' |
|
151 | 155 | |
|
152 | 156 | # We only need to exclude from this things NOT already excluded in the |
|
153 | 157 | # MANIFEST.in file. |
|
154 | 158 | exclude = ('.sh','.1.gz') |
|
155 | 159 | # We need to figure out how we want to package all of our rst docs? |
|
156 | 160 | # docfiles = filter(lambda f:file_doesnt_endwith(f,exclude),glob('docs/*')) |
|
157 | 161 | examfiles = filter(isfile, glob('docs/examples/core/*.py')) |
|
158 | 162 | examfiles.append(filter(isfile, glob('docs/examples/kernel/*.py'))) |
|
159 | 163 | manpages = filter(isfile, glob('docs/man/*.1.gz')) |
|
160 | 164 | igridhelpfiles = filter(isfile, glob('IPython/Extensions/igrid_help.*')) |
|
161 | 165 | |
|
162 | 166 | data_files = [#('data', docdirbase, docfiles), |
|
163 | 167 | ('data', pjoin(docdirbase, 'examples'),examfiles), |
|
164 | 168 | ('data', manpagebase, manpages), |
|
165 | 169 | ('data',pjoin(docdirbase, 'extensions'),igridhelpfiles), |
|
166 | 170 | ] |
|
167 | 171 | # import pprint |
|
168 | 172 | # pprint.pprint(data_files) |
|
169 | 173 | return [] |
|
170 | 174 | |
|
171 | 175 | #--------------------------------------------------------------------------- |
|
172 | 176 | # Find scripts |
|
173 | 177 | #--------------------------------------------------------------------------- |
|
174 | 178 | |
|
175 | 179 | def find_scripts(): |
|
176 | 180 | """ |
|
177 | 181 | Find IPython's scripts. |
|
178 | 182 | """ |
|
179 | 183 | scripts = [] |
|
180 | 184 | scripts.append('IPython/kernel/scripts/ipengine') |
|
181 | 185 | scripts.append('IPython/kernel/scripts/ipcontroller') |
|
182 | 186 | scripts.append('IPython/kernel/scripts/ipcluster') |
|
183 | 187 | scripts.append('scripts/ipython') |
|
188 | scripts.append('scripts/ipythonx') | |
|
184 | 189 | scripts.append('scripts/pycolor') |
|
185 | 190 | scripts.append('scripts/irunner') |
|
186 | 191 | |
|
187 | 192 | # Script to be run by the windows binary installer after the default setup |
|
188 | 193 | # routine, to add shortcuts and similar windows-only things. Windows |
|
189 | 194 | # post-install scripts MUST reside in the scripts/ dir, otherwise distutils |
|
190 | 195 | # doesn't find them. |
|
191 | 196 | if 'bdist_wininst' in sys.argv: |
|
192 | 197 | if len(sys.argv) > 2 and ('sdist' in sys.argv or 'bdist_rpm' in sys.argv): |
|
193 | 198 | print >> sys.stderr,"ERROR: bdist_wininst must be run alone. Exiting." |
|
194 | 199 | sys.exit(1) |
|
195 | 200 | scripts.append('scripts/ipython_win_post_install.py') |
|
196 | 201 | |
|
197 | 202 | return scripts |
|
198 | 203 | |
|
199 | 204 | #--------------------------------------------------------------------------- |
|
200 | 205 | # Find scripts |
|
201 | 206 | #--------------------------------------------------------------------------- |
|
202 | 207 | |
|
203 | 208 | def check_for_dependencies(): |
|
204 | 209 | """Check for IPython's dependencies. |
|
205 | 210 | |
|
206 | 211 | This function should NOT be called if running under setuptools! |
|
207 | 212 | """ |
|
208 | 213 | from setupext.setupext import ( |
|
209 | 214 | print_line, print_raw, print_status, print_message, |
|
210 | 215 | check_for_zopeinterface, check_for_twisted, |
|
211 | 216 | check_for_foolscap, check_for_pyopenssl, |
|
212 | 217 | check_for_sphinx, check_for_pygments, |
|
213 | 218 | check_for_nose, check_for_pexpect |
|
214 | 219 | ) |
|
215 | 220 | print_line() |
|
216 | 221 | print_raw("BUILDING IPYTHON") |
|
217 | 222 | print_status('python', sys.version) |
|
218 | 223 | print_status('platform', sys.platform) |
|
219 | 224 | if sys.platform == 'win32': |
|
220 | 225 | print_status('Windows version', sys.getwindowsversion()) |
|
221 | 226 | |
|
222 | 227 | print_raw("") |
|
223 | 228 | print_raw("OPTIONAL DEPENDENCIES") |
|
224 | 229 | |
|
225 | 230 | check_for_zopeinterface() |
|
226 | 231 | check_for_twisted() |
|
227 | 232 | check_for_foolscap() |
|
228 | 233 | check_for_pyopenssl() |
|
229 | 234 | check_for_sphinx() |
|
230 | 235 | check_for_pygments() |
|
231 | 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