##// END OF EJS Templates
Continuing a massive refactor of everything.
Brian Granger -
Show More
@@ -0,0 +1,45 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 Autocall capabilities for IPython.core.
5
6 Authors:
7
8 * Brian Granger
9 * Fernando Perez
10
11 Notes
12 -----
13 """
14
15 #-----------------------------------------------------------------------------
16 # Copyright (C) 2008-2009 The IPython Development Team
17 #
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
20 #-----------------------------------------------------------------------------
21
22 #-----------------------------------------------------------------------------
23 # Imports
24 #-----------------------------------------------------------------------------
25
26
27 #-----------------------------------------------------------------------------
28 # Code
29 #-----------------------------------------------------------------------------
30
31 class IPyAutocall(object):
32 """ Instances of this class are always autocalled
33
34 This happens regardless of 'autocall' variable state. Use this to
35 develop macro-like mechanisms.
36 """
37
38 def set_ip(self,ip):
39 """ Will be used to set _ip point to current ipython instance b/f call
40
41 Override this method if you don't want this to happen.
42
43 """
44 self._ip = ip
45
@@ -0,0 +1,52 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 Global exception classes for IPython.core.
5
6 Authors:
7
8 * Brian Granger
9 * Fernando Perez
10
11 Notes
12 -----
13 """
14
15 #-----------------------------------------------------------------------------
16 # Copyright (C) 2008-2009 The IPython Development Team
17 #
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
20 #-----------------------------------------------------------------------------
21
22 #-----------------------------------------------------------------------------
23 # Imports
24 #-----------------------------------------------------------------------------
25
26 #-----------------------------------------------------------------------------
27 # Exception classes
28 #-----------------------------------------------------------------------------
29
30 class IPythonCoreError(Exception):
31 pass
32
33
34 class TryNext(IPythonCoreError):
35 """Try next hook exception.
36
37 Raise this in your hook function to indicate that the next hook handler
38 should be used to handle the operation. If you pass arguments to the
39 constructor those arguments will be used by the next hook instead of the
40 original ones.
41 """
42
43 def __init__(self, *args, **kwargs):
44 self.args = args
45 self.kwargs = kwargs
46
47 class UsageError(IPythonCoreError):
48 """Error in magic function arguments, etc.
49
50 Something that probably won't warrant a full traceback, but should
51 nevertheless interrupt a macro / batch file.
52 """ No newline at end of file
@@ -0,0 +1,306 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 Paging capabilities for IPython.core
5
6 Authors:
7
8 * Brian Granger
9 * Fernando Perez
10
11 Notes
12 -----
13
14 For now this uses ipapi, so it can't be in IPython.utils. If we can get
15 rid of that dependency, we could move it there.
16 -----
17 """
18
19 #-----------------------------------------------------------------------------
20 # Copyright (C) 2008-2009 The IPython Development Team
21 #
22 # Distributed under the terms of the BSD License. The full license is in
23 # the file COPYING, distributed as part of this software.
24 #-----------------------------------------------------------------------------
25
26 #-----------------------------------------------------------------------------
27 # Imports
28 #-----------------------------------------------------------------------------
29
30 import os
31 import re
32 import sys
33
34 from IPython.core import ipapi
35 from IPython.core.error import TryNext
36 from IPython.utils.genutils import (
37 chop, Term
38 )
39
40 if os.name == "nt":
41 from IPython.utils.winconsole import get_console_size
42
43
44 #-----------------------------------------------------------------------------
45 # Classes and functions
46 #-----------------------------------------------------------------------------
47
48 esc_re = re.compile(r"(\x1b[^m]+m)")
49
50 def page_dumb(strng,start=0,screen_lines=25):
51 """Very dumb 'pager' in Python, for when nothing else works.
52
53 Only moves forward, same interface as page(), except for pager_cmd and
54 mode."""
55
56 out_ln = strng.splitlines()[start:]
57 screens = chop(out_ln,screen_lines-1)
58 if len(screens) == 1:
59 print >>Term.cout, os.linesep.join(screens[0])
60 else:
61 last_escape = ""
62 for scr in screens[0:-1]:
63 hunk = os.linesep.join(scr)
64 print >>Term.cout, last_escape + hunk
65 if not page_more():
66 return
67 esc_list = esc_re.findall(hunk)
68 if len(esc_list) > 0:
69 last_escape = esc_list[-1]
70 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
71
72 #----------------------------------------------------------------------------
73 def page(strng,start=0,screen_lines=0,pager_cmd = None):
74 """Print a string, piping through a pager after a certain length.
75
76 The screen_lines parameter specifies the number of *usable* lines of your
77 terminal screen (total lines minus lines you need to reserve to show other
78 information).
79
80 If you set screen_lines to a number <=0, page() will try to auto-determine
81 your screen size and will only use up to (screen_size+screen_lines) for
82 printing, paging after that. That is, if you want auto-detection but need
83 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
84 auto-detection without any lines reserved simply use screen_lines = 0.
85
86 If a string won't fit in the allowed lines, it is sent through the
87 specified pager command. If none given, look for PAGER in the environment,
88 and ultimately default to less.
89
90 If no system pager works, the string is sent through a 'dumb pager'
91 written in python, very simplistic.
92 """
93
94 # Some routines may auto-compute start offsets incorrectly and pass a
95 # negative value. Offset to 0 for robustness.
96 start = max(0,start)
97
98 # first, try the hook
99 ip = ipapi.get()
100 if ip:
101 try:
102 ip.hooks.show_in_pager(strng)
103 return
104 except TryNext:
105 pass
106
107 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
108 TERM = os.environ.get('TERM','dumb')
109 if TERM in ['dumb','emacs'] and os.name != 'nt':
110 print strng
111 return
112 # chop off the topmost part of the string we don't want to see
113 str_lines = strng.split(os.linesep)[start:]
114 str_toprint = os.linesep.join(str_lines)
115 num_newlines = len(str_lines)
116 len_str = len(str_toprint)
117
118 # Dumb heuristics to guesstimate number of on-screen lines the string
119 # takes. Very basic, but good enough for docstrings in reasonable
120 # terminals. If someone later feels like refining it, it's not hard.
121 numlines = max(num_newlines,int(len_str/80)+1)
122
123 if os.name == "nt":
124 screen_lines_def = get_console_size(defaulty=25)[1]
125 else:
126 screen_lines_def = 25 # default value if we can't auto-determine
127
128 # auto-determine screen size
129 if screen_lines <= 0:
130 if TERM=='xterm':
131 use_curses = USE_CURSES
132 else:
133 # curses causes problems on many terminals other than xterm.
134 use_curses = False
135 if use_curses:
136 # There is a bug in curses, where *sometimes* it fails to properly
137 # initialize, and then after the endwin() call is made, the
138 # terminal is left in an unusable state. Rather than trying to
139 # check everytime for this (by requesting and comparing termios
140 # flags each time), we just save the initial terminal state and
141 # unconditionally reset it every time. It's cheaper than making
142 # the checks.
143 term_flags = termios.tcgetattr(sys.stdout)
144 scr = curses.initscr()
145 screen_lines_real,screen_cols = scr.getmaxyx()
146 curses.endwin()
147 # Restore terminal state in case endwin() didn't.
148 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
149 # Now we have what we needed: the screen size in rows/columns
150 screen_lines += screen_lines_real
151 #print '***Screen size:',screen_lines_real,'lines x',\
152 #screen_cols,'columns.' # dbg
153 else:
154 screen_lines += screen_lines_def
155
156 #print 'numlines',numlines,'screenlines',screen_lines # dbg
157 if numlines <= screen_lines :
158 #print '*** normal print' # dbg
159 print >>Term.cout, str_toprint
160 else:
161 # Try to open pager and default to internal one if that fails.
162 # All failure modes are tagged as 'retval=1', to match the return
163 # value of a failed system command. If any intermediate attempt
164 # sets retval to 1, at the end we resort to our own page_dumb() pager.
165 pager_cmd = get_pager_cmd(pager_cmd)
166 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
167 if os.name == 'nt':
168 if pager_cmd.startswith('type'):
169 # The default WinXP 'type' command is failing on complex strings.
170 retval = 1
171 else:
172 tmpname = tempfile.mktemp('.txt')
173 tmpfile = file(tmpname,'wt')
174 tmpfile.write(strng)
175 tmpfile.close()
176 cmd = "%s < %s" % (pager_cmd,tmpname)
177 if os.system(cmd):
178 retval = 1
179 else:
180 retval = None
181 os.remove(tmpname)
182 else:
183 try:
184 retval = None
185 # if I use popen4, things hang. No idea why.
186 #pager,shell_out = os.popen4(pager_cmd)
187 pager = os.popen(pager_cmd,'w')
188 pager.write(strng)
189 pager.close()
190 retval = pager.close() # success returns None
191 except IOError,msg: # broken pipe when user quits
192 if msg.args == (32,'Broken pipe'):
193 retval = None
194 else:
195 retval = 1
196 except OSError:
197 # Other strange problems, sometimes seen in Win2k/cygwin
198 retval = 1
199 if retval is not None:
200 page_dumb(strng,screen_lines=screen_lines)
201
202 #----------------------------------------------------------------------------
203 def page_file(fname,start = 0, pager_cmd = None):
204 """Page a file, using an optional pager command and starting line.
205 """
206
207 pager_cmd = get_pager_cmd(pager_cmd)
208 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
209
210 try:
211 if os.environ['TERM'] in ['emacs','dumb']:
212 raise EnvironmentError
213 xsys(pager_cmd + ' ' + fname)
214 except:
215 try:
216 if start > 0:
217 start -= 1
218 page(open(fname).read(),start)
219 except:
220 print 'Unable to show file',`fname`
221
222 #----------------------------------------------------------------------------
223 def get_pager_cmd(pager_cmd = None):
224 """Return a pager command.
225
226 Makes some attempts at finding an OS-correct one."""
227
228 if os.name == 'posix':
229 default_pager_cmd = 'less -r' # -r for color control sequences
230 elif os.name in ['nt','dos']:
231 default_pager_cmd = 'type'
232
233 if pager_cmd is None:
234 try:
235 pager_cmd = os.environ['PAGER']
236 except:
237 pager_cmd = default_pager_cmd
238 return pager_cmd
239
240 #-----------------------------------------------------------------------------
241 def get_pager_start(pager,start):
242 """Return the string for paging files with an offset.
243
244 This is the '+N' argument which less and more (under Unix) accept.
245 """
246
247 if pager in ['less','more']:
248 if start:
249 start_string = '+' + str(start)
250 else:
251 start_string = ''
252 else:
253 start_string = ''
254 return start_string
255
256 #----------------------------------------------------------------------------
257 # (X)emacs on W32 doesn't like to be bypassed with msvcrt.getch()
258 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
259 import msvcrt
260 def page_more():
261 """ Smart pausing between pages
262
263 @return: True if need print more lines, False if quit
264 """
265 Term.cout.write('---Return to continue, q to quit--- ')
266 ans = msvcrt.getch()
267 if ans in ("q", "Q"):
268 result = False
269 else:
270 result = True
271 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
272 return result
273 else:
274 def page_more():
275 ans = raw_input('---Return to continue, q to quit--- ')
276 if ans.lower().startswith('q'):
277 return False
278 else:
279 return True
280
281 #----------------------------------------------------------------------------
282 def snip_print(str,width = 75,print_full = 0,header = ''):
283 """Print a string snipping the midsection to fit in width.
284
285 print_full: mode control:
286 - 0: only snip long strings
287 - 1: send to page() directly.
288 - 2: snip long strings and ask for full length viewing with page()
289 Return 1 if snipping was necessary, 0 otherwise."""
290
291 if print_full == 1:
292 page(header+str)
293 return 0
294
295 print header,
296 if len(str) < width:
297 print str
298 snip = 0
299 else:
300 whalf = int((width -5)/2)
301 print str[:whalf] + ' <...> ' + str[-whalf:]
302 snip = 1
303 if snip and print_full == 2:
304 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
305 page(str)
306 return snip No newline at end of file
@@ -1,76 +1,50 b''
1 # -*- coding: utf-8 -*-
1 #!/usr/bin/env python
2 # encoding: utf-8
2 """
3 """
3 IPython -- An enhanced Interactive Python
4 IPython.
4
5
5 One of Python's nicest features is its interactive interpreter. This allows
6 IPython is a set of tools for interactive and exploratory computing in Python.
6 very fast testing of ideas without the overhead of creating test files as is
7 typical in most programming languages. However, the interpreter supplied with
8 the standard Python distribution is fairly primitive (and IDLE isn't really
9 much better).
10
11 IPython tries to:
12
13 i - provide an efficient environment for interactive work in Python
14 programming. It tries to address what we see as shortcomings of the standard
15 Python prompt, and adds many features to make interactive work much more
16 efficient.
17
18 ii - offer a flexible framework so that it can be used as the base
19 environment for other projects and problems where Python can be the
20 underlying language. Specifically scientific environments like Mathematica,
21 IDL and Mathcad inspired its design, but similar ideas can be useful in many
22 fields. Python is a fabulous language for implementing this kind of system
23 (due to its dynamic and introspective features), and with suitable libraries
24 entire systems could be built leveraging Python's power.
25
26 iii - serve as an embeddable, ready to go interpreter for your own programs.
27
28 IPython requires Python 2.4 or newer.
29 """
7 """
30
8
31 #*****************************************************************************
9 #-----------------------------------------------------------------------------
32 # Copyright (C) 2008-2009 The IPython Development Team
10 # Copyright (C) 2008-2009 The IPython Development Team
33 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
34 #
11 #
35 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
36 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
37 #*****************************************************************************
14 #-----------------------------------------------------------------------------
15
16 #-----------------------------------------------------------------------------
17 # Imports
18 #-----------------------------------------------------------------------------
38
19
39 # Enforce proper version requirements
20 import os
40 import sys
21 import sys
22 from IPython.core import release
23
24 #-----------------------------------------------------------------------------
25 # Setup everything
26 #-----------------------------------------------------------------------------
27
41
28
42 if sys.version[0:3] < '2.4':
29 if sys.version[0:3] < '2.4':
43 raise ImportError('Python Version 2.4 or above is required for IPython.')
30 raise ImportError('Python Version 2.4 or above is required for IPython.')
44
31
32
45 # Make it easy to import extensions - they are always directly on pythonpath.
33 # Make it easy to import extensions - they are always directly on pythonpath.
46 # Therefore, non-IPython modules can be added to extensions directory
34 # Therefore, non-IPython modules can be added to extensions directory
47 import os
48 sys.path.append(os.path.join(os.path.dirname(__file__), "extensions"))
35 sys.path.append(os.path.join(os.path.dirname(__file__), "extensions"))
49
36
50 # Define what gets imported with a 'from IPython import *'
51 __all__ = ['IPython.core.ipapi','utils.generics','utils.ipstruct',
52 'core.release','core.shell']
53
54 # Load __all__ in IPython namespace so that a simple 'import IPython' gives
55 # access to them via IPython.<name>
56 glob,loc = globals(),locals()
57 for name in __all__:
58 #print 'Importing: ',name # dbg
59 __import__(name,glob,loc,[])
60
37
61 from IPython.core import shell
38 # from IPython.core import shell
62 Shell = shell
39 # Shell = shell
63 from IPython.core import ipapi
64 from IPython.core import iplib
40 from IPython.core import iplib
65
41
42
66 # Release data
43 # Release data
67 from IPython.core import release # do it explicitly so pydoc can see it - pydoc bug
44 __author__ = ''
68 __author__ = '%s <%s>\n%s <%s>\n%s <%s>' % \
45 for author, email in release.authors.values():
69 ( release.authors['Fernando'] + release.authors['Janko'] + \
46 __author__ += author + ' <' + email + '>\n'
70 release.authors['Nathan'] )
71 __license__ = release.license
47 __license__ = release.license
72 __version__ = release.version
48 __version__ = release.version
73 __revision__ = release.revision
49 __revision__ = release.revision
74
50
75 # Namespace cleanup
76 del name,glob,loc
@@ -1,9 +1,6 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3
3
4 def test_import_configloader():
5 from IPython.config import configloader
6
7 def test_import_userconfig():
4 def test_import_userconfig():
8 from IPython.config import userconfig
5 from IPython.config import userconfig
9
6
@@ -70,12 +70,13 b' import os'
70 import re
70 import re
71 import shlex
71 import shlex
72 import sys
72 import sys
73 import IPython.utils.rlineimpl as readline
74 import itertools
73 import itertools
74 import types
75
76 from IPython.core.error import TryNext
77 import IPython.utils.rlineimpl as readline
75 from IPython.utils.ipstruct import Struct
78 from IPython.utils.ipstruct import Struct
76 from IPython.core import ipapi
77 from IPython.utils import generics
79 from IPython.utils import generics
78 import types
79
80
80 # Python 2.4 offers sets as a builtin
81 # Python 2.4 offers sets as a builtin
81 try:
82 try:
@@ -195,7 +196,7 b' class Completer:'
195
196
196 try:
197 try:
197 words = generics.complete_object(obj, words)
198 words = generics.complete_object(obj, words)
198 except ipapi.TryNext:
199 except TryNext:
199 pass
200 pass
200 # Build match list to return
201 # Build match list to return
201 n = len(attr)
202 n = len(attr)
@@ -553,7 +554,7 b' class IPCompleter(Completer):'
553 return withcase
554 return withcase
554 # if none, then case insensitive ones are ok too
555 # if none, then case insensitive ones are ok too
555 return [r for r in res if r.lower().startswith(text.lower())]
556 return [r for r in res if r.lower().startswith(text.lower())]
556 except ipapi.TryNext:
557 except TryNext:
557 pass
558 pass
558
559
559 return None
560 return None
@@ -21,6 +21,7 b' Authors:'
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 from copy import deepcopy
23 from copy import deepcopy
24 import datetime
24 from weakref import WeakValueDictionary
25 from weakref import WeakValueDictionary
25
26
26 from IPython.utils.ipstruct import Struct
27 from IPython.utils.ipstruct import Struct
@@ -122,6 +123,7 b' class Component(HasTraitlets):'
122 config = Instance(Struct,(),{})
123 config = Instance(Struct,(),{})
123 parent = This()
124 parent = This()
124 root = This()
125 root = This()
126 created = None
125
127
126 def __init__(self, parent, name=None, config=None):
128 def __init__(self, parent, name=None, config=None):
127 """Create a component given a parent and possibly and name and config.
129 """Create a component given a parent and possibly and name and config.
@@ -170,6 +172,8 b' class Component(HasTraitlets):'
170 if self.parent is not None:
172 if self.parent is not None:
171 self.config = deepcopy(self.parent.config)
173 self.config = deepcopy(self.parent.config)
172
174
175 self.created = datetime.datetime.now()
176
173 #-------------------------------------------------------------------------
177 #-------------------------------------------------------------------------
174 # Static traitlet notifiations
178 # Static traitlet notifiations
175 #-------------------------------------------------------------------------
179 #-------------------------------------------------------------------------
@@ -110,7 +110,7 b' class Tracer(object):'
110 __IPYTHON__
110 __IPYTHON__
111 except NameError:
111 except NameError:
112 # Outside of ipython, we set our own exception hook manually
112 # Outside of ipython, we set our own exception hook manually
113 __IPYTHON__ = ipapi.get(True,False)
113 __IPYTHON__ = ipapi.get()
114 BdbQuit_excepthook.excepthook_ori = sys.excepthook
114 BdbQuit_excepthook.excepthook_ori = sys.excepthook
115 sys.excepthook = BdbQuit_excepthook
115 sys.excepthook = BdbQuit_excepthook
116 def_colors = 'NoColor'
116 def_colors = 'NoColor'
@@ -123,7 +123,7 b' class Tracer(object):'
123 else:
123 else:
124 # In ipython, we use its custom exception handler mechanism
124 # In ipython, we use its custom exception handler mechanism
125 ip = ipapi.get()
125 ip = ipapi.get()
126 def_colors = ip.options.colors
126 def_colors = ip.colors
127 ip.set_custom_exc((bdb.BdbQuit,),BdbQuit_IPython_excepthook)
127 ip.set_custom_exc((bdb.BdbQuit,),BdbQuit_IPython_excepthook)
128
128
129 if colors is None:
129 if colors is None:
@@ -47,9 +47,7 b" def magic_history(self, parameter_s = ''):"
47 confirmation first if it already exists.
47 confirmation first if it already exists.
48 """
48 """
49
49
50 ip = self.api
50 if not self.outputcache.do_full_cache:
51 shell = self.shell
52 if not shell.outputcache.do_full_cache:
53 print 'This feature is only available if numbered prompts are in use.'
51 print 'This feature is only available if numbered prompts are in use.'
54 return
52 return
55 opts,args = self.parse_options(parameter_s,'gntsrf:',mode='list')
53 opts,args = self.parse_options(parameter_s,'gntsrf:',mode='list')
@@ -71,11 +69,11 b" def magic_history(self, parameter_s = ''):"
71 close_at_end = True
69 close_at_end = True
72
70
73 if 't' in opts:
71 if 't' in opts:
74 input_hist = shell.input_hist
72 input_hist = self.input_hist
75 elif 'r' in opts:
73 elif 'r' in opts:
76 input_hist = shell.input_hist_raw
74 input_hist = self.input_hist_raw
77 else:
75 else:
78 input_hist = shell.input_hist
76 input_hist = self.input_hist
79
77
80 default_length = 40
78 default_length = 40
81 pattern = None
79 pattern = None
@@ -105,7 +103,7 b" def magic_history(self, parameter_s = ''):"
105
103
106 found = False
104 found = False
107 if pattern is not None:
105 if pattern is not None:
108 sh = ip.IP.shadowhist.all()
106 sh = self.shadowhist.all()
109 for idx, s in sh:
107 for idx, s in sh:
110 if fnmatch.fnmatch(s, pattern):
108 if fnmatch.fnmatch(s, pattern):
111 print "0%d: %s" %(idx, s)
109 print "0%d: %s" %(idx, s)
@@ -168,9 +166,8 b' def rep_f(self, arg):'
168 """
166 """
169
167
170 opts,args = self.parse_options(arg,'',mode='list')
168 opts,args = self.parse_options(arg,'',mode='list')
171 ip = self.api
172 if not args:
169 if not args:
173 ip.set_next_input(str(ip.user_ns["_"]))
170 self.set_next_input(str(self.user_ns["_"]))
174 return
171 return
175
172
176 if len(args) == 1 and not '-' in args[0]:
173 if len(args) == 1 and not '-' in args[0]:
@@ -179,33 +176,33 b' def rep_f(self, arg):'
179 # get from shadow hist
176 # get from shadow hist
180 num = int(arg[1:])
177 num = int(arg[1:])
181 line = self.shadowhist.get(num)
178 line = self.shadowhist.get(num)
182 ip.set_next_input(str(line))
179 self.set_next_input(str(line))
183 return
180 return
184 try:
181 try:
185 num = int(args[0])
182 num = int(args[0])
186 ip.set_next_input(str(ip.IP.input_hist_raw[num]).rstrip())
183 self.set_next_input(str(self.input_hist_raw[num]).rstrip())
187 return
184 return
188 except ValueError:
185 except ValueError:
189 pass
186 pass
190
187
191 for h in reversed(self.shell.input_hist_raw):
188 for h in reversed(self.input_hist_raw):
192 if 'rep' in h:
189 if 'rep' in h:
193 continue
190 continue
194 if fnmatch.fnmatch(h,'*' + arg + '*'):
191 if fnmatch.fnmatch(h,'*' + arg + '*'):
195 ip.set_next_input(str(h).rstrip())
192 self.set_next_input(str(h).rstrip())
196 return
193 return
197
194
198 try:
195 try:
199 lines = self.extract_input_slices(args, True)
196 lines = self.extract_input_slices(args, True)
200 print "lines",lines
197 print "lines",lines
201 ip.runlines(lines)
198 self.runlines(lines)
202 except ValueError:
199 except ValueError:
203 print "Not found in recent history:", args
200 print "Not found in recent history:", args
204
201
205
202
206 _sentinel = object()
203 _sentinel = object()
207
204
208 class ShadowHist:
205 class ShadowHist(object):
209 def __init__(self,db):
206 def __init__(self,db):
210 # cmd => idx mapping
207 # cmd => idx mapping
211 self.curidx = 0
208 self.curidx = 0
@@ -228,7 +225,7 b' class ShadowHist:'
228 #print "new",newidx # dbg
225 #print "new",newidx # dbg
229 self.db.hset('shadowhist',ent, newidx)
226 self.db.hset('shadowhist',ent, newidx)
230 except:
227 except:
231 ipapi.get().IP.showtraceback()
228 ipapi.get().showtraceback()
232 print "WARNING: disabling shadow history"
229 print "WARNING: disabling shadow history"
233 self.disabled = True
230 self.disabled = True
234
231
@@ -250,8 +247,8 b' class ShadowHist:'
250 def init_ipython(ip):
247 def init_ipython(ip):
251 import ipy_completers
248 import ipy_completers
252
249
253 ip.expose_magic("rep",rep_f)
250 ip.define_magic("rep",rep_f)
254 ip.expose_magic("hist",magic_hist)
251 ip.define_magic("hist",magic_hist)
255 ip.expose_magic("history",magic_history)
252 ip.define_magic("history",magic_history)
256
253
257 ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
254 ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
@@ -26,7 +26,7 b' def calljed(self,filename, linenum):'
26 "My editor hook calls the jed editor directly."
26 "My editor hook calls the jed editor directly."
27 print "Calling my own editor, jed ..."
27 print "Calling my own editor, jed ..."
28 if os.system('jed +%d %s' % (linenum,filename)) != 0:
28 if os.system('jed +%d %s' % (linenum,filename)) != 0:
29 raise ipapi.TryNext()
29 raise TryNext()
30
30
31 ip.set_hook('editor', calljed)
31 ip.set_hook('editor', calljed)
32
32
@@ -41,13 +41,13 b' somewhere in your configuration files or ipython command line.'
41 # the file COPYING, distributed as part of this software.
41 # the file COPYING, distributed as part of this software.
42 #*****************************************************************************
42 #*****************************************************************************
43
43
44 from IPython.core import ipapi
45
46 import os, bisect
44 import os, bisect
47 import sys
45 import sys
48 from IPython.utils.genutils import Term, shell
46 from IPython.utils.genutils import Term, shell
49 from pprint import PrettyPrinter
47 from pprint import PrettyPrinter
50
48
49 from IPython.core.error import TryNext
50
51 # List here all the default hooks. For now it's just the editor functions
51 # List here all the default hooks. For now it's just the editor functions
52 # but over time we'll move here all the public API for user-accessible things.
52 # but over time we'll move here all the public API for user-accessible things.
53 # vds: >>
53 # vds: >>
@@ -83,7 +83,7 b' def editor(self,filename, linenum=None):'
83
83
84 # Call the actual editor
84 # Call the actual editor
85 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
85 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
86 raise ipapi.TryNext()
86 raise TryNext()
87
87
88 import tempfile
88 import tempfile
89 def fix_error_editor(self,filename,linenum,column,msg):
89 def fix_error_editor(self,filename,linenum,column,msg):
@@ -105,7 +105,7 b' def fix_error_editor(self,filename,linenum,column,msg):'
105 t = vim_quickfix_file()
105 t = vim_quickfix_file()
106 try:
106 try:
107 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
107 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
108 raise ipapi.TryNext()
108 raise TryNext()
109 finally:
109 finally:
110 t.close()
110 t.close()
111
111
@@ -140,12 +140,12 b' class CommandChainDispatcher:'
140 try:
140 try:
141 ret = cmd(*args, **kw)
141 ret = cmd(*args, **kw)
142 return ret
142 return ret
143 except ipapi.TryNext, exc:
143 except TryNext, exc:
144 if exc.args or exc.kwargs:
144 if exc.args or exc.kwargs:
145 args = exc.args
145 args = exc.args
146 kw = exc.kwargs
146 kw = exc.kwargs
147 # if no function will accept it, raise TryNext up to the caller
147 # if no function will accept it, raise TryNext up to the caller
148 raise ipapi.TryNext
148 raise TryNext
149
149
150 def __str__(self):
150 def __str__(self):
151 return str(self.chain)
151 return str(self.chain)
@@ -214,14 +214,12 b' def late_startup_hook(self):'
214
214
215 def generate_prompt(self, is_continuation):
215 def generate_prompt(self, is_continuation):
216 """ calculate and return a string with the prompt to display """
216 """ calculate and return a string with the prompt to display """
217 ip = self.api
218 if is_continuation:
217 if is_continuation:
219 return str(ip.IP.outputcache.prompt2)
218 return str(self.outputcache.prompt2)
220 return str(ip.IP.outputcache.prompt1)
219 return str(self.outputcache.prompt1)
221
220
222 def generate_output_prompt(self):
221 def generate_output_prompt(self):
223 ip = self.api
222 return str(self.outputcache.prompt_out)
224 return str(ip.IP.outputcache.prompt_out)
225
223
226 def shell_hook(self,cmd):
224 def shell_hook(self,cmd):
227 """ Run system/shell command a'la os.system() """
225 """ Run system/shell command a'la os.system() """
@@ -231,7 +229,7 b' def shell_hook(self,cmd):'
231 def show_in_pager(self,s):
229 def show_in_pager(self,s):
232 """ Run a string through pager """
230 """ Run a string through pager """
233 # raising TryNext here will use the default paging functionality
231 # raising TryNext here will use the default paging functionality
234 raise ipapi.TryNext
232 raise TryNext
235
233
236 def pre_prompt_hook(self):
234 def pre_prompt_hook(self):
237 """ Run before displaying the next prompt
235 """ Run before displaying the next prompt
This diff has been collapsed as it changes many lines, (699 lines changed) Show them Hide them
@@ -1,684 +1,61 b''
1 """IPython customization API
1 #!/usr/bin/env python
2
2 # encoding: utf-8
3 Your one-stop module for configuring & extending ipython
3 """
4
4 Oh my @#*%, where did ipapi go?
5 The API will probably break when ipython 1.0 is released, but so
6 will the other configuration method (rc files).
7
8 All names prefixed by underscores are for internal use, not part
9 of the public api.
10
11 Below is an example that you can just put to a module and import from ipython.
12
13 A good practice is to install the config script below as e.g.
14
15 ~/.ipython/my_private_conf.py
16
17 And do
18
19 import_mod my_private_conf
20
21 in ~/.ipython/ipythonrc
22
23 That way the module is imported at startup and you can have all your
24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
25 stuff) in there.
26
27 from IPython.core import ipapi
28 ip = ipapi.get()
29
30 def ankka_f(self, arg):
31 print 'Ankka',self,'says uppercase:',arg.upper()
32
33 ip.expose_magic('ankka',ankka_f)
34
35 ip.magic('alias sayhi echo "Testing, hi ok"')
36 ip.magic('alias helloworld echo "Hello world"')
37 ip.system('pwd')
38
39 ip.ex('import re')
40 ip.ex('''
41 def funcci(a,b):
42 print a+b
43 print funcci(3,4)
44 ''')
45 ip.ex('funcci(348,9)')
46
5
47 def jed_editor(self,filename, linenum=None):
6 Originally, this module was designed to be a public api for IPython. It is
48 print 'Calling my own editor, jed ... via hook!'
7 now deprecated and replaced by :class:`IPython.core.Interactive` shell.
49 import os
8 Almost all of the methods that were here are now there, but possibly renamed.
50 if linenum is None: linenum = 0
51 os.system('jed +%d %s' % (linenum, filename))
52 print 'exiting jed'
53
9
54 ip.set_hook('editor',jed_editor)
10 During our transition, we will keep this simple module with its :func:`get`
11 function. It too will eventually go away when the new component querying
12 interface is fully used.
55
13
56 o = ip.options
14 Authors:
57 o.autocall = 2 # FULL autocall mode
58
15
59 print 'done!'
16 * Brian Granger
60 """
17 """
61
18
62 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
63 # Modules and globals
20 # Copyright (C) 2008-2009 The IPython Development Team
64
21 #
65 # stdlib imports
22 # Distributed under the terms of the BSD License. The full license is in
66 import __builtin__
23 # the file COPYING, distributed as part of this software.
67 import sys
68
69 # contains the most recently instantiated IPApi
70 _RECENT_IP = None
71
72 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
73 # Code begins
74
75 class TryNext(Exception):
76 """Try next hook exception.
77
78 Raise this in your hook function to indicate that the next hook handler
79 should be used to handle the operation. If you pass arguments to the
80 constructor those arguments will be used by the next hook instead of the
81 original ones.
82 """
83
84 def __init__(self, *args, **kwargs):
85 self.args = args
86 self.kwargs = kwargs
87
88
89 class UsageError(Exception):
90 """ Error in magic function arguments, etc.
91
92 Something that probably won't warrant a full traceback, but should
93 nevertheless interrupt a macro / batch file.
94 """
95
96
97 class IPyAutocall:
98 """ Instances of this class are always autocalled
99
100 This happens regardless of 'autocall' variable state. Use this to
101 develop macro-like mechanisms.
102 """
103
104 def set_ip(self,ip):
105 """ Will be used to set _ip point to current ipython instance b/f call
106
107 Override this method if you don't want this to happen.
108
109 """
110 self._ip = ip
111
112
113 class IPythonNotRunning:
114 """Dummy do-nothing class.
115
116 Instances of this class return a dummy attribute on all accesses, which
117 can be called and warns. This makes it easier to write scripts which use
118 the ipapi.get() object for informational purposes to operate both with and
119 without ipython. Obviously code which uses the ipython object for
120 computations will not work, but this allows a wider range of code to
121 transparently work whether ipython is being used or not."""
122
123 def __init__(self,warn=True):
124 if warn:
125 self.dummy = self._dummy_warn
126 else:
127 self.dummy = self._dummy_silent
128
129 def __str__(self):
130 return "<IPythonNotRunning>"
131
132 __repr__ = __str__
133
134 def __getattr__(self,name):
135 return self.dummy
136
137 def _dummy_warn(self,*args,**kw):
138 """Dummy function, which doesn't do anything but warn."""
139
140 print ("IPython is not running, this is a dummy no-op function")
141
142 def _dummy_silent(self,*args,**kw):
143 """Dummy function, which doesn't do anything and emits no warnings."""
144 pass
145
146
147 def get(allow_dummy=False,dummy_warn=True):
148 """Get an IPApi object.
149
150 If allow_dummy is true, returns an instance of IPythonNotRunning
151 instead of None if not running under IPython.
152
153 If dummy_warn is false, the dummy instance will be completely silent.
154
155 Running this should be the first thing you do when writing extensions that
156 can be imported as normal modules. You can then direct all the
157 configuration operations against the returned object.
158 """
159 global _RECENT_IP
160 if allow_dummy and not _RECENT_IP:
161 _RECENT_IP = IPythonNotRunning(dummy_warn)
162 return _RECENT_IP
163
164
165 class IPApi(object):
166 """ The actual API class for configuring IPython
167
168 You should do all of the IPython configuration by getting an IPApi object
169 with IPython.ipapi.get() and using the attributes and methods of the
170 returned object."""
171
172 def __init__(self,ip):
173
174 global _RECENT_IP
175
176 # All attributes exposed here are considered to be the public API of
177 # IPython. As needs dictate, some of these may be wrapped as
178 # properties.
179
180 self.magic = ip.ipmagic
181
182 self.system = ip.system
183
184 self.set_hook = ip.set_hook
185
186 self.set_custom_exc = ip.set_custom_exc
187
188 self.user_ns = ip.user_ns
189
190 self.set_crash_handler = ip.set_crash_handler
191
192 # Session-specific data store, which can be used to store
193 # data that should persist through the ipython session.
194 self.meta = ip.meta
195
196 # The ipython instance provided
197 self.IP = ip
198
199 self.extensions = {}
200
201 self.dbg = DebugTools(self)
202
203 _RECENT_IP = self
204
205 # Use a property for some things which are added to the instance very
206 # late. I don't have time right now to disentangle the initialization
207 # order issues, so a property lets us delay item extraction while
208 # providing a normal attribute API.
209 def get_db(self):
210 """A handle to persistent dict-like database (a PickleShareDB object)"""
211 return self.IP.db
212
25
213 db = property(get_db,None,None,get_db.__doc__)
26 #-----------------------------------------------------------------------------
214
27 # Imports
215 def get_options(self):
28 #-----------------------------------------------------------------------------
216 """All configurable variables."""
217
218 # catch typos by disabling new attribute creation. If new attr creation
219 # is in fact wanted (e.g. when exposing new options), do
220 # allow_new_attr(True) for the received rc struct.
221
222 return self.IP
223
224 options = property(get_options,None,None,get_options.__doc__)
225
226 def expose_magic(self,magicname, func):
227 """Expose own function as magic function for ipython
228
229 def foo_impl(self,parameter_s=''):
230 'My very own magic!. (Use docstrings, IPython reads them).'
231 print 'Magic function. Passed parameter is between < >:'
232 print '<%s>' % parameter_s
233 print 'The self object is:',self
234
235 ipapi.expose_magic('foo',foo_impl)
236 """
237
238 import new
239 im = new.instancemethod(func,self.IP, self.IP.__class__)
240 old = getattr(self.IP, "magic_" + magicname, None)
241 if old:
242 self.dbg.debug_stack("Magic redefinition '%s', old %s" %
243 (magicname,old) )
244
245 setattr(self.IP, "magic_" + magicname, im)
246
247 def ex(self,cmd):
248 """ Execute a normal python statement in user namespace """
249 exec cmd in self.user_ns
250
251 def ev(self,expr):
252 """ Evaluate python expression expr in user namespace
253
254 Returns the result of evaluation"""
255 return eval(expr,self.user_ns)
256
257 def runlines(self,lines):
258 """ Run the specified lines in interpreter, honoring ipython directives.
259
260 This allows %magic and !shell escape notations.
261
262 Takes either all lines in one string or list of lines.
263 """
264
265 def cleanup_ipy_script(script):
266 """ Make a script safe for _ip.runlines()
267
268 - Removes empty lines Suffixes all indented blocks that end with
269 - unindented lines with empty lines
270 """
271
272 res = []
273 lines = script.splitlines()
274
275 level = 0
276 for l in lines:
277 lstripped = l.lstrip()
278 stripped = l.strip()
279 if not stripped:
280 continue
281 newlevel = len(l) - len(lstripped)
282 def is_secondary_block_start(s):
283 if not s.endswith(':'):
284 return False
285 if (s.startswith('elif') or
286 s.startswith('else') or
287 s.startswith('except') or
288 s.startswith('finally')):
289 return True
290
291 if level > 0 and newlevel == 0 and \
292 not is_secondary_block_start(stripped):
293 # add empty line
294 res.append('')
295
296 res.append(l)
297 level = newlevel
298 return '\n'.join(res) + '\n'
299
300 if isinstance(lines,basestring):
301 script = lines
302 else:
303 script = '\n'.join(lines)
304 clean=cleanup_ipy_script(script)
305 # print "_ip.runlines() script:\n",clean # dbg
306 self.IP.runlines(clean)
307
308 def to_user_ns(self,vars, interactive = True):
309 """Inject a group of variables into the IPython user namespace.
310
311 Inputs:
312
313 - vars: string with variable names separated by whitespace, or a
314 dict with name/value pairs.
315
316 - interactive: if True (default), the var will be listed with
317 %whos et. al.
318
319 This utility routine is meant to ease interactive debugging work,
320 where you want to easily propagate some internal variable in your code
321 up to the interactive namespace for further exploration.
322
323 When you run code via %run, globals in your script become visible at
324 the interactive prompt, but this doesn't happen for locals inside your
325 own functions and methods. Yet when debugging, it is common to want
326 to explore some internal variables further at the interactive propmt.
327
328 Examples:
329
330 To use this, you first must obtain a handle on the ipython object as
331 indicated above, via:
332
333 from IPython.core import ipapi
334 ip = ipapi.get()
335
336 Once this is done, inside a routine foo() where you want to expose
337 variables x and y, you do the following:
338
339 def foo():
340 ...
341 x = your_computation()
342 y = something_else()
343
344 # This pushes x and y to the interactive prompt immediately, even
345 # if this routine crashes on the next line after:
346 ip.to_user_ns('x y')
347 ...
348
349 # To expose *ALL* the local variables from the function, use:
350 ip.to_user_ns(locals())
351
352 ...
353 # return
354
355
356 If you need to rename variables, the dict input makes it easy. For
357 example, this call exposes variables 'foo' as 'x' and 'bar' as 'y'
358 in IPython user namespace:
359
360 ip.to_user_ns(dict(x=foo,y=bar))
361 """
362
363 # print 'vars given:',vars # dbg
364
365 # We need a dict of name/value pairs to do namespace updates.
366 if isinstance(vars,dict):
367 # If a dict was given, no need to change anything.
368 vdict = vars
369 elif isinstance(vars,basestring):
370 # If a string with names was given, get the caller's frame to
371 # evaluate the given names in
372 cf = sys._getframe(1)
373 vdict = {}
374 for name in vars.split():
375 try:
376 vdict[name] = eval(name,cf.f_globals,cf.f_locals)
377 except:
378 print ('could not get var. %s from %s' %
379 (name,cf.f_code.co_name))
380 else:
381 raise ValueError('vars must be a string or a dict')
382
383 # Propagate variables to user namespace
384 self.user_ns.update(vdict)
385
386 # And configure interactive visibility
387 config_ns = self.IP.user_config_ns
388 if interactive:
389 for name,val in vdict.iteritems():
390 config_ns.pop(name,None)
391 else:
392 for name,val in vdict.iteritems():
393 config_ns[name] = val
394
395 def expand_alias(self,line):
396 """ Expand an alias in the command line
397
398 Returns the provided command line, possibly with the first word
399 (command) translated according to alias expansion rules.
400
401 [ipython]|16> _ip.expand_aliases("np myfile.txt")
402 <16> 'q:/opt/np/notepad++.exe myfile.txt'
403 """
404
405 pre,fn,rest = self.IP.split_user_input(line)
406 res = pre + self.IP.expand_aliases(fn,rest)
407 return res
408
409 def itpl(self, s, depth = 1):
410 """ Expand Itpl format string s.
411
412 Only callable from command line (i.e. prefilter results);
413 If you use in your scripts, you need to use a bigger depth!
414 """
415 return self.IP.var_expand(s, depth)
416
417 def defalias(self, name, cmd):
418 """ Define a new alias
419
420 _ip.defalias('bb','bldmake bldfiles')
421
422 Creates a new alias named 'bb' in ipython user namespace
423 """
424
425 self.dbg.check_hotname(name)
426
427 if name in self.IP.alias_table:
428 self.dbg.debug_stack("Alias redefinition: '%s' => '%s' (old '%s')"
429 % (name, cmd, self.IP.alias_table[name]))
430
431 if callable(cmd):
432 self.IP.alias_table[name] = cmd
433 from IPython.core import shadowns
434 setattr(shadowns, name,cmd)
435 return
436
437 if isinstance(cmd,basestring):
438 nargs = cmd.count('%s')
439 if nargs>0 and cmd.find('%l')>=0:
440 raise Exception('The %s and %l specifiers are mutually '
441 'exclusive in alias definitions.')
442
443 self.IP.alias_table[name] = (nargs,cmd)
444 return
445
446 # just put it in - it's probably (0,'foo')
447 self.IP.alias_table[name] = cmd
448
449 def defmacro(self, *args):
450 """ Define a new macro
451
452 2 forms of calling:
453
454 mac = _ip.defmacro('print "hello"\nprint "world"')
455
456 (doesn't put the created macro on user namespace)
457
458 _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb')
459
460 (creates a macro named 'build' in user namespace)
461 """
462
463 from IPython.core import macro
464
465 if len(args) == 1:
466 return macro.Macro(args[0])
467 elif len(args) == 2:
468 self.user_ns[args[0]] = macro.Macro(args[1])
469 else:
470 return Exception("_ip.defmacro must be called with 1 or 2 arguments")
471
472 def set_next_input(self, s):
473 """ Sets the 'default' input string for the next command line.
474
475 Requires readline.
476
477 Example:
478
479 [D:\ipython]|1> _ip.set_next_input("Hello Word")
480 [D:\ipython]|2> Hello Word_ # cursor is here
481 """
482
483 self.IP.rl_next_input = s
484
485 def load(self, mod):
486 """ Load an extension.
487
488 Some modules should (or must) be 'load()':ed, rather than just imported.
489
490 Loading will do:
491
492 - run init_ipython(ip)
493 - run ipython_firstrun(ip)
494 """
495
496 if mod in self.extensions:
497 # just to make sure we don't init it twice
498 # note that if you 'load' a module that has already been
499 # imported, init_ipython gets run anyway
500
501 return self.extensions[mod]
502 __import__(mod)
503 m = sys.modules[mod]
504 if hasattr(m,'init_ipython'):
505 m.init_ipython(self)
506
507 if hasattr(m,'ipython_firstrun'):
508 already_loaded = self.db.get('firstrun_done', set())
509 if mod not in already_loaded:
510 m.ipython_firstrun(self)
511 already_loaded.add(mod)
512 self.db['firstrun_done'] = already_loaded
513
514 self.extensions[mod] = m
515 return m
516
517
518 class DebugTools:
519 """ Used for debugging mishaps in api usage
520
521 So far, tracing redefinitions is supported.
522 """
523
524 def __init__(self, ip):
525 self.ip = ip
526 self.debugmode = False
527 self.hotnames = set()
528
529 def hotname(self, name_to_catch):
530 self.hotnames.add(name_to_catch)
531
532 def debug_stack(self, msg = None):
533 if not self.debugmode:
534 return
535
536 import traceback
537 if msg is not None:
538 print '====== %s ========' % msg
539 traceback.print_stack()
540
541 def check_hotname(self,name):
542 if name in self.hotnames:
543 self.debug_stack( "HotName '%s' caught" % name)
544
545
546 def launch_new_instance(user_ns = None,shellclass = None):
547 """ Make and start a new ipython instance.
548
549 This can be called even without having an already initialized
550 ipython session running.
551
552 This is also used as the egg entry point for the 'ipython' script.
553
554 """
555 ses = make_session(user_ns,shellclass)
556 ses.mainloop()
557
558
559 def make_user_ns(user_ns = None):
560 """Return a valid user interactive namespace.
561
562 This builds a dict with the minimal information needed to operate as a
563 valid IPython user namespace, which you can pass to the various embedding
564 classes in ipython.
565
566 This API is currently deprecated. Use ipapi.make_user_namespaces() instead
567 to make both the local and global namespace objects simultaneously.
568
569 :Parameters:
570 user_ns : dict-like, optional
571 The current user namespace. The items in this namespace should be
572 included in the output. If None, an appropriate blank namespace
573 should be created.
574
575 :Returns:
576 A dictionary-like object to be used as the local namespace of the
577 interpreter.
578 """
579
580 raise NotImplementedError
581
582
583 def make_user_global_ns(ns = None):
584 """Return a valid user global namespace.
585
586 Similar to make_user_ns(), but global namespaces are really only needed in
587 embedded applications, where there is a distinction between the user's
588 interactive namespace and the global one where ipython is running.
589
590 This API is currently deprecated. Use ipapi.make_user_namespaces() instead
591 to make both the local and global namespace objects simultaneously.
592
593 :Parameters:
594 ns : dict, optional
595 The current user global namespace. The items in this namespace
596 should be included in the output. If None, an appropriate blank
597 namespace should be created.
598
599 :Returns:
600 A true dict to be used as the global namespace of the interpreter.
601 """
602
603 raise NotImplementedError
604
605 # Record the true objects in order to be able to test if the user has overridden
606 # these API functions.
607 _make_user_ns = make_user_ns
608 _make_user_global_ns = make_user_global_ns
609
29
30 from IPython.core.error import TryNext, UsageError
31 from IPython.core.component import Component
32 from warnings import warn
610
33
611 def make_user_namespaces(user_ns = None, user_global_ns = None):
34 #-----------------------------------------------------------------------------
612 """Return a valid local and global user interactive namespaces.
35 # Classes and functions
36 #-----------------------------------------------------------------------------
613
37
614 This builds a dict with the minimal information needed to operate as a
38 msg = """
615 valid IPython user namespace, which you can pass to the various embedding
39 This module (IPython.core.ipapi) is being deprecated. For now, all we
616 classes in ipython. The default implementation returns the same dict for
40 offer here is the ``get`` function for getting the most recently created
617 both the locals and the globals to allow functions to refer to variables in
41 InteractiveShell instance."""
618 the namespace. Customized implementations can return different dicts. The
619 locals dictionary can actually be anything following the basic mapping
620 protocol of a dict, but the globals dict must be a true dict, not even
621 a subclass. It is recommended that any custom object for the locals
622 namespace synchronize with the globals dict somehow.
623
42
624 Raises TypeError if the provided globals namespace is not a true dict.
43 warn(msg, category=DeprecationWarning, stacklevel=1)
625
44
626 :Parameters:
627 user_ns : dict-like, optional
628 The current user namespace. The items in this namespace should be
629 included in the output. If None, an appropriate blank namespace
630 should be created.
631 user_global_ns : dict, optional
632 The current user global namespace. The items in this namespace
633 should be included in the output. If None, an appropriate blank
634 namespace should be created.
635
45
636 :Returns:
46 def get():
637 A tuple pair of dictionary-like object to be used as the local namespace
47 """Get the most recently created InteractiveShell instance."""
638 of the interpreter and a dict to be used as the global namespace.
48 insts = Component.get_instances(name='__IP')
639 """
49 most_recent = insts[0]
50 for inst in insts[1:]:
51 if inst.created > most_recent.created:
52 most_recent = inst
53 return most_recent.getapi()
640
54
641 if user_ns is None:
642 if make_user_ns is not _make_user_ns:
643 # Old API overridden.
644 # FIXME: Issue DeprecationWarning, or just let the old API live on?
645 user_ns = make_user_ns(user_ns)
646 else:
647 # Set __name__ to __main__ to better match the behavior of the
648 # normal interpreter.
649 user_ns = {'__name__' :'__main__',
650 '__builtins__' : __builtin__,
651 }
652 else:
653 user_ns.setdefault('__name__','__main__')
654 user_ns.setdefault('__builtins__',__builtin__)
655
55
656 if user_global_ns is None:
657 if make_user_global_ns is not _make_user_global_ns:
658 # Old API overridden.
659 user_global_ns = make_user_global_ns(user_global_ns)
660 else:
661 user_global_ns = user_ns
662 if type(user_global_ns) is not dict:
663 raise TypeError("user_global_ns must be a true dict; got %r"
664 % type(user_global_ns))
665
56
666 return user_ns, user_global_ns
667
57
668
58
669 def make_session(user_ns = None, shellclass = None):
670 """Makes, but does not launch an IPython session.
671
672 Later on you can call obj.mainloop() on the returned object.
673
59
674 Inputs:
675
60
676 - user_ns(None): a dict to be used as the user's namespace with initial
677 data.
678
679 WARNING: This should *not* be run when a session exists already."""
680
61
681 import IPython.core.shell
682 if shellclass is None:
683 return IPython.core.shell.start(user_ns)
684 return shellclass(user_ns = user_ns)
@@ -34,17 +34,19 b' import tempfile'
34
34
35 from IPython.core import ultratb
35 from IPython.core import ultratb
36 from IPython.core import debugger, oinspect
36 from IPython.core import debugger, oinspect
37 from IPython.core import ipapi
38 from IPython.core import shadowns
37 from IPython.core import shadowns
39 from IPython.core import history as ipcorehist
38 from IPython.core import history as ipcorehist
40 from IPython.core import prefilter
39 from IPython.core import prefilter
40 from IPython.core.autocall import IPyAutocall
41 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
41 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
42 from IPython.core.logger import Logger
42 from IPython.core.logger import Logger
43 from IPython.core.magic import Magic
43 from IPython.core.magic import Magic
44 from IPython.core.prompts import CachedOutput
44 from IPython.core.prompts import CachedOutput
45 from IPython.core.page import page
45 from IPython.core.component import Component
46 from IPython.core.component import Component
46 from IPython.core.oldusersetup import user_setup
47 from IPython.core.oldusersetup import user_setup
47 from IPython.core.usage import interactive_usage, default_banner
48 from IPython.core.usage import interactive_usage, default_banner
49 from IPython.core.error import TryNext, UsageError
48
50
49 from IPython.extensions import pickleshare
51 from IPython.extensions import pickleshare
50 from IPython.external.Itpl import ItplNS
52 from IPython.external.Itpl import ItplNS
@@ -319,10 +321,6 b' class InteractiveShell(Component, Magic):'
319 self.init_hooks()
321 self.init_hooks()
320 self.init_pushd_popd_magic()
322 self.init_pushd_popd_magic()
321 self.init_traceback_handlers(custom_exceptions)
323 self.init_traceback_handlers(custom_exceptions)
322
323 # Produce a public API instance
324 self.api = ipapi.IPApi(self)
325
326 self.init_namespaces()
324 self.init_namespaces()
327 self.init_logger()
325 self.init_logger()
328 self.init_aliases()
326 self.init_aliases()
@@ -343,7 +341,6 b' class InteractiveShell(Component, Magic):'
343 self.init_magics()
341 self.init_magics()
344 self.init_pdb()
342 self.init_pdb()
345 self.hooks.late_startup_hook()
343 self.hooks.late_startup_hook()
346 self.init_exec_commands()
347
344
348 #-------------------------------------------------------------------------
345 #-------------------------------------------------------------------------
349 # Traitlet changed handlers
346 # Traitlet changed handlers
@@ -485,7 +482,7 b' class InteractiveShell(Component, Magic):'
485 # These routines return properly built dicts as needed by the rest of
482 # These routines return properly built dicts as needed by the rest of
486 # the code, and can also be used by extension writers to generate
483 # the code, and can also be used by extension writers to generate
487 # properly initialized namespaces.
484 # properly initialized namespaces.
488 user_ns, user_global_ns = ipapi.make_user_namespaces(user_ns,
485 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
489 user_global_ns)
486 user_global_ns)
490
487
491 # Assign namespaces
488 # Assign namespaces
@@ -576,6 +573,55 b' class InteractiveShell(Component, Magic):'
576 else:
573 else:
577 sys.modules[main_name] = FakeModule(self.user_ns)
574 sys.modules[main_name] = FakeModule(self.user_ns)
578
575
576 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
577 """Return a valid local and global user interactive namespaces.
578
579 This builds a dict with the minimal information needed to operate as a
580 valid IPython user namespace, which you can pass to the various
581 embedding classes in ipython. The default implementation returns the
582 same dict for both the locals and the globals to allow functions to
583 refer to variables in the namespace. Customized implementations can
584 return different dicts. The locals dictionary can actually be anything
585 following the basic mapping protocol of a dict, but the globals dict
586 must be a true dict, not even a subclass. It is recommended that any
587 custom object for the locals namespace synchronize with the globals
588 dict somehow.
589
590 Raises TypeError if the provided globals namespace is not a true dict.
591
592 :Parameters:
593 user_ns : dict-like, optional
594 The current user namespace. The items in this namespace should
595 be included in the output. If None, an appropriate blank
596 namespace should be created.
597 user_global_ns : dict, optional
598 The current user global namespace. The items in this namespace
599 should be included in the output. If None, an appropriate
600 blank namespace should be created.
601
602 :Returns:
603 A tuple pair of dictionary-like object to be used as the local namespace
604 of the interpreter and a dict to be used as the global namespace.
605 """
606
607 if user_ns is None:
608 # Set __name__ to __main__ to better match the behavior of the
609 # normal interpreter.
610 user_ns = {'__name__' :'__main__',
611 '__builtins__' : __builtin__,
612 }
613 else:
614 user_ns.setdefault('__name__','__main__')
615 user_ns.setdefault('__builtins__',__builtin__)
616
617 if user_global_ns is None:
618 user_global_ns = user_ns
619 if type(user_global_ns) is not dict:
620 raise TypeError("user_global_ns must be a true dict; got %r"
621 % type(user_global_ns))
622
623 return user_ns, user_global_ns
624
579 def init_history(self):
625 def init_history(self):
580 # List of input with multi-line handling.
626 # List of input with multi-line handling.
581 self.input_hist = InputList()
627 self.input_hist = InputList()
@@ -933,23 +979,55 b' class InteractiveShell(Component, Magic):'
933 # self.call_pdb is a property
979 # self.call_pdb is a property
934 self.call_pdb = self.pdb
980 self.call_pdb = self.pdb
935
981
936 def init_exec_commands(self):
982 # def init_exec_commands(self):
937 for cmd in self.config.EXECUTE:
983 # for cmd in self.config.EXECUTE:
938 print "execute:", cmd
984 # print "execute:", cmd
939 self.api.runlines(cmd)
985 # self.api.runlines(cmd)
940
986 #
941 batchrun = False
987 # batchrun = False
942 if self.config.has_key('EXECFILE'):
988 # if self.config.has_key('EXECFILE'):
943 for batchfile in [path(arg) for arg in self.config.EXECFILE
989 # for batchfile in [path(arg) for arg in self.config.EXECFILE
944 if arg.lower().endswith('.ipy')]:
990 # if arg.lower().endswith('.ipy')]:
945 if not batchfile.isfile():
991 # if not batchfile.isfile():
946 print "No such batch file:", batchfile
992 # print "No such batch file:", batchfile
947 continue
993 # continue
948 self.api.runlines(batchfile.text())
994 # self.api.runlines(batchfile.text())
949 batchrun = True
995 # batchrun = True
950 # without -i option, exit after running the batch file
996 # # without -i option, exit after running the batch file
951 if batchrun and not self.interactive:
997 # if batchrun and not self.interactive:
952 self.ask_exit()
998 # self.ask_exit()
999
1000 # def load(self, mod):
1001 # """ Load an extension.
1002 #
1003 # Some modules should (or must) be 'load()':ed, rather than just imported.
1004 #
1005 # Loading will do:
1006 #
1007 # - run init_ipython(ip)
1008 # - run ipython_firstrun(ip)
1009 # """
1010 #
1011 # if mod in self.extensions:
1012 # # just to make sure we don't init it twice
1013 # # note that if you 'load' a module that has already been
1014 # # imported, init_ipython gets run anyway
1015 #
1016 # return self.extensions[mod]
1017 # __import__(mod)
1018 # m = sys.modules[mod]
1019 # if hasattr(m,'init_ipython'):
1020 # m.init_ipython(self)
1021 #
1022 # if hasattr(m,'ipython_firstrun'):
1023 # already_loaded = self.db.get('firstrun_done', set())
1024 # if mod not in already_loaded:
1025 # m.ipython_firstrun(self)
1026 # already_loaded.add(mod)
1027 # self.db['firstrun_done'] = already_loaded
1028 #
1029 # self.extensions[mod] = m
1030 # return m
953
1031
954 def init_namespaces(self):
1032 def init_namespaces(self):
955 """Initialize all user-visible namespaces to their minimum defaults.
1033 """Initialize all user-visible namespaces to their minimum defaults.
@@ -966,8 +1044,8 b' class InteractiveShell(Component, Magic):'
966 # The user namespace MUST have a pointer to the shell itself.
1044 # The user namespace MUST have a pointer to the shell itself.
967 self.user_ns[self.name] = self
1045 self.user_ns[self.name] = self
968
1046
969 # Store the public api instance
1047 # Store myself as the public api!!!
970 self.user_ns['_ip'] = self.api
1048 self.user_ns['_ip'] = self
971
1049
972 # make global variables for user access to the histories
1050 # make global variables for user access to the histories
973 self.user_ns['_ih'] = self.input_hist
1051 self.user_ns['_ih'] = self.input_hist
@@ -1015,10 +1093,9 b' class InteractiveShell(Component, Magic):'
1015 builtins_new = dict(__IPYTHON__ = self,
1093 builtins_new = dict(__IPYTHON__ = self,
1016 ip_set_hook = self.set_hook,
1094 ip_set_hook = self.set_hook,
1017 jobs = self.jobs,
1095 jobs = self.jobs,
1018 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
1096 # magic = self.magic,
1019 ipalias = wrap_deprecated(self.ipalias),
1097 ipalias = wrap_deprecated(self.ipalias),
1020 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
1098 # ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
1021 #_ip = self.api
1022 )
1099 )
1023 for biname,bival in builtins_new.items():
1100 for biname,bival in builtins_new.items():
1024 try:
1101 try:
@@ -1184,33 +1261,24 b' class InteractiveShell(Component, Magic):'
1184
1261
1185 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1262 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1186 'Control auto-activation of pdb at exceptions')
1263 'Control auto-activation of pdb at exceptions')
1187
1188 # These special functions get installed in the builtin namespace, to
1189 # provide programmatic (pure python) access to magics, aliases and system
1190 # calls. This is important for logging, user scripting, and more.
1191
1192 # We are basically exposing, via normal python functions, the three
1193 # mechanisms in which ipython offers special call modes (magics for
1194 # internal control, aliases for direct system access via pre-selected
1195 # names, and !cmd for calling arbitrary system commands).
1196
1264
1197 def ipmagic(self,arg_s):
1265 def magic(self,arg_s):
1198 """Call a magic function by name.
1266 """Call a magic function by name.
1199
1267
1200 Input: a string containing the name of the magic function to call and any
1268 Input: a string containing the name of the magic function to call and any
1201 additional arguments to be passed to the magic.
1269 additional arguments to be passed to the magic.
1202
1270
1203 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
1271 magic('name -opt foo bar') is equivalent to typing at the ipython
1204 prompt:
1272 prompt:
1205
1273
1206 In[1]: %name -opt foo bar
1274 In[1]: %name -opt foo bar
1207
1275
1208 To call a magic without arguments, simply use ipmagic('name').
1276 To call a magic without arguments, simply use magic('name').
1209
1277
1210 This provides a proper Python function to call IPython's magics in any
1278 This provides a proper Python function to call IPython's magics in any
1211 valid Python code you can type at the interpreter, including loops and
1279 valid Python code you can type at the interpreter, including loops and
1212 compound statements. It is added by IPython to the Python builtin
1280 compound statements.
1213 namespace upon initialization."""
1281 """
1214
1282
1215 args = arg_s.split(' ',1)
1283 args = arg_s.split(' ',1)
1216 magic_name = args[0]
1284 magic_name = args[0]
@@ -1227,6 +1295,44 b' class InteractiveShell(Component, Magic):'
1227 magic_args = self.var_expand(magic_args,1)
1295 magic_args = self.var_expand(magic_args,1)
1228 return fn(magic_args)
1296 return fn(magic_args)
1229
1297
1298 def define_magic(self, magicname, func):
1299 """Expose own function as magic function for ipython
1300
1301 def foo_impl(self,parameter_s=''):
1302 'My very own magic!. (Use docstrings, IPython reads them).'
1303 print 'Magic function. Passed parameter is between < >:'
1304 print '<%s>' % parameter_s
1305 print 'The self object is:',self
1306
1307 self.define_magic('foo',foo_impl)
1308 """
1309
1310 import new
1311 im = new.instancemethod(func,self, self.__class__)
1312 old = getattr(self, "magic_" + magicname, None)
1313 setattr(self, "magic_" + magicname, im)
1314 return old
1315
1316 def define_macro(self, name, themacro):
1317 """Define a new macro
1318
1319 Parameters
1320 ----------
1321 name : str
1322 The name of the macro.
1323 themacro : str or Macro
1324 The action to do upon invoking the macro. If a string, a new
1325 Macro object is created by passing the string to it.
1326 """
1327
1328 from IPython.core import macro
1329
1330 if isinstance(themacro, basestring):
1331 themacro = macro.Macro(themacro)
1332 if not isinstance(themacro, macro.Macro):
1333 raise ValueError('A macro must be a string or a Macro instance.')
1334 self.user_ns[name] = themacro
1335
1230 def define_alias(self, name, cmd):
1336 def define_alias(self, name, cmd):
1231 """ Define a new alias."""
1337 """ Define a new alias."""
1232
1338
@@ -1280,7 +1386,16 b' class InteractiveShell(Component, Magic):'
1280 """Make a system call, using IPython."""
1386 """Make a system call, using IPython."""
1281 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1387 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1282
1388
1283 ipsystem = system
1389 def ex(self, cmd):
1390 """Execute a normal python statement in user namespace."""
1391 exec cmd in self.user_ns
1392
1393 def ev(self, expr):
1394 """Evaluate python expression expr in user namespace.
1395
1396 Returns the result of evaluation
1397 """
1398 return eval(expr,self.user_ns)
1284
1399
1285 def getoutput(self, cmd):
1400 def getoutput(self, cmd):
1286 return getoutput(self.var_expand(cmd,depth=2),
1401 return getoutput(self.var_expand(cmd,depth=2),
@@ -1314,7 +1429,7 b' class InteractiveShell(Component, Magic):'
1314 In [9]: print x
1429 In [9]: print x
1315 hello
1430 hello
1316
1431
1317 In [10]: _ip.IP.complete('x.l')
1432 In [10]: _ip.complete('x.l')
1318 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1433 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1319 """
1434 """
1320
1435
@@ -1350,8 +1465,7 b' class InteractiveShell(Component, Magic):'
1350 These are ALL parameter-less aliases"""
1465 These are ALL parameter-less aliases"""
1351
1466
1352 for alias,cmd in self.auto_alias:
1467 for alias,cmd in self.auto_alias:
1353 self.getapi().defalias(alias,cmd)
1468 self.define_alias(alias,cmd)
1354
1355
1469
1356 def alias_table_validate(self,verbose=0):
1470 def alias_table_validate(self,verbose=0):
1357 """Update information about the alias table.
1471 """Update information about the alias table.
@@ -1365,7 +1479,20 b' class InteractiveShell(Component, Magic):'
1365 if verbose:
1479 if verbose:
1366 print ("Deleting alias <%s>, it's a Python "
1480 print ("Deleting alias <%s>, it's a Python "
1367 "keyword or builtin." % k)
1481 "keyword or builtin." % k)
1368
1482
1483 def set_next_input(self, s):
1484 """ Sets the 'default' input string for the next command line.
1485
1486 Requires readline.
1487
1488 Example:
1489
1490 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1491 [D:\ipython]|2> Hello Word_ # cursor is here
1492 """
1493
1494 self.rl_next_input = s
1495
1369 def set_autoindent(self,value=None):
1496 def set_autoindent(self,value=None):
1370 """Set the autoindent flag, checking for readline support.
1497 """Set the autoindent flag, checking for readline support.
1371
1498
@@ -1518,9 +1645,9 b' class InteractiveShell(Component, Magic):'
1518
1645
1519 In [10]: import IPython
1646 In [10]: import IPython
1520
1647
1521 In [11]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__)
1648 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
1522
1649
1523 In [12]: IPython.__file__ in _ip.IP._main_ns_cache
1650 In [12]: IPython.__file__ in _ip._main_ns_cache
1524 Out[12]: True
1651 Out[12]: True
1525 """
1652 """
1526 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
1653 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
@@ -1535,14 +1662,14 b' class InteractiveShell(Component, Magic):'
1535
1662
1536 In [15]: import IPython
1663 In [15]: import IPython
1537
1664
1538 In [16]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__)
1665 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
1539
1666
1540 In [17]: len(_ip.IP._main_ns_cache) > 0
1667 In [17]: len(_ip._main_ns_cache) > 0
1541 Out[17]: True
1668 Out[17]: True
1542
1669
1543 In [18]: _ip.IP.clear_main_mod_cache()
1670 In [18]: _ip.clear_main_mod_cache()
1544
1671
1545 In [19]: len(_ip.IP._main_ns_cache) == 0
1672 In [19]: len(_ip._main_ns_cache) == 0
1546 Out[19]: True
1673 Out[19]: True
1547 """
1674 """
1548 self._main_ns_cache.clear()
1675 self._main_ns_cache.clear()
@@ -1572,7 +1699,7 b' class InteractiveShell(Component, Magic):'
1572 try:
1699 try:
1573 self.hooks.fix_error_editor(e.filename,
1700 self.hooks.fix_error_editor(e.filename,
1574 int0(e.lineno),int0(e.offset),e.msg)
1701 int0(e.lineno),int0(e.offset),e.msg)
1575 except ipapi.TryNext:
1702 except TryNext:
1576 warn('Could not open editor')
1703 warn('Could not open editor')
1577 return False
1704 return False
1578 return True
1705 return True
@@ -1686,7 +1813,7 b' class InteractiveShell(Component, Magic):'
1686
1813
1687 if etype is SyntaxError:
1814 if etype is SyntaxError:
1688 self.showsyntaxerror(filename)
1815 self.showsyntaxerror(filename)
1689 elif etype is ipapi.UsageError:
1816 elif etype is UsageError:
1690 print "UsageError:", value
1817 print "UsageError:", value
1691 else:
1818 else:
1692 # WARNING: these variables are somewhat deprecated and not
1819 # WARNING: these variables are somewhat deprecated and not
@@ -1743,7 +1870,7 b' class InteractiveShell(Component, Magic):'
1743 This emulates Python's -c option."""
1870 This emulates Python's -c option."""
1744
1871
1745 #sys.argv = ['-c']
1872 #sys.argv = ['-c']
1746 self.push(self.prefilter(self.c, False))
1873 self.push_line(self.prefilter(self.c, False))
1747 if not self.interactive:
1874 if not self.interactive:
1748 self.ask_exit()
1875 self.ask_exit()
1749
1876
@@ -1856,7 +1983,7 b' class InteractiveShell(Component, Magic):'
1856 self.input_hist_raw.append('%s\n' % line)
1983 self.input_hist_raw.append('%s\n' % line)
1857
1984
1858
1985
1859 self.more = self.push(lineout)
1986 self.more = self.push_line(lineout)
1860 if (self.SyntaxTB.last_syntax_error and
1987 if (self.SyntaxTB.last_syntax_error and
1861 self.autoedit_syntax):
1988 self.autoedit_syntax):
1862 self.edit_syntax_error()
1989 self.edit_syntax_error()
@@ -1951,7 +2078,7 b' class InteractiveShell(Component, Magic):'
1951 # asynchronously by signal handlers, for example.
2078 # asynchronously by signal handlers, for example.
1952 self.showtraceback()
2079 self.showtraceback()
1953 else:
2080 else:
1954 more = self.push(line)
2081 more = self.push_line(line)
1955 if (self.SyntaxTB.last_syntax_error and
2082 if (self.SyntaxTB.last_syntax_error and
1956 self.autoedit_syntax):
2083 self.autoedit_syntax):
1957 self.edit_syntax_error()
2084 self.edit_syntax_error()
@@ -1983,8 +2110,22 b' class InteractiveShell(Component, Magic):'
1983 """
2110 """
1984 self.showtraceback((etype,value,tb),tb_offset=0)
2111 self.showtraceback((etype,value,tb),tb_offset=0)
1985
2112
1986 def expand_aliases(self,fn,rest):
2113 def expand_alias(self, line):
1987 """ Expand multiple levels of aliases:
2114 """ Expand an alias in the command line
2115
2116 Returns the provided command line, possibly with the first word
2117 (command) translated according to alias expansion rules.
2118
2119 [ipython]|16> _ip.expand_aliases("np myfile.txt")
2120 <16> 'q:/opt/np/notepad++.exe myfile.txt'
2121 """
2122
2123 pre,fn,rest = self.split_user_input(line)
2124 res = pre + self.expand_aliases(fn, rest)
2125 return res
2126
2127 def expand_aliases(self, fn, rest):
2128 """Expand multiple levels of aliases:
1988
2129
1989 if:
2130 if:
1990
2131
@@ -2091,18 +2232,114 b' class InteractiveShell(Component, Magic):'
2091 else:
2232 else:
2092 self.indent_current_nsp = 0
2233 self.indent_current_nsp = 0
2093
2234
2094 def runlines(self,lines):
2235 def push(self, variables, interactive=True):
2236 """Inject a group of variables into the IPython user namespace.
2237
2238 Parameters
2239 ----------
2240 variables : dict, str or list/tuple of str
2241 The variables to inject into the user's namespace. If a dict,
2242 a simple update is done. If a str, the string is assumed to
2243 have variable names separated by spaces. A list/tuple of str
2244 can also be used to give the variable names. If just the variable
2245 names are give (list/tuple/str) then the variable values looked
2246 up in the callers frame.
2247 interactive : bool
2248 If True (default), the variables will be listed with the ``who``
2249 magic.
2250 """
2251 vdict = None
2252
2253 # We need a dict of name/value pairs to do namespace updates.
2254 if isinstance(variables, dict):
2255 vdict = variables
2256 elif isinstance(variables, (basestring, list, tuple)):
2257 if isinstance(variables, basestring):
2258 vlist = variables.split()
2259 else:
2260 vlist = variables
2261 vdict = {}
2262 cf = sys._getframe(1)
2263 for name in vlist:
2264 try:
2265 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
2266 except:
2267 print ('Could not get variable %s from %s' %
2268 (name,cf.f_code.co_name))
2269 else:
2270 raise ValueError('variables must be a dict/str/list/tuple')
2271
2272 # Propagate variables to user namespace
2273 self.user_ns.update(vdict)
2274
2275 # And configure interactive visibility
2276 config_ns = self.user_config_ns
2277 if interactive:
2278 for name, val in vdict.iteritems():
2279 config_ns.pop(name, None)
2280 else:
2281 for name,val in vdict.iteritems():
2282 config_ns[name] = val
2283
2284 def cleanup_ipy_script(self, script):
2285 """Make a script safe for self.runlines()
2286
2287 Notes
2288 -----
2289 This was copied over from the old ipapi and probably can be done
2290 away with once we move to block based interpreter.
2291
2292 - Removes empty lines Suffixes all indented blocks that end with
2293 - unindented lines with empty lines
2294 """
2295
2296 res = []
2297 lines = script.splitlines()
2298
2299 level = 0
2300 for l in lines:
2301 lstripped = l.lstrip()
2302 stripped = l.strip()
2303 if not stripped:
2304 continue
2305 newlevel = len(l) - len(lstripped)
2306 def is_secondary_block_start(s):
2307 if not s.endswith(':'):
2308 return False
2309 if (s.startswith('elif') or
2310 s.startswith('else') or
2311 s.startswith('except') or
2312 s.startswith('finally')):
2313 return True
2314
2315 if level > 0 and newlevel == 0 and \
2316 not is_secondary_block_start(stripped):
2317 # add empty line
2318 res.append('')
2319
2320 res.append(l)
2321 level = newlevel
2322 return '\n'.join(res) + '\n'
2323
2324 def runlines(self, lines, clean=False):
2095 """Run a string of one or more lines of source.
2325 """Run a string of one or more lines of source.
2096
2326
2097 This method is capable of running a string containing multiple source
2327 This method is capable of running a string containing multiple source
2098 lines, as if they had been entered at the IPython prompt. Since it
2328 lines, as if they had been entered at the IPython prompt. Since it
2099 exposes IPython's processing machinery, the given strings can contain
2329 exposes IPython's processing machinery, the given strings can contain
2100 magic calls (%magic), special shell access (!cmd), etc."""
2330 magic calls (%magic), special shell access (!cmd), etc.
2331 """
2332
2333 if isinstance(lines, (list, tuple)):
2334 lines = '\n'.join(lines)
2335
2336 if clean:
2337 lines = self.cleanup_ipy_script(lines)
2101
2338
2102 # We must start with a clean buffer, in case this is run from an
2339 # We must start with a clean buffer, in case this is run from an
2103 # interactive IPython session (via a magic, for example).
2340 # interactive IPython session (via a magic, for example).
2104 self.resetbuffer()
2341 self.resetbuffer()
2105 lines = lines.split('\n')
2342 lines = lines.splitlines()
2106 more = 0
2343 more = 0
2107
2344
2108 for line in lines:
2345 for line in lines:
@@ -2113,7 +2350,7 b' class InteractiveShell(Component, Magic):'
2113 if line or more:
2350 if line or more:
2114 # push to raw history, so hist line numbers stay in sync
2351 # push to raw history, so hist line numbers stay in sync
2115 self.input_hist_raw.append("# " + line + "\n")
2352 self.input_hist_raw.append("# " + line + "\n")
2116 more = self.push(self.prefilter(line,more))
2353 more = self.push_line(self.prefilter(line,more))
2117 # IPython's runsource returns None if there was an error
2354 # IPython's runsource returns None if there was an error
2118 # compiling the code. This allows us to stop processing right
2355 # compiling the code. This allows us to stop processing right
2119 # away, so the user gets the error message at the right place.
2356 # away, so the user gets the error message at the right place.
@@ -2124,7 +2361,7 b' class InteractiveShell(Component, Magic):'
2124 # final newline in case the input didn't have it, so that the code
2361 # final newline in case the input didn't have it, so that the code
2125 # actually does get executed
2362 # actually does get executed
2126 if more:
2363 if more:
2127 self.push('\n')
2364 self.push_line('\n')
2128
2365
2129 def runsource(self, source, filename='<input>', symbol='single'):
2366 def runsource(self, source, filename='<input>', symbol='single'):
2130 """Compile and run some source in the interpreter.
2367 """Compile and run some source in the interpreter.
@@ -2232,7 +2469,7 b' class InteractiveShell(Component, Magic):'
2232 self.code_to_run = None
2469 self.code_to_run = None
2233 return outflag
2470 return outflag
2234
2471
2235 def push(self, line):
2472 def push_line(self, line):
2236 """Push a line to the interpreter.
2473 """Push a line to the interpreter.
2237
2474
2238 The line should not have a trailing newline; it may have
2475 The line should not have a trailing newline; it may have
@@ -2442,7 +2679,7 b' class InteractiveShell(Component, Magic):'
2442 # print "=>",tgt #dbg
2679 # print "=>",tgt #dbg
2443 if callable(tgt):
2680 if callable(tgt):
2444 if '$' in line_info.line:
2681 if '$' in line_info.line:
2445 call_meth = '(_ip, _ip.itpl(%s))'
2682 call_meth = '(_ip, _ip.var_expand(%s))'
2446 else:
2683 else:
2447 call_meth = '(_ip,%s)'
2684 call_meth = '(_ip,%s)'
2448 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2685 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
@@ -2510,7 +2747,7 b' class InteractiveShell(Component, Magic):'
2510 self.log(line,line,continue_prompt)
2747 self.log(line,line,continue_prompt)
2511 return line
2748 return line
2512
2749
2513 force_auto = isinstance(obj, ipapi.IPyAutocall)
2750 force_auto = isinstance(obj, IPyAutocall)
2514 auto_rewrite = True
2751 auto_rewrite = True
2515
2752
2516 if pre == self.ESC_QUOTE:
2753 if pre == self.ESC_QUOTE:
@@ -2593,18 +2830,6 b' class InteractiveShell(Component, Magic):'
2593 # If the code compiles ok, we should handle it normally
2830 # If the code compiles ok, we should handle it normally
2594 return self.handle_normal(line_info)
2831 return self.handle_normal(line_info)
2595
2832
2596 def getapi(self):
2597 """ Get an IPApi object for this shell instance
2598
2599 Getting an IPApi object is always preferable to accessing the shell
2600 directly, but this holds true especially for extensions.
2601
2602 It should always be possible to implement an extension with IPApi
2603 alone. If not, contact maintainer to request an addition.
2604
2605 """
2606 return self.api
2607
2608 def handle_emacs(self, line_info):
2833 def handle_emacs(self, line_info):
2609 """Handle input lines marked by python-mode."""
2834 """Handle input lines marked by python-mode."""
2610
2835
@@ -7,10 +7,8 b''
7 # the file COPYING, distributed as part of this software.
7 # the file COPYING, distributed as part of this software.
8 #*****************************************************************************
8 #*****************************************************************************
9
9
10 from IPython.core import ipapi
11
12 from IPython.utils.genutils import Term
10 from IPython.utils.genutils import Term
13 from IPython.core.ipapi import IPyAutocall
11 from IPython.core.autocall import IPyAutocall
14
12
15 class Macro(IPyAutocall):
13 class Macro(IPyAutocall):
16 """Simple class to store the value of macros as strings.
14 """Simple class to store the value of macros as strings.
@@ -45,16 +45,17 b' except ImportError:'
45 import IPython
45 import IPython
46 from IPython.utils import wildcard
46 from IPython.utils import wildcard
47 from IPython.core import debugger, oinspect
47 from IPython.core import debugger, oinspect
48 from IPython.core.error import TryNext
48 from IPython.core.fakemodule import FakeModule
49 from IPython.core.fakemodule import FakeModule
49 from IPython.external.Itpl import Itpl, itpl, printpl,itplns
50 from IPython.external.Itpl import Itpl, itpl, printpl,itplns
50 from IPython.utils.PyColorize import Parser
51 from IPython.utils.PyColorize import Parser
51 from IPython.utils.ipstruct import Struct
52 from IPython.utils.ipstruct import Struct
52 from IPython.core.macro import Macro
53 from IPython.core.macro import Macro
53 from IPython.utils.genutils import *
54 from IPython.utils.genutils import *
55 from IPython.core.page import page
54 from IPython.utils import platutils
56 from IPython.utils import platutils
55 import IPython.utils.generics
57 import IPython.utils.generics
56 from IPython.core import ipapi
58 from IPython.core.error import UsageError
57 from IPython.core.ipapi import UsageError
58 from IPython.testing import decorators as testdec
59 from IPython.testing import decorators as testdec
59
60
60 #***************************************************************************
61 #***************************************************************************
@@ -470,8 +471,8 b' ipythonrc file, placing a line like:'
470
471
471 will define %pf as a new name for %profile.
472 will define %pf as a new name for %profile.
472
473
473 You can also call magics in code using the ipmagic() function, which IPython
474 You can also call magics in code using the magic() function, which IPython
474 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
475 automatically adds to the builtin namespace. Type 'magic?' for details.
475
476
476 For a list of the available magic functions, use %lsmagic. For a description
477 For a list of the available magic functions, use %lsmagic. For a description
477 of any of them, type %magic_name?, e.g. '%cd?'.
478 of any of them, type %magic_name?, e.g. '%cd?'.
@@ -720,7 +721,7 b' Currently the magic system has the following functions:\\n"""'
720 try:
721 try:
721 IPython.utils.generics.inspect_object(info.obj)
722 IPython.utils.generics.inspect_object(info.obj)
722 return
723 return
723 except ipapi.TryNext:
724 except TryNext:
724 pass
725 pass
725 # Get the docstring of the class property if it exists.
726 # Get the docstring of the class property if it exists.
726 path = oname.split('.')
727 path = oname.split('.')
@@ -1571,7 +1572,7 b' Currently the magic system has the following functions:\\n"""'
1571 return
1572 return
1572
1573
1573 if filename.lower().endswith('.ipy'):
1574 if filename.lower().endswith('.ipy'):
1574 self.api.runlines(open(filename).read())
1575 self.runlines(open(filename).read(), clean=True)
1575 return
1576 return
1576
1577
1577 # Control the response to exit() calls made by the script being run
1578 # Control the response to exit() calls made by the script being run
@@ -2063,7 +2064,7 b' Currently the magic system has the following functions:\\n"""'
2063 #print 'rng',ranges # dbg
2064 #print 'rng',ranges # dbg
2064 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2065 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2065 macro = Macro(lines)
2066 macro = Macro(lines)
2066 self.shell.user_ns.update({name:macro})
2067 self.shell.define_macro(name, macro)
2067 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2068 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2068 print 'Macro contents:'
2069 print 'Macro contents:'
2069 print macro,
2070 print macro,
@@ -2393,7 +2394,7 b' Currently the magic system has the following functions:\\n"""'
2393 sys.stdout.flush()
2394 sys.stdout.flush()
2394 try:
2395 try:
2395 self.shell.hooks.editor(filename,lineno)
2396 self.shell.hooks.editor(filename,lineno)
2396 except ipapi.TryNext:
2397 except TryNext:
2397 warn('Could not open editor')
2398 warn('Could not open editor')
2398 return
2399 return
2399
2400
@@ -2685,12 +2686,9 b' Defaulting color scheme to \'NoColor\'"""'
2685 This function also resets the root module cache of module completer,
2686 This function also resets the root module cache of module completer,
2686 used on slow filesystems.
2687 used on slow filesystems.
2687 """
2688 """
2688
2689
2690 ip = self.api
2691
2689
2692 # for the benefit of module completer in ipy_completers.py
2690 # for the benefit of module completer in ipy_completers.py
2693 del ip.db['rootmodules']
2691 del self.db['rootmodules']
2694
2692
2695 path = [os.path.abspath(os.path.expanduser(p)) for p in
2693 path = [os.path.abspath(os.path.expanduser(p)) for p in
2696 os.environ.get('PATH','').split(os.pathsep)]
2694 os.environ.get('PATH','').split(os.pathsep)]
@@ -2745,7 +2743,7 b' Defaulting color scheme to \'NoColor\'"""'
2745 # no, we don't want them. if %rehashx clobbers them, good,
2743 # no, we don't want them. if %rehashx clobbers them, good,
2746 # we'll probably get better versions
2744 # we'll probably get better versions
2747 # self.shell.init_auto_alias()
2745 # self.shell.init_auto_alias()
2748 db = ip.db
2746 db = self.db
2749 db['syscmdlist'] = syscmdlist
2747 db['syscmdlist'] = syscmdlist
2750 finally:
2748 finally:
2751 os.chdir(savedir)
2749 os.chdir(savedir)
@@ -3439,7 +3437,7 b' Defaulting color scheme to \'NoColor\'"""'
3439 ipinstallation = path(IPython.__file__).dirname()
3437 ipinstallation = path(IPython.__file__).dirname()
3440 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'utils' / 'upgradedir.py')
3438 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'utils' / 'upgradedir.py')
3441 src_config = ipinstallation / 'config' / 'userconfig'
3439 src_config = ipinstallation / 'config' / 'userconfig'
3442 userdir = path(ip.options.IPYTHONDIR)
3440 userdir = path(ip.config.IPYTHONDIR)
3443 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3441 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3444 print ">",cmd
3442 print ">",cmd
3445 shell(cmd)
3443 shell(cmd)
@@ -28,7 +28,8 b' import types'
28
28
29 # IPython's own
29 # IPython's own
30 from IPython.utils import PyColorize
30 from IPython.utils import PyColorize
31 from IPython.utils.genutils import page,indent,Term
31 from IPython.utils.genutils import indent, Term
32 from IPython.core.page import page
32 from IPython.external.Itpl import itpl
33 from IPython.external.Itpl import itpl
33 from IPython.utils.wildcard import list_namespace
34 from IPython.utils.wildcard import list_namespace
34 from IPython.utils.coloransi import *
35 from IPython.utils.coloransi import *
@@ -8,7 +8,8 b' transforming work.'
8 __docformat__ = "restructuredtext en"
8 __docformat__ = "restructuredtext en"
9
9
10 import re
10 import re
11 from IPython.core import ipapi
11 from IPython.core.autocall import IPyAutocall
12
12
13
13 class LineInfo(object):
14 class LineInfo(object):
14 """A single line of input and associated info.
15 """A single line of input and associated info.
@@ -178,8 +179,8 b' def checkEmacs(l_info,ip):'
178 def checkIPyAutocall(l_info,ip):
179 def checkIPyAutocall(l_info,ip):
179 "Instances of IPyAutocall in user_ns get autocalled immediately"
180 "Instances of IPyAutocall in user_ns get autocalled immediately"
180 obj = ip.user_ns.get(l_info.iFun, None)
181 obj = ip.user_ns.get(l_info.iFun, None)
181 if isinstance(obj, ipapi.IPyAutocall):
182 if isinstance(obj, IPyAutocall):
182 obj.set_ip(ip.api)
183 obj.set_ip(ip)
183 return ip.handle_auto
184 return ip.handle_auto
184 else:
185 else:
185 return None
186 return None
@@ -23,7 +23,7 b' import time'
23 from IPython.utils import coloransi
23 from IPython.utils import coloransi
24 from IPython.core import release
24 from IPython.core import release
25 from IPython.external.Itpl import ItplNS
25 from IPython.external.Itpl import ItplNS
26 from IPython.core.ipapi import TryNext
26 from IPython.core.error import TryNext
27 from IPython.utils.ipstruct import Struct
27 from IPython.utils.ipstruct import Struct
28 from IPython.core.macro import Macro
28 from IPython.core.macro import Macro
29 import IPython.utils.generics
29 import IPython.utils.generics
@@ -150,8 +150,8 b' class IPShellEmbed:'
150 embedded=True,
150 embedded=True,
151 user_ns=user_ns)
151 user_ns=user_ns)
152
152
153 ip = ipapi.IPApi(self.IP)
153 ip = self.IP
154 ip.expose_magic("kill_embedded",kill_embedded)
154 ip.define_magic("kill_embedded",kill_embedded)
155
155
156 # copy our own displayhook also
156 # copy our own displayhook also
157 self.sys_displayhook_embed = sys.displayhook
157 self.sys_displayhook_embed = sys.displayhook
@@ -31,4 +31,4 b' class A(object):'
31 a = A()
31 a = A()
32
32
33 # Now, we force an exit, the caller will check that the del printout was given
33 # Now, we force an exit, the caller will check that the del printout was given
34 _ip.IP.ask_exit()
34 _ip.ask_exit()
@@ -28,9 +28,6 b' def test_import_ipapi():'
28 def test_import_iplib():
28 def test_import_iplib():
29 from IPython.core import iplib
29 from IPython.core import iplib
30
30
31 def test_import_ipmaker():
32 from IPython.core import ipmaker
33
34 def test_import_logger():
31 def test_import_logger():
35 from IPython.core import logger
32 from IPython.core import logger
36
33
@@ -38,8 +38,6 b' if ip is None:'
38 # consistency when the test suite is being run via iptest
38 # consistency when the test suite is being run via iptest
39 from IPython.testing.plugin import ipdoctest
39 from IPython.testing.plugin import ipdoctest
40 ip = ipapi.get()
40 ip = ipapi.get()
41
42 IP = ip.IP # This is the actual IPython shell 'raw' object.
43
41
44 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
45 # Test functions
43 # Test functions
@@ -47,10 +45,10 b" IP = ip.IP # This is the actual IPython shell 'raw' object."
47
45
48 def test_reset():
46 def test_reset():
49 """reset must clear most namespaces."""
47 """reset must clear most namespaces."""
50 IP.reset() # first, it should run without error
48 ip.reset() # first, it should run without error
51 # Then, check that most namespaces end up empty
49 # Then, check that most namespaces end up empty
52 for ns in IP.ns_refs_table:
50 for ns in ip.ns_refs_table:
53 if ns is IP.user_ns:
51 if ns is ip.user_ns:
54 # The user namespace is reset with some data, so we can't check for
52 # The user namespace is reset with some data, so we can't check for
55 # it being empty
53 # it being empty
56 continue
54 continue
@@ -64,8 +62,8 b' def test_user_setup():'
64 kw = dict(mode='install', interactive=False)
62 kw = dict(mode='install', interactive=False)
65
63
66 # Call the user setup and verify that the directory exists
64 # Call the user setup and verify that the directory exists
67 yield user_setup, (ip.options.IPYTHONDIR,''), kw
65 yield user_setup, (ip.config.IPYTHONDIR,''), kw
68 yield os.path.isdir, ip.options.IPYTHONDIR
66 yield os.path.isdir, ip.config.IPYTHONDIR
69
67
70 # Now repeat the operation with a non-existent directory. Check both that
68 # Now repeat the operation with a non-existent directory. Check both that
71 # the call succeeds and that the directory is created.
69 # the call succeeds and that the directory is created.
@@ -20,14 +20,14 b' from IPython.testing import tools as tt'
20
20
21 def test_rehashx():
21 def test_rehashx():
22 # clear up everything
22 # clear up everything
23 _ip.IP.alias_table.clear()
23 _ip.alias_table.clear()
24 del _ip.db['syscmdlist']
24 del _ip.db['syscmdlist']
25
25
26 _ip.magic('rehashx')
26 _ip.magic('rehashx')
27 # Practically ALL ipython development systems will have more than 10 aliases
27 # Practically ALL ipython development systems will have more than 10 aliases
28
28
29 yield (nt.assert_true, len(_ip.IP.alias_table) > 10)
29 yield (nt.assert_true, len(_ip.alias_table) > 10)
30 for key, val in _ip.IP.alias_table.items():
30 for key, val in _ip.alias_table.items():
31 # we must strip dots from alias names
31 # we must strip dots from alias names
32 nt.assert_true('.' not in key)
32 nt.assert_true('.' not in key)
33
33
@@ -52,7 +52,7 b' def doctest_hist_r():'
52
52
53 XXX - This test is not recording the output correctly. Not sure why...
53 XXX - This test is not recording the output correctly. Not sure why...
54
54
55 In [20]: 'hist' in _ip.IP.lsmagic()
55 In [20]: 'hist' in _ip.lsmagic()
56 Out[20]: True
56 Out[20]: True
57
57
58 In [6]: x=1
58 In [6]: x=1
@@ -69,7 +69,7 b' def test_obj_del():'
69 test_dir = os.path.dirname(__file__)
69 test_dir = os.path.dirname(__file__)
70 del_file = os.path.join(test_dir,'obj_del.py')
70 del_file = os.path.join(test_dir,'obj_del.py')
71 ipython_cmd = find_cmd('ipython')
71 ipython_cmd = find_cmd('ipython')
72 out = _ip.IP.getoutput('%s %s' % (ipython_cmd, del_file))
72 out = _ip.getoutput('%s %s' % (ipython_cmd, del_file))
73 nt.assert_equals(out,'obj_del.py: object A deleted')
73 nt.assert_equals(out,'obj_del.py: object A deleted')
74
74
75
75
@@ -124,7 +124,7 b' def doctest_refbug():'
124 """Very nasty problem with references held by multiple runs of a script.
124 """Very nasty problem with references held by multiple runs of a script.
125 See: https://bugs.launchpad.net/ipython/+bug/269966
125 See: https://bugs.launchpad.net/ipython/+bug/269966
126
126
127 In [1]: _ip.IP.clear_main_mod_cache()
127 In [1]: _ip.clear_main_mod_cache()
128
128
129 In [2]: run refbug
129 In [2]: run refbug
130
130
@@ -247,7 +247,7 b' class TestMagicRun(object):'
247 def test_prompts(self):
247 def test_prompts(self):
248 """Test that prompts correctly generate after %run"""
248 """Test that prompts correctly generate after %run"""
249 self.run_tmpfile()
249 self.run_tmpfile()
250 p2 = str(_ip.IP.outputcache.prompt2).strip()
250 p2 = str(_ip.outputcache.prompt2).strip()
251 nt.assert_equals(p2[:3], '...')
251 nt.assert_equals(p2[:3], '...')
252
252
253 def teardown(self):
253 def teardown(self):
@@ -268,7 +268,7 b' def test_paste():'
268 _ip.magic('paste '+flags)
268 _ip.magic('paste '+flags)
269
269
270 # Inject fake clipboard hook but save original so we can restore it later
270 # Inject fake clipboard hook but save original so we can restore it later
271 hooks = _ip.IP.hooks
271 hooks = _ip.hooks
272 user_ns = _ip.user_ns
272 user_ns = _ip.user_ns
273 original_clip = hooks.clipboard_get
273 original_clip = hooks.clipboard_get
274
274
@@ -305,8 +305,8 b' def test_paste():'
305
305
306 # Also test paste echoing, by temporarily faking the writer
306 # Also test paste echoing, by temporarily faking the writer
307 w = StringIO()
307 w = StringIO()
308 writer = _ip.IP.write
308 writer = _ip.write
309 _ip.IP.write = w.write
309 _ip.write = w.write
310 code = """
310 code = """
311 a = 100
311 a = 100
312 b = 200"""
312 b = 200"""
@@ -314,7 +314,7 b' def test_paste():'
314 paste(code,'')
314 paste(code,'')
315 out = w.getvalue()
315 out = w.getvalue()
316 finally:
316 finally:
317 _ip.IP.write = writer
317 _ip.write = writer
318 yield (nt.assert_equal, user_ns['a'], 100)
318 yield (nt.assert_equal, user_ns['a'], 100)
319 yield (nt.assert_equal, user_ns['b'], 200)
319 yield (nt.assert_equal, user_ns['b'], 200)
320 yield (nt.assert_equal, out, code+"\n## -- End pasted text --\n")
320 yield (nt.assert_equal, out, code+"\n## -- End pasted text --\n")
@@ -270,7 +270,7 b' def _formatTracebackLines(lnum, index, lines, Colors, lvals=None,scheme=None):'
270 if scheme is None:
270 if scheme is None:
271 ipinst = ipapi.get()
271 ipinst = ipapi.get()
272 if ipinst is not None:
272 if ipinst is not None:
273 scheme = ipinst.IP.colors
273 scheme = ipinst.colors
274 else:
274 else:
275 scheme = DEFAULT_SCHEME
275 scheme = DEFAULT_SCHEME
276
276
@@ -494,7 +494,7 b' class ListTB(TBTools):'
494 if have_filedata:
494 if have_filedata:
495 ipinst = ipapi.get()
495 ipinst = ipapi.get()
496 if ipinst is not None:
496 if ipinst is not None:
497 ipinst.IP.hooks.synchronize_with_editor(filename, lineno, 0)
497 ipinst.hooks.synchronize_with_editor(filename, lineno, 0)
498 # vds:<<
498 # vds:<<
499
499
500 return list
500 return list
@@ -816,7 +816,7 b' class VerboseTB(TBTools):'
816 filepath = os.path.abspath(filepath)
816 filepath = os.path.abspath(filepath)
817 ipinst = ipapi.get()
817 ipinst = ipapi.get()
818 if ipinst is not None:
818 if ipinst is not None:
819 ipinst.IP.hooks.synchronize_with_editor(filepath, lnum, 0)
819 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
820 # vds: <<
820 # vds: <<
821
821
822 # return all our info assembled as a single string
822 # return all our info assembled as a single string
@@ -16,7 +16,8 b" __all__ = ['Gnuplot','gp','gp_new','plot','plot2','splot','replot',"
16 'gphelp']
16 'gphelp']
17
17
18 import IPython.GnuplotRuntime as GRun
18 import IPython.GnuplotRuntime as GRun
19 from IPython.utils.genutils import page,warn
19 from IPython.utils.genutils import warn
20 from IPython.core.page import page
20
21
21 # Set global names for interactive use
22 # Set global names for interactive use
22 Gnuplot = GRun.Gnuplot
23 Gnuplot = GRun.Gnuplot
@@ -77,7 +77,7 b' def idoctest(ns=None,eraise=False):'
77 if ns is None:
77 if ns is None:
78 ns = ip.user_ns
78 ns = ip.user_ns
79
79
80 ip.IP.savehist()
80 ip.savehist()
81 try:
81 try:
82 while True:
82 while True:
83 line = raw_input()
83 line = raw_input()
@@ -96,7 +96,7 b' def idoctest(ns=None,eraise=False):'
96 print "KeyboardInterrupt - Discarding input."
96 print "KeyboardInterrupt - Discarding input."
97 run_test = False
97 run_test = False
98
98
99 ip.IP.reloadhist()
99 ip.reloadhist()
100
100
101 if run_test:
101 if run_test:
102 # Extra blank line at the end to ensure that the final docstring has a
102 # Extra blank line at the end to ensure that the final docstring has a
@@ -81,7 +81,7 b' def clear_f(self,arg):'
81 gc.collect()
81 gc.collect()
82
82
83 # Activate the extension
83 # Activate the extension
84 ip.expose_magic("clear",clear_f)
84 ip.define_magic("clear",clear_f)
85 import ipy_completers
85 import ipy_completers
86 ipy_completers.quick_completer(
86 ipy_completers.quick_completer(
87 '%clear','in out shadow_nuke shadow_compress dhist')
87 '%clear','in out shadow_nuke shadow_compress dhist')
@@ -3,6 +3,8 b''
3 """
3 """
4
4
5 from IPython.core import ipapi
5 from IPython.core import ipapi
6 from IPython.core.error import TryNext
7
6 ip = ipapi.get()
8 ip = ipapi.get()
7
9
8 import os,sys
10 import os,sys
@@ -16,7 +18,7 b' def restore_env(self):'
16 os.environ[k] = os.environ.get(k,"") + v
18 os.environ[k] = os.environ.get(k,"") + v
17 for k,v in env['pre']:
19 for k,v in env['pre']:
18 os.environ[k] = v + os.environ.get(k,"")
20 os.environ[k] = v + os.environ.get(k,"")
19 raise ipapi.TryNext
21 raise TryNext
20
22
21 ip.set_hook('late_startup_hook', restore_env)
23 ip.set_hook('late_startup_hook', restore_env)
22
24
@@ -85,6 +87,6 b' def env_completer(self,event):'
85 """ Custom completer that lists all env vars """
87 """ Custom completer that lists all env vars """
86 return os.environ.keys()
88 return os.environ.keys()
87
89
88 ip.expose_magic('env', persist_env)
90 ip.define_magic('env', persist_env)
89 ip.set_hook('complete_command',env_completer, str_key = '%env')
91 ip.set_hook('complete_command',env_completer, str_key = '%env')
90
92
@@ -9,6 +9,7 b' var = !ls'
9 """
9 """
10
10
11 from IPython.core import ipapi
11 from IPython.core import ipapi
12 from IPython.core.error import TryNext
12 from IPython.utils.genutils import *
13 from IPython.utils.genutils import *
13
14
14 ip = ipapi.get()
15 ip = ipapi.get()
@@ -17,9 +18,6 b' import re'
17
18
18 def hnd_magic(line,mo):
19 def hnd_magic(line,mo):
19 """ Handle a = %mymagic blah blah """
20 """ Handle a = %mymagic blah blah """
20 #cmd = genutils.make_quoted_expr(mo.group('syscmd'))
21 #mag = 'ipmagic
22 #return "%s = %s"
23 var = mo.group('varname')
21 var = mo.group('varname')
24 cmd = mo.group('cmd')
22 cmd = mo.group('cmd')
25 expr = make_quoted_expr(cmd)
23 expr = make_quoted_expr(cmd)
@@ -27,9 +25,6 b' def hnd_magic(line,mo):'
27
25
28 def hnd_syscmd(line,mo):
26 def hnd_syscmd(line,mo):
29 """ Handle a = !ls """
27 """ Handle a = !ls """
30 #cmd = genutils.make_quoted_expr(mo.group('syscmd'))
31 #mag = 'ipmagic
32 #return "%s = %s"
33 var = mo.group('varname')
28 var = mo.group('varname')
34 cmd = mo.group('cmd')
29 cmd = mo.group('cmd')
35 expr = make_quoted_expr(itpl("sc -l =$cmd"))
30 expr = make_quoted_expr(itpl("sc -l =$cmd"))
@@ -58,6 +53,6 b' def regex_prefilter_f(self,line):'
58 if mo:
53 if mo:
59 return handler(line,mo)
54 return handler(line,mo)
60
55
61 raise ipapi.TryNext
56 raise TryNext
62
57
63 ip.set_hook('input_prefilter', regex_prefilter_f)
58 ip.set_hook('input_prefilter', regex_prefilter_f)
@@ -1612,10 +1612,10 b' class ihist(Table):'
1612 def __iter__(self):
1612 def __iter__(self):
1613 api = ipapi.get()
1613 api = ipapi.get()
1614 if self.raw:
1614 if self.raw:
1615 for line in api.IP.input_hist_raw:
1615 for line in api.input_hist_raw:
1616 yield line.rstrip("\n")
1616 yield line.rstrip("\n")
1617 else:
1617 else:
1618 for line in api.IP.input_hist:
1618 for line in api.input_hist:
1619 yield line.rstrip("\n")
1619 yield line.rstrip("\n")
1620
1620
1621
1621
@@ -1644,7 +1644,7 b' class ialias(Table):'
1644 def __iter__(self):
1644 def __iter__(self):
1645 api = ipapi.get()
1645 api = ipapi.get()
1646
1646
1647 for (name, (args, command)) in api.IP.alias_table.iteritems():
1647 for (name, (args, command)) in api.alias_table.iteritems():
1648 yield Alias(name, args, command)
1648 yield Alias(name, args, command)
1649
1649
1650
1650
@@ -225,6 +225,7 b' reloader = ModuleReloader()'
225 # IPython connectivity
225 # IPython connectivity
226 #------------------------------------------------------------------------------
226 #------------------------------------------------------------------------------
227 from IPython.core import ipapi
227 from IPython.core import ipapi
228 from IPython.core.error import TryNext
228
229
229 ip = ipapi.get()
230 ip = ipapi.get()
230
231
@@ -232,7 +233,7 b' autoreload_enabled = False'
232
233
233 def runcode_hook(self):
234 def runcode_hook(self):
234 if not autoreload_enabled:
235 if not autoreload_enabled:
235 raise ipapi.TryNext
236 raise TryNext
236 try:
237 try:
237 reloader.check()
238 reloader.check()
238 except:
239 except:
@@ -339,11 +340,11 b" def aimport_f(self, parameter_s=''):"
339 __import__(modname)
340 __import__(modname)
340 basename = modname.split('.')[0]
341 basename = modname.split('.')[0]
341 mod = sys.modules[basename]
342 mod = sys.modules[basename]
342 ip.to_user_ns({basename: mod})
343 ip.push({basename: mod})
343
344
344 def init():
345 def init():
345 ip.expose_magic('autoreload', autoreload_f)
346 ip.define_magic('autoreload', autoreload_f)
346 ip.expose_magic('aimport', aimport_f)
347 ip.define_magic('aimport', aimport_f)
347 ip.set_hook('pre_runcode_hook', runcode_hook)
348 ip.set_hook('pre_runcode_hook', runcode_hook)
348
349
349 init()
350 init()
@@ -8,6 +8,8 b" ip.set_hook('complete_command', svn_completer, str_key = 'svn')"
8
8
9 """
9 """
10 from IPython.core import ipapi
10 from IPython.core import ipapi
11 from IPython.core.error import TryNext
12
11 import glob,os,shlex,sys
13 import glob,os,shlex,sys
12 import inspect
14 import inspect
13 from time import time
15 from time import time
@@ -169,7 +171,7 b' def vcs_completer(commands, event):'
169 if len(cmd_param) == 2 or 'help' in cmd_param:
171 if len(cmd_param) == 2 or 'help' in cmd_param:
170 return commands.split()
172 return commands.split()
171
173
172 return ip.IP.Completer.file_matches(event.symbol)
174 return ip.Completer.file_matches(event.symbol)
173
175
174
176
175 pkg_cache = None
177 pkg_cache = None
@@ -245,7 +247,7 b' def bzr_completer(self,event):'
245 return []
247 return []
246 else:
248 else:
247 # the rest are probably file names
249 # the rest are probably file names
248 return ip.IP.Completer.file_matches(event.symbol)
250 return ip.Completer.file_matches(event.symbol)
249
251
250 return bzr_commands()
252 return bzr_commands()
251
253
@@ -329,7 +331,7 b' def cd_completer(self, event):'
329 if ' ' in d:
331 if ' ' in d:
330 # we don't want to deal with any of that, complex code
332 # we don't want to deal with any of that, complex code
331 # for this is elsewhere
333 # for this is elsewhere
332 raise ipapi.TryNext
334 raise TryNext
333 found.append( d )
335 found.append( d )
334
336
335 if not found:
337 if not found:
@@ -341,7 +343,7 b' def cd_completer(self, event):'
341 if bkmatches:
343 if bkmatches:
342 return bkmatches
344 return bkmatches
343
345
344 raise ipapi.TryNext
346 raise TryNext
345
347
346
348
347 def single_dir_expand(matches):
349 def single_dir_expand(matches):
@@ -6,6 +6,7 b' Contributions are *very* welcome.'
6 """
6 """
7
7
8 from IPython.core import ipapi
8 from IPython.core import ipapi
9 from IPython.core.error import TryNext
9 ip = ipapi.get()
10 ip = ipapi.get()
10
11
11 from IPython.external.Itpl import itplns
12 from IPython.external.Itpl import itplns
@@ -29,7 +30,7 b' def install_editor(run_template, wait = False):'
29 cmd = itplns(run_template, locals())
30 cmd = itplns(run_template, locals())
30 print ">",cmd
31 print ">",cmd
31 if os.system(cmd) != 0:
32 if os.system(cmd) != 0:
32 raise ipapi.TryNext()
33 raise TryNext()
33 if wait:
34 if wait:
34 raw_input("Press Enter when done editing:")
35 raw_input("Press Enter when done editing:")
35
36
@@ -43,7 +43,7 b' def export(filename = None):'
43 varstomove.append(k)
43 varstomove.append(k)
44 lines.append('%s = %s' % (k,repr(v)))
44 lines.append('%s = %s' % (k,repr(v)))
45
45
46 lines.append('ip.to_user_ns("%s")' % (' '.join(varstomove)))
46 lines.append('ip.push("%s")' % (' '.join(varstomove)))
47
47
48 bkms = ip.db.get('bookmarks',{})
48 bkms = ip.db.get('bookmarks',{})
49
49
@@ -57,7 +57,7 b' def export(filename = None):'
57 lines.extend(['','# === Alias definitions ===',''])
57 lines.extend(['','# === Alias definitions ===',''])
58 for k,v in aliases.items():
58 for k,v in aliases.items():
59 try:
59 try:
60 lines.append("ip.defalias('%s', %s)" % (k, repr(v[1])))
60 lines.append("ip.define_alias('%s', %s)" % (k, repr(v[1])))
61 except (AttributeError, TypeError):
61 except (AttributeError, TypeError):
62 pass
62 pass
63
63
@@ -9,6 +9,7 b' to.'
9
9
10 from IPython.core import ipapi
10 from IPython.core import ipapi
11 ip = ipapi.get()
11 ip = ipapi.get()
12 from IPython.core.iplib import InteractiveShell
12
13
13 import sys,textwrap,inspect
14 import sys,textwrap,inspect
14
15
@@ -34,10 +35,10 b' class ExtUtil:'
34 act = []
35 act = []
35 for mname,m in sys.modules.items():
36 for mname,m in sys.modules.items():
36 o = getattr(m, 'ip', None)
37 o = getattr(m, 'ip', None)
37 if isinstance(o, ipapi.IPApi):
38 if isinstance(o, InteractiveShell):
38 act.append((mname,m))
39 act.append((mname,m))
39 act.sort()
40 act.sort()
40 return act
41 return act
41
42
42 extutil = ExtUtil()
43 extutil = ExtUtil()
43 ip.to_user_ns('extutil')
44 ip.push('extutil')
@@ -16,12 +16,13 b' Not to be confused with ipipe commands (ils etc.) that also start with i.'
16 """
16 """
17
17
18 from IPython.core import ipapi
18 from IPython.core import ipapi
19 from IPython.core.error import TryNext
19 ip = ipapi.get()
20 ip = ipapi.get()
20
21
21 import shutil,os,shlex
22 import shutil,os,shlex
22 from IPython.external import mglob
23 from IPython.external import mglob
23 from IPython.external.path import path
24 from IPython.external.path import path
24 from IPython.core.ipapi import UsageError
25 from IPython.core.error import UsageError
25 import IPython.utils.generics
26 import IPython.utils.generics
26
27
27 def parse_args(args):
28 def parse_args(args):
@@ -59,7 +60,7 b' def icp(ip,arg):'
59 else:
60 else:
60 shutil.copy2(f,targetdir)
61 shutil.copy2(f,targetdir)
61 return fs
62 return fs
62 ip.defalias("icp",icp)
63 ip.define_alias("icp",icp)
63
64
64 def imv(ip,arg):
65 def imv(ip,arg):
65 """ imv src tgt
66 """ imv src tgt
@@ -73,7 +74,7 b' def imv(ip,arg):'
73 for f in fs:
74 for f in fs:
74 shutil.move(f, target)
75 shutil.move(f, target)
75 return fs
76 return fs
76 ip.defalias("imv",imv)
77 ip.define_alias("imv",imv)
77
78
78 def irm(ip,arg):
79 def irm(ip,arg):
79 """ irm path[s]...
80 """ irm path[s]...
@@ -92,7 +93,7 b' def irm(ip,arg):'
92 else:
93 else:
93 os.remove(p)
94 os.remove(p)
94
95
95 ip.defalias("irm",irm)
96 ip.define_alias("irm",irm)
96
97
97 def imkdir(ip,arg):
98 def imkdir(ip,arg):
98 """ imkdir path
99 """ imkdir path
@@ -103,7 +104,7 b' def imkdir(ip,arg):'
103 targetdir = arg.split(None,1)[1]
104 targetdir = arg.split(None,1)[1]
104 distutils.dir_util.mkpath(targetdir,verbose =1)
105 distutils.dir_util.mkpath(targetdir,verbose =1)
105
106
106 ip.defalias("imkdir",imkdir)
107 ip.define_alias("imkdir",imkdir)
107
108
108 def igrep(ip,arg):
109 def igrep(ip,arg):
109 """ igrep PAT files...
110 """ igrep PAT files...
@@ -129,7 +130,7 b' def igrep(ip,arg):'
129 print l.rstrip()
130 print l.rstrip()
130 return res
131 return res
131
132
132 ip.defalias("igrep",igrep)
133 ip.define_alias("igrep",igrep)
133
134
134 def collect(ip,arg):
135 def collect(ip,arg):
135 """ collect foo/a.txt rec:bar=*.py
136 """ collect foo/a.txt rec:bar=*.py
@@ -159,7 +160,7 b' def collect(ip,arg):'
159 print f,"=>",trg
160 print f,"=>",trg
160 shutil.copy2(f,trg)
161 shutil.copy2(f,trg)
161
162
162 ip.defalias("collect",collect)
163 ip.define_alias("collect",collect)
163
164
164 def inote(ip,arg):
165 def inote(ip,arg):
165 """ inote Hello world
166 """ inote Hello world
@@ -175,9 +176,9 b' def inote(ip,arg):'
175 entry = " === " + time.asctime() + ': ===\n' + arg.split(None,1)[1] + '\n'
176 entry = " === " + time.asctime() + ': ===\n' + arg.split(None,1)[1] + '\n'
176 f= open(fname, 'a').write(entry)
177 f= open(fname, 'a').write(entry)
177 except IndexError:
178 except IndexError:
178 ip.IP.hooks.editor(fname)
179 ip.hooks.editor(fname)
179
180
180 ip.defalias("inote",inote)
181 ip.define_alias("inote",inote)
181
182
182 def pathobj_mangle(p):
183 def pathobj_mangle(p):
183 return p.replace(' ', '__').replace('.','DOT')
184 return p.replace(' ', '__').replace('.','DOT')
@@ -229,7 +230,7 b' def complete_pathobj(obj, prev_completions):'
229 if res:
230 if res:
230 return res
231 return res
231 # just return normal attributes of 'path' object if the dir is empty
232 # just return normal attributes of 'path' object if the dir is empty
232 raise ipapi.TryNext
233 raise TryNext
233
234
234 complete_pathobj = IPython.utils.generics.complete_object.when_type(PathObj)(complete_pathobj)
235 complete_pathobj = IPython.utils.generics.complete_object.when_type(PathObj)(complete_pathobj)
235
236
@@ -240,6 +241,6 b' def test_pathobj():'
240 rootdir = PathObj("/")
241 rootdir = PathObj("/")
241 startmenu = PathObj("d:/Documents and Settings/All Users/Start Menu/Programs")
242 startmenu = PathObj("d:/Documents and Settings/All Users/Start Menu/Programs")
242 cwd = PathObj('.')
243 cwd = PathObj('.')
243 ip.to_user_ns("rootdir startmenu cwd")
244 ip.push("rootdir startmenu cwd")
244
245
245 #test_pathobj() No newline at end of file
246 #test_pathobj()
@@ -28,7 +28,7 b' def global_f(self,cmdline):'
28 lines = ['%s [%s]\n%s' % (p[2].rjust(70),p[1],p[3].rstrip()) for p in parts]
28 lines = ['%s [%s]\n%s' % (p[2].rjust(70),p[1],p[3].rstrip()) for p in parts]
29 print "\n".join(lines)
29 print "\n".join(lines)
30
30
31 ip.expose_magic('global', global_f)
31 ip.define_magic('global', global_f)
32
32
33 def global_completer(self,event):
33 def global_completer(self,event):
34 compl = [l.rstrip() for l in os.popen(global_bin + ' -c ' + event.symbol).readlines()]
34 compl = [l.rstrip() for l in os.popen(global_bin + ' -c ' + event.symbol).readlines()]
@@ -10,6 +10,7 b' do the same in default completer.'
10
10
11 """
11 """
12 from IPython.core import ipapi
12 from IPython.core import ipapi
13 from IPython.core.error import TryNext
13 from IPython.utils import generics
14 from IPython.utils import generics
14 from IPython.utils.genutils import dir2
15 from IPython.utils.genutils import dir2
15
16
@@ -59,7 +60,7 b' def attr_matches(self, text):'
59
60
60 try:
61 try:
61 words = generics.complete_object(obj, words)
62 words = generics.complete_object(obj, words)
62 except ipapi.TryNext:
63 except TryNext:
63 pass
64 pass
64 # Build match list to return
65 # Build match list to return
65 n = len(attr)
66 n = len(attr)
@@ -116,14 +116,14 b" def jot_obj(self, obj, name, comment=''):"
116 uname = 'jot/'+name+suffix
116 uname = 'jot/'+name+suffix
117
117
118 # which one works better?
118 # which one works better?
119 #all = ip.IP.shadowhist.all()
119 #all = ip.shadowhist.all()
120 all = ip.IP.shell.input_hist
120 all = ip.shell.input_hist
121
121
122 # We may actually want to make snapshot of files that are run-ned.
122 # We may actually want to make snapshot of files that are run-ned.
123
123
124 # get the comment
124 # get the comment
125 try:
125 try:
126 comment = ip.IP.magic_edit('-x').strip()
126 comment = ip.magic_edit('-x').strip()
127 except:
127 except:
128 print "No comment is recorded."
128 print "No comment is recorded."
129 comment = ''
129 comment = ''
@@ -307,5 +307,5 b" def magic_read(self, parameter_s=''):"
307 return read_variables(ip, toret)
307 return read_variables(ip, toret)
308
308
309
309
310 ip.expose_magic('jot',magic_jot)
310 ip.define_magic('jot',magic_jot)
311 ip.expose_magic('read',magic_read)
311 ip.define_magic('read',magic_read)
@@ -16,7 +16,7 b' def pylaunchers():'
16 for f in fs:
16 for f in fs:
17 l = PyLauncher(f)
17 l = PyLauncher(f)
18 n = os.path.splitext(f)[0]
18 n = os.path.splitext(f)[0]
19 ip.defalias(n, l)
19 ip.define_alias(n, l)
20 ip.magic('store '+n)
20 ip.magic('store '+n)
21
21
22
22
@@ -39,7 +39,7 b' def main():'
39 return
39 return
40
40
41 os.environ["PATH"] = os.environ["PATH"] + ";" + kitroot() + "\\bin;"
41 os.environ["PATH"] = os.environ["PATH"] + ";" + kitroot() + "\\bin;"
42 ip.to_user_ns("pylaunchers")
42 ip.push("pylaunchers")
43 cmds = ip.db.get('syscmdlist', None)
43 cmds = ip.db.get('syscmdlist', None)
44 if cmds is None:
44 if cmds is None:
45 ip.magic('rehashx')
45 ip.magic('rehashx')
@@ -63,8 +63,8 b' def ipython_firstrun(ip):'
63
63
64 print "First run of ipykit - configuring"
64 print "First run of ipykit - configuring"
65
65
66 ip.defalias('py',selflaunch)
66 ip.define_alias('py',selflaunch)
67 ip.defalias('d','dir /w /og /on')
67 ip.define_alias('d','dir /w /og /on')
68 ip.magic('store py')
68 ip.magic('store py')
69 ip.magic('store d')
69 ip.magic('store d')
70
70
@@ -43,7 +43,7 b" def magic_rehash(self, parameter_s = ''):"
43 # aliases since %rehash will probably clobber them
43 # aliases since %rehash will probably clobber them
44 self.shell.init_auto_alias()
44 self.shell.init_auto_alias()
45
45
46 ip.expose_magic("rehash", magic_rehash)
46 ip.define_magic("rehash", magic_rehash)
47
47
48 # Exit
48 # Exit
49 def magic_Quit(self, parameter_s=''):
49 def magic_Quit(self, parameter_s=''):
@@ -51,7 +51,7 b" def magic_Quit(self, parameter_s=''):"
51
51
52 self.shell.ask_exit()
52 self.shell.ask_exit()
53
53
54 ip.expose_magic("Quit", magic_Quit)
54 ip.define_magic("Quit", magic_Quit)
55
55
56
56
57 # make it autocallable fn if you really need it
57 # make it autocallable fn if you really need it
@@ -59,4 +59,4 b" def magic_p(self, parameter_s=''):"
59 """Just a short alias for Python's 'print'."""
59 """Just a short alias for Python's 'print'."""
60 exec 'print ' + parameter_s in self.shell.user_ns
60 exec 'print ' + parameter_s in self.shell.user_ns
61
61
62 ip.expose_magic("p", magic_p)
62 ip.define_magic("p", magic_p)
@@ -229,6 +229,6 b" def lookfor_modules_f(self, arg=''):"
229 else:
229 else:
230 _lookfor_modules = arg.split()
230 _lookfor_modules = arg.split()
231
231
232 ip.expose_magic('lookfor', lookfor_f)
232 ip.define_magic('lookfor', lookfor_f)
233 ip.expose_magic('lookfor_modules', lookfor_modules_f)
233 ip.define_magic('lookfor_modules', lookfor_modules_f)
234
234
@@ -25,9 +25,9 b" def p4_f(self, parameter_s=''):"
25 def p4d(fname):
25 def p4d(fname):
26 return os.popen('p4 where ' + fname).read().split()[0]
26 return os.popen('p4 where ' + fname).read().split()[0]
27
27
28 ip.to_user_ns("p4d")
28 ip.push("p4d")
29
29
30 ip.expose_magic('p4', p4_f)
30 ip.define_magic('p4', p4_f)
31
31
32 p4_commands = """\
32 p4_commands = """\
33 add admin annotate branch branches change changes changelist
33 add admin annotate branch branches change changes changelist
@@ -17,6 +17,7 b' for numpy dtype objects, add the following to your ipy_user_conf.py::'
17 """
17 """
18
18
19 from IPython.core import ipapi
19 from IPython.core import ipapi
20 from IPython.core.error import TryNext
20 from IPython.utils.genutils import Term
21 from IPython.utils.genutils import Term
21
22
22 from IPython.external import pretty
23 from IPython.external import pretty
@@ -41,6 +41,6 b' def main():'
41 o.xmode = 'plain'
41 o.xmode = 'plain'
42
42
43 # Store the activity flag in the metadata bag from the running shell
43 # Store the activity flag in the metadata bag from the running shell
44 ip.IP.meta.doctest_mode = True
44 ip.meta.doctest_mode = True
45
45
46 main()
46 main()
@@ -8,6 +8,7 b' compatibility)'
8 """
8 """
9
9
10 from IPython.core import ipapi
10 from IPython.core import ipapi
11 from IPython.core.error import TryNext
11 import os,re,textwrap
12 import os,re,textwrap
12
13
13 # The import below effectively obsoletes your old-style ipythonrc[.ini],
14 # The import below effectively obsoletes your old-style ipythonrc[.ini],
@@ -69,10 +70,10 b' def main():'
69 o.banner = "IPython %s [on Py %s]\n" % (release.version,sys.version.split(None,1)[0])
70 o.banner = "IPython %s [on Py %s]\n" % (release.version,sys.version.split(None,1)[0])
70
71
71
72
72 ip.IP.default_option('cd','-q')
73 ip.default_option('cd','-q')
73 ip.IP.default_option('macro', '-r')
74 ip.default_option('macro', '-r')
74 # If you only rarely want to execute the things you %edit...
75 # If you only rarely want to execute the things you %edit...
75 #ip.IP.default_option('edit','-x')
76 #ip.default_option('edit','-x')
76
77
77
78
78 o.prompts_pad_left="1"
79 o.prompts_pad_left="1"
@@ -108,11 +109,11 b' def main():'
108 cmd = noext
109 cmd = noext
109
110
110 key = mapper(cmd)
111 key = mapper(cmd)
111 if key not in ip.IP.alias_table:
112 if key not in ip.alias_table:
112 # Dots will be removed from alias names, since ipython
113 # Dots will be removed from alias names, since ipython
113 # assumes names with dots to be python code
114 # assumes names with dots to be python code
114
115
115 ip.defalias(key.replace('.',''), cmd)
116 ip.define_alias(key.replace('.',''), cmd)
116
117
117 # mglob combines 'find', recursion, exclusion... '%mglob?' to learn more
118 # mglob combines 'find', recursion, exclusion... '%mglob?' to learn more
118 ip.load("IPython.external.mglob")
119 ip.load("IPython.external.mglob")
@@ -121,13 +122,13 b' def main():'
121 if sys.platform == 'win32':
122 if sys.platform == 'win32':
122 if 'cygwin' in os.environ['PATH'].lower():
123 if 'cygwin' in os.environ['PATH'].lower():
123 # use the colors of cygwin ls (recommended)
124 # use the colors of cygwin ls (recommended)
124 ip.defalias('d', 'ls -F --color=auto')
125 ip.define_alias('d', 'ls -F --color=auto')
125 else:
126 else:
126 # get icp, imv, imkdir, igrep, irm,...
127 # get icp, imv, imkdir, igrep, irm,...
127 ip.load('ipy_fsops')
128 ip.load('ipy_fsops')
128
129
129 # and the next best thing to real 'ls -F'
130 # and the next best thing to real 'ls -F'
130 ip.defalias('d','dir /w /og /on')
131 ip.define_alias('d','dir /w /og /on')
131
132
132 ip.set_hook('input_prefilter', slash_prefilter_f)
133 ip.set_hook('input_prefilter', slash_prefilter_f)
133 extend_shell_behavior(ip)
134 extend_shell_behavior(ip)
@@ -141,10 +142,10 b' class LastArgFinder:'
141 ip = ipapi.get()
142 ip = ipapi.get()
142 if hist_idx is None:
143 if hist_idx is None:
143 return str(self)
144 return str(self)
144 return ip.IP.input_hist_raw[hist_idx].strip().split()[-1]
145 return ip.input_hist_raw[hist_idx].strip().split()[-1]
145 def __str__(self):
146 def __str__(self):
146 ip = ipapi.get()
147 ip = ipapi.get()
147 for cmd in reversed(ip.IP.input_hist_raw):
148 for cmd in reversed(ip.input_hist_raw):
148 parts = cmd.strip().split()
149 parts = cmd.strip().split()
149 if len(parts) < 2 or parts[-1] in ['$LA', 'LA()']:
150 if len(parts) < 2 or parts[-1] in ['$LA', 'LA()']:
150 continue
151 continue
@@ -159,7 +160,7 b' def slash_prefilter_f(self,line):'
159 from IPython.utils import genutils
160 from IPython.utils import genutils
160 if re.match('(?:[.~]|/[a-zA-Z_0-9]+)/', line):
161 if re.match('(?:[.~]|/[a-zA-Z_0-9]+)/', line):
161 return "_ip.system(" + genutils.make_quoted_expr(line)+")"
162 return "_ip.system(" + genutils.make_quoted_expr(line)+")"
162 raise ipapi.TryNext
163 raise TryNext
163
164
164 # XXX You do not need to understand the next function!
165 # XXX You do not need to understand the next function!
165 # This should probably be moved out of profile
166 # This should probably be moved out of profile
@@ -169,16 +170,16 b' def extend_shell_behavior(ip):'
169 # Instead of making signature a global variable tie it to IPSHELL.
170 # Instead of making signature a global variable tie it to IPSHELL.
170 # In future if it is required to distinguish between different
171 # In future if it is required to distinguish between different
171 # shells we can assign a signature per shell basis
172 # shells we can assign a signature per shell basis
172 ip.IP.__sig__ = 0xa005
173 ip.__sig__ = 0xa005
173 # mark the IPSHELL with this signature
174 # mark the IPSHELL with this signature
174 ip.IP.user_ns['__builtins__'].__dict__['__sig__'] = ip.IP.__sig__
175 ip.user_ns['__builtins__'].__dict__['__sig__'] = ip.__sig__
175
176
176 from IPython.external.Itpl import ItplNS
177 from IPython.external.Itpl import ItplNS
177 from IPython.utils.genutils import shell
178 from IPython.utils.genutils import shell
178 # utility to expand user variables via Itpl
179 # utility to expand user variables via Itpl
179 # xxx do something sensible with depth?
180 # xxx do something sensible with depth?
180 ip.IP.var_expand = lambda cmd, lvars=None, depth=2: \
181 ip.var_expand = lambda cmd, lvars=None, depth=2: \
181 str(ItplNS(cmd, ip.IP.user_ns, get_locals()))
182 str(ItplNS(cmd, ip.user_ns, get_locals()))
182
183
183 def get_locals():
184 def get_locals():
184 """ Substituting a variable through Itpl deep inside the IPSHELL stack
185 """ Substituting a variable through Itpl deep inside the IPSHELL stack
@@ -194,7 +195,7 b' def extend_shell_behavior(ip):'
194 getlvars = lambda fno: sys._getframe(fno+1).f_locals
195 getlvars = lambda fno: sys._getframe(fno+1).f_locals
195 # trackback until we enter the IPSHELL
196 # trackback until we enter the IPSHELL
196 frame_no = 1
197 frame_no = 1
197 sig = ip.IP.__sig__
198 sig = ip.__sig__
198 fsig = ~sig
199 fsig = ~sig
199 while fsig != sig :
200 while fsig != sig :
200 try:
201 try:
@@ -230,7 +231,7 b' def extend_shell_behavior(ip):'
230
231
231 # We must start with a clean buffer, in case this is run from an
232 # We must start with a clean buffer, in case this is run from an
232 # interactive IPython session (via a magic, for example).
233 # interactive IPython session (via a magic, for example).
233 ip.IP.resetbuffer()
234 ip.resetbuffer()
234 lines = lines.split('\n')
235 lines = lines.split('\n')
235 more = 0
236 more = 0
236 command = ''
237 command = ''
@@ -251,9 +252,9 b' def extend_shell_behavior(ip):'
251 command += line
252 command += line
252 if command or more:
253 if command or more:
253 # push to raw history, so hist line numbers stay in sync
254 # push to raw history, so hist line numbers stay in sync
254 ip.IP.input_hist_raw.append("# " + command + "\n")
255 ip.input_hist_raw.append("# " + command + "\n")
255
256
256 more = ip.IP.push(ip.IP.prefilter(command,more))
257 more = ip.push_line(ip.prefilter(command,more))
257 command = ''
258 command = ''
258 # IPython's runsource returns None if there was an error
259 # IPython's runsource returns None if there was an error
259 # compiling the code. This allows us to stop processing right
260 # compiling the code. This allows us to stop processing right
@@ -263,8 +264,8 b' def extend_shell_behavior(ip):'
263 # final newline in case the input didn't have it, so that the code
264 # final newline in case the input didn't have it, so that the code
264 # actually does get executed
265 # actually does get executed
265 if more:
266 if more:
266 ip.IP.push('\n')
267 ip.push_line('\n')
267
268
268 ip.IP.runlines = _runlines
269 ip.runlines = _runlines
269
270
270 main()
271 main()
@@ -19,12 +19,12 b' def call_pydb(self, args):'
19 # print argl # dbg
19 # print argl # dbg
20 if len(inspect.getargspec(pydb.runv)[0]) == 2:
20 if len(inspect.getargspec(pydb.runv)[0]) == 2:
21 pdb = debugger.Pdb(color_scheme=self.colors)
21 pdb = debugger.Pdb(color_scheme=self.colors)
22 ip.IP.history_saving_wrapper( lambda : pydb.runv(argl, pdb) )()
22 ip.history_saving_wrapper( lambda : pydb.runv(argl, pdb) )()
23 else:
23 else:
24 ip.IP.history_saving_wrapper( lambda : pydb.runv(argl) )()
24 ip.history_saving_wrapper( lambda : pydb.runv(argl) )()
25
25
26
26
27 ip.expose_magic("pydb",call_pydb)
27 ip.define_magic("pydb",call_pydb)
28
28
29
29
30
30
@@ -42,7 +42,7 b' class PyLauncher:'
42 """ Invoke selflanucher on the specified script
42 """ Invoke selflanucher on the specified script
43
43
44 This is mostly useful for associating with scripts using::
44 This is mostly useful for associating with scripts using::
45 _ip.defalias('foo',PyLauncher('foo_script.py'))
45 _ip.define_alias('foo',PyLauncher('foo_script.py'))
46
46
47 """
47 """
48 def __init__(self,script):
48 def __init__(self,script):
@@ -137,4 +137,4 b' def rehashdir_f(self,arg):'
137 os.chdir(savedir)
137 os.chdir(savedir)
138 return created
138 return created
139
139
140 ip.expose_magic("rehashdir",rehashdir_f)
140 ip.define_magic("rehashdir",rehashdir_f)
@@ -64,5 +64,5 b' def render(tmpl):'
64 toclip(res)
64 toclip(res)
65 return res
65 return res
66
66
67 ip.to_user_ns('render')
67 ip.push('render')
68 No newline at end of file
68
@@ -55,7 +55,7 b' def init():'
55 o.allow_new_attr (True )
55 o.allow_new_attr (True )
56 o.verbose = 0
56 o.verbose = 0
57
57
58 ip.IP.system = (sys.platform == 'win32' and new_ipsystem_win32 or
58 ip.system = (sys.platform == 'win32' and new_ipsystem_win32 or
59 new_ipsystem_posix)
59 new_ipsystem_posix)
60
60
61 init()
61 init()
@@ -52,7 +52,8 b' Notes'
52 from enthought.traits import api as T
52 from enthought.traits import api as T
53
53
54 # IPython imports
54 # IPython imports
55 from IPython.core.ipapi import TryNext, get as ipget
55 from IPython.core.error import TryNext
56 from IPython.core.ipapi import get as ipget
56 from IPython.utils.genutils import dir2
57 from IPython.utils.genutils import dir2
57 try:
58 try:
58 set
59 set
@@ -68,6 +68,7 b' something. Instead of edit, use the vim magic. Thats it!'
68 """
68 """
69
69
70 from IPython.core import ipapi
70 from IPython.core import ipapi
71 from IPython.core.error import TryNext
71
72
72 import socket, select
73 import socket, select
73 import os, threading, subprocess
74 import os, threading, subprocess
@@ -161,7 +162,7 b' def shutdown_server(self):'
161 if SERVER:
162 if SERVER:
162 SERVER.stop()
163 SERVER.stop()
163 SERVER.join(3)
164 SERVER.join(3)
164 raise ipapi.TryNext
165 raise TryNext
165
166
166 ip.set_hook('shutdown_hook', shutdown_server, 10)
167 ip.set_hook('shutdown_hook', shutdown_server, 10)
167
168
@@ -235,5 +236,5 b' def vim(self, argstr):'
235 argstr = 'edit -x ' + argstr
236 argstr = 'edit -x ' + argstr
236 ip.magic(argstr)
237 ip.magic(argstr)
237
238
238 ip.expose_magic('vim', vim)
239 ip.define_magic('vim', vim)
239
240
@@ -23,7 +23,7 b' def which(fname):'
23 return
23 return
24
24
25 def which_alias(fname):
25 def which_alias(fname):
26 for al, tgt in ip.IP.alias_table.items():
26 for al, tgt in ip.alias_table.items():
27 if not (al == fname or fnmatch(al, fname)):
27 if not (al == fname or fnmatch(al, fname)):
28 continue
28 continue
29 if callable(tgt):
29 if callable(tgt):
@@ -72,5 +72,5 b' def which_f(self, arg):'
72 for e in which(arg):
72 for e in which(arg):
73 print e
73 print e
74
74
75 ip.expose_magic("which",which_f)
75 ip.define_magic("which",which_f)
76
76
@@ -22,6 +22,7 b' For more details: https://bugs.launchpad.net/ipython/+bug/249036'
22 import os
22 import os
23
23
24 from IPython.core import ipapi
24 from IPython.core import ipapi
25 from IPython.core.error import UsageError
25 import rpdb2
26 import rpdb2
26
27
27 ip = ipapi.get()
28 ip = ipapi.get()
@@ -58,7 +59,7 b' def wdb_f(self, arg):'
58
59
59 path = os.path.abspath(arg)
60 path = os.path.abspath(arg)
60 if not os.path.isfile(path):
61 if not os.path.isfile(path):
61 raise ipapi.UsageError("%%wdb: file %s does not exist" % path)
62 raise UsageError("%%wdb: file %s does not exist" % path)
62 if not rpdb_started:
63 if not rpdb_started:
63 passwd = ip.db.get('winpdb_pass', None)
64 passwd = ip.db.get('winpdb_pass', None)
64 if passwd is None:
65 if passwd is None:
@@ -80,4 +81,4 b' def wdb_f(self, arg):'
80 ip.magic('%run ' + arg)
81 ip.magic('%run ' + arg)
81
82
82
83
83 ip.expose_magic('wdb', wdb_f)
84 ip.define_magic('wdb', wdb_f)
@@ -40,4 +40,4 b' def workdir_f(ip,line):'
40 finally:
40 finally:
41 os.chdir(olddir)
41 os.chdir(olddir)
42
42
43 ip.defalias("workdir",workdir_f)
43 ip.define_alias("workdir",workdir_f)
@@ -48,6 +48,7 b' import threading,Queue'
48 from IPython.utils import genutils
48 from IPython.utils import genutils
49
49
50 from IPython.core import ipapi
50 from IPython.core import ipapi
51 from IPython.core.error import TryNext
51
52
52 if os.name == 'nt':
53 if os.name == 'nt':
53 def kill_process(pid):
54 def kill_process(pid):
@@ -123,12 +124,12 b' def jobctrl_prefilter_f(self,line):'
123 if line.startswith('&'):
124 if line.startswith('&'):
124 pre,fn,rest = self.split_user_input(line[1:])
125 pre,fn,rest = self.split_user_input(line[1:])
125
126
126 line = ip.IP.expand_aliases(fn,rest)
127 line = ip.expand_aliases(fn,rest)
127 if not _jobq:
128 if not _jobq:
128 return '_ip.startjob(%s)' % genutils.make_quoted_expr(line)
129 return '_ip.startjob(%s)' % genutils.make_quoted_expr(line)
129 return '_ip.jobq(%s)' % genutils.make_quoted_expr(line)
130 return '_ip.jobq(%s)' % genutils.make_quoted_expr(line)
130
131
131 raise ipapi.TryNext
132 raise TryNext
132
133
133 def jobq_output_hook(self):
134 def jobq_output_hook(self):
134 if not _jobq:
135 if not _jobq:
@@ -235,8 +236,8 b' def install():'
235 ip.startjob = startjob
236 ip.startjob = startjob
236 ip.set_hook('input_prefilter', jobctrl_prefilter_f)
237 ip.set_hook('input_prefilter', jobctrl_prefilter_f)
237 ip.set_hook('shell_hook', jobctrl_shellcmd)
238 ip.set_hook('shell_hook', jobctrl_shellcmd)
238 ip.expose_magic('kill',magic_kill)
239 ip.define_magic('kill',magic_kill)
239 ip.expose_magic('tasks',magic_tasks)
240 ip.define_magic('tasks',magic_tasks)
240 ip.expose_magic('jobqueue',jobqueue_f)
241 ip.define_magic('jobqueue',jobqueue_f)
241 ip.set_hook('pre_prompt_hook', jobq_output_hook)
242 ip.set_hook('pre_prompt_hook', jobq_output_hook)
242 install()
243 install()
@@ -95,4 +95,4 b' def line_edit_complete_f(self,event):'
95
95
96 ip.set_hook('complete_command', line_edit_complete_f , str_key = '%led')
96 ip.set_hook('complete_command', line_edit_complete_f , str_key = '%led')
97
97
98 ip.expose_magic('led', line_edit_f) No newline at end of file
98 ip.define_magic('led', line_edit_f) No newline at end of file
@@ -6,7 +6,7 b' Stores variables, aliases etc. in PickleShare database.'
6 """
6 """
7
7
8 from IPython.core import ipapi
8 from IPython.core import ipapi
9 from IPython.core.ipapi import UsageError
9 from IPython.core.error import TryNext, UsageError
10 ip = ipapi.get()
10 ip = ipapi.get()
11
11
12 import pickleshare
12 import pickleshare
@@ -20,7 +20,7 b' def restore_aliases(self):'
20 for k,v in staliases.items():
20 for k,v in staliases.items():
21 #print "restore alias",k,v # dbg
21 #print "restore alias",k,v # dbg
22 #self.alias_table[k] = v
22 #self.alias_table[k] = v
23 ip.defalias(k,v)
23 ip.define_alias(k,v)
24
24
25
25
26 def refresh_variables(ip):
26 def refresh_variables(ip):
@@ -47,7 +47,7 b' def restore_data(self):'
47 refresh_variables(ip)
47 refresh_variables(ip)
48 restore_aliases(self)
48 restore_aliases(self)
49 restore_dhist(self)
49 restore_dhist(self)
50 raise ipapi.TryNext
50 raise TryNext
51
51
52 ip.set_hook('late_startup_hook', restore_data)
52 ip.set_hook('late_startup_hook', restore_data)
53
53
@@ -179,4 +179,4 b" def magic_store(self, parameter_s=''):"
179 self.db[ 'autorestore/' + args[0] ] = obj
179 self.db[ 'autorestore/' + args[0] ] = obj
180 print "Stored '%s' (%s)" % (args[0], obj.__class__.__name__)
180 print "Stored '%s' (%s)" % (args[0], obj.__class__.__name__)
181
181
182 ip.expose_magic('store',magic_store)
182 ip.define_magic('store',magic_store)
@@ -42,4 +42,4 b" def clip_f( self, parameter_s = '' ):"
42 print 'The following text was written to the clipboard'
42 print 'The following text was written to the clipboard'
43 print val
43 print val
44
44
45 ip.expose_magic( "clip", clip_f )
45 ip.define_magic( "clip", clip_f )
@@ -222,7 +222,7 b' def mglob_f(self, arg):'
222 def init_ipython(ip):
222 def init_ipython(ip):
223 """ register %mglob for IPython """
223 """ register %mglob for IPython """
224 mglob_f.__doc__ = globsyntax
224 mglob_f.__doc__ = globsyntax
225 ip.expose_magic("mglob",mglob_f)
225 ip.define_magic("mglob",mglob_f)
226
226
227 # test()
227 # test()
228 if __name__ == "__main__":
228 if __name__ == "__main__":
@@ -28,7 +28,6 b' import re'
28 import __builtin__
28 import __builtin__
29
29
30 from IPython.core.ipmaker import make_IPython
30 from IPython.core.ipmaker import make_IPython
31 from IPython.core.ipapi import IPApi
32 from IPython.kernel.core.redirector_output_trap import RedirectorOutputTrap
31 from IPython.kernel.core.redirector_output_trap import RedirectorOutputTrap
33
32
34 from IPython.kernel.core.sync_traceback_trap import SyncTracebackTrap
33 from IPython.kernel.core.sync_traceback_trap import SyncTracebackTrap
@@ -112,7 +111,7 b' class PrefilterFrontEnd(LineFrontEndBase):'
112 self.ipython0.set_hook('show_in_pager',
111 self.ipython0.set_hook('show_in_pager',
113 lambda s, string: self.write("\n" + string))
112 lambda s, string: self.write("\n" + string))
114 self.ipython0.write = self.write
113 self.ipython0.write = self.write
115 self._ip = _ip = IPApi(self.ipython0)
114 self._ip = _ip = self.ipython0
116 # Make sure the raw system call doesn't get called, as we don't
115 # Make sure the raw system call doesn't get called, as we don't
117 # have a stdin accessible.
116 # have a stdin accessible.
118 self._ip.system = self.system_call
117 self._ip.system = self.system_call
@@ -61,8 +61,8 b' def isolate_ipython0(func):'
61 if ip0 is None:
61 if ip0 is None:
62 return func()
62 return func()
63 # We have a real ipython running...
63 # We have a real ipython running...
64 user_ns = ip0.IP.user_ns
64 user_ns = ip0.user_ns
65 user_global_ns = ip0.IP.user_global_ns
65 user_global_ns = ip0.user_global_ns
66
66
67 # Previously the isolation was attempted with a deep copy of the user
67 # Previously the isolation was attempted with a deep copy of the user
68 # dicts, but we found cases where this didn't work correctly. I'm not
68 # dicts, but we found cases where this didn't work correctly. I'm not
@@ -189,7 +189,7 b' class NonBlockingIPShell(object):'
189 ip = ipapi.get()
189 ip = ipapi.get()
190 def bypass_magic(self, arg):
190 def bypass_magic(self, arg):
191 print '%this magic is currently disabled.'
191 print '%this magic is currently disabled.'
192 ip.expose_magic('cpaste', bypass_magic)
192 ip.define_magic('cpaste', bypass_magic)
193
193
194 import __builtin__
194 import __builtin__
195 __builtin__.raw_input = self._raw_input
195 __builtin__.raw_input = self._raw_input
@@ -492,7 +492,7 b' class NonBlockingIPShell(object):'
492 self._IP.showtraceback()
492 self._IP.showtraceback()
493 else:
493 else:
494 self._IP.write(str(self._IP.outputcache.prompt_out).strip())
494 self._IP.write(str(self._IP.outputcache.prompt_out).strip())
495 self._iter_more = self._IP.push(line)
495 self._iter_more = self._IP.push_line(line)
496 if (self._IP.SyntaxTB.last_syntax_error and \
496 if (self._IP.SyntaxTB.last_syntax_error and \
497 self._IP.autoedit_syntax):
497 self._IP.autoedit_syntax):
498 self._IP.edit_syntax_error()
498 self._IP.edit_syntax_error()
@@ -109,7 +109,7 b' class MyFrame(wx.Frame):'
109
109
110 def optionSave(self, name, value):
110 def optionSave(self, name, value):
111 ip = get()
111 ip = get()
112 path = ip.IP.config.IPYTHONDIR
112 path = ip.config.IPYTHONDIR
113 opt = open(path + '/options.conf','w')
113 opt = open(path + '/options.conf','w')
114
114
115 try:
115 try:
@@ -126,7 +126,7 b' class MyFrame(wx.Frame):'
126 def optionLoad(self):
126 def optionLoad(self):
127 try:
127 try:
128 ip = get()
128 ip = get()
129 path = ip.IP.config.IPYTHONDIR
129 path = ip.config.IPYTHONDIR
130 opt = open(path + '/options.conf','r')
130 opt = open(path + '/options.conf','r')
131 lines = opt.readlines()
131 lines = opt.readlines()
132 opt.close()
132 opt.close()
@@ -25,5 +25,5 b' to use the new IPython.core.ipapi module"""'
25
25
26 warn(msg, category=DeprecationWarning, stacklevel=1)
26 warn(msg, category=DeprecationWarning, stacklevel=1)
27
27
28 from IPython.core.ipapi import *
28 from IPython.core.ipapi import get
29
29
@@ -110,7 +110,7 b' class RemoteContextBase(object):'
110 def _findsource_ipython(self,f):
110 def _findsource_ipython(self,f):
111 from IPython.core import ipapi
111 from IPython.core import ipapi
112 self.ip = ipapi.get()
112 self.ip = ipapi.get()
113 buf = self.ip.IP.input_hist_raw[-1].splitlines()[1:]
113 buf = self.ip.input_hist_raw[-1].splitlines()[1:]
114 wsource = [l+'\n' for l in buf ]
114 wsource = [l+'\n' for l in buf ]
115
115
116 return strip_whitespace(wsource)
116 return strip_whitespace(wsource)
@@ -29,7 +29,7 b' from IPython.external.Itpl import ItplNS'
29
29
30 from IPython.utils import coloransi
30 from IPython.utils import coloransi
31 from IPython.core import release
31 from IPython.core import release
32 from IPython.core.ipapi import TryNext
32 from IPython.core.error import TryNext
33 from IPython.utils.genutils import *
33 from IPython.utils.genutils import *
34 import IPython.utils.generics
34 import IPython.utils.generics
35
35
@@ -314,7 +314,7 b' class InteractiveMultiEngineClient(object):'
314 from IPython.core import ipapi
314 from IPython.core import ipapi
315 self.ip = ipapi.get()
315 self.ip = ipapi.get()
316 wsource = [l+'\n' for l in
316 wsource = [l+'\n' for l in
317 self.ip.IP.input_hist_raw[-1].splitlines()[1:]]
317 self.ip.input_hist_raw[-1].splitlines()[1:]]
318 return strip_whitespace(wsource)
318 return strip_whitespace(wsource)
319
319
320 def __enter__(self):
320 def __enter__(self):
@@ -4,7 +4,7 b''
4 import subprocess
4 import subprocess
5 import sys
5 import sys
6
6
7 from IPython.core.ipapi import TryNext
7 from IPython.core.error import TryNext
8
8
9
9
10 def win32_clipboard_get():
10 def win32_clipboard_get():
@@ -23,6 +23,7 b' this mode, there is no way to pass IPython any command-line options, as those'
23 are trapped first by Python itself.
23 are trapped first by Python itself.
24 """
24 """
25
25
26 import IPython.core.shell
26 import IPython.core.ipapp import IPythonApp
27
27
28 IPython.core.shell.start().mainloop()
28 app = IPythonApp()
29 app.start()
@@ -105,7 +105,7 b' def _run_ns_sync(self,arg_s,runner=None):'
105 fname = arg_s
105 fname = arg_s
106
106
107 finder = py_file_finder(fname)
107 finder = py_file_finder(fname)
108 out = _ip.IP.magic_run_ori(arg_s,runner,finder)
108 out = _ip.magic_run_ori(arg_s,runner,finder)
109
109
110 # Simliarly, there is no test_globs when a test is NOT a doctest
110 # Simliarly, there is no test_globs when a test is NOT a doctest
111 if hasattr(_run_ns_sync,'test_globs'):
111 if hasattr(_run_ns_sync,'test_globs'):
@@ -172,7 +172,7 b' def start_ipython():'
172 This is just a convenience function to replace the IPython system call
172 This is just a convenience function to replace the IPython system call
173 with one that is more doctest-friendly.
173 with one that is more doctest-friendly.
174 """
174 """
175 cmd = _ip.IP.var_expand(cmd,depth=1)
175 cmd = _ip.var_expand(cmd,depth=1)
176 sys.stdout.write(commands.getoutput(cmd))
176 sys.stdout.write(commands.getoutput(cmd))
177 sys.stdout.flush()
177 sys.stdout.flush()
178
178
@@ -184,8 +184,7 b' def start_ipython():'
184 argv = default_argv()
184 argv = default_argv()
185
185
186 # Start IPython instance. We customize it to start with minimal frills.
186 # Start IPython instance. We customize it to start with minimal frills.
187 user_ns,global_ns = ipapi.make_user_namespaces(ipnsdict(),dict())
187 IPython.shell.IPShell(argv,ipnsdict(),global_ns)
188 IPython.shell.IPShell(argv,user_ns,global_ns)
189
188
190 # Deactivate the various python system hooks added by ipython for
189 # Deactivate the various python system hooks added by ipython for
191 # interactive convenience so we don't confuse the doctest system
190 # interactive convenience so we don't confuse the doctest system
@@ -204,16 +203,16 b' def start_ipython():'
204 _ip.system = xsys
203 _ip.system = xsys
205
204
206 # Also patch our %run function in.
205 # Also patch our %run function in.
207 im = new.instancemethod(_run_ns_sync,_ip.IP, _ip.IP.__class__)
206 im = new.instancemethod(_run_ns_sync,_ip, _ip.__class__)
208 _ip.IP.magic_run_ori = _ip.IP.magic_run
207 _ip.magic_run_ori = _ip.magic_run
209 _ip.IP.magic_run = im
208 _ip.magic_run = im
210
209
211 # XXX - For some very bizarre reason, the loading of %history by default is
210 # XXX - For some very bizarre reason, the loading of %history by default is
212 # failing. This needs to be fixed later, but for now at least this ensures
211 # failing. This needs to be fixed later, but for now at least this ensures
213 # that tests that use %hist run to completion.
212 # that tests that use %hist run to completion.
214 from IPython.core import history
213 from IPython.core import history
215 history.init_ipython(_ip)
214 history.init_ipython(_ip)
216 if not hasattr(_ip.IP,'magic_history'):
215 if not hasattr(_ip,'magic_history'):
217 raise RuntimeError("Can't load magics, aborting")
216 raise RuntimeError("Can't load magics, aborting")
218
217
219
218
@@ -437,8 +436,8 b' class DocTestCase(doctests.DocTestCase):'
437 # for IPython examples *only*, we swap the globals with the ipython
436 # for IPython examples *only*, we swap the globals with the ipython
438 # namespace, after updating it with the globals (which doctest
437 # namespace, after updating it with the globals (which doctest
439 # fills with the necessary info from the module being tested).
438 # fills with the necessary info from the module being tested).
440 _ip.IP.user_ns.update(self._dt_test.globs)
439 _ip.user_ns.update(self._dt_test.globs)
441 self._dt_test.globs = _ip.IP.user_ns
440 self._dt_test.globs = _ip.user_ns
442
441
443 super(DocTestCase, self).setUp()
442 super(DocTestCase, self).setUp()
444
443
@@ -539,7 +538,7 b' class IPDocTestParser(doctest.DocTestParser):'
539 # and turned into lines, so it looks to the parser like regular user
538 # and turned into lines, so it looks to the parser like regular user
540 # input
539 # input
541 for lnum,line in enumerate(source.strip().splitlines()):
540 for lnum,line in enumerate(source.strip().splitlines()):
542 newline(_ip.IP.prefilter(line,lnum>0))
541 newline(_ip.prefilter(line,lnum>0))
543 newline('') # ensure a closing newline, needed by doctest
542 newline('') # ensure a closing newline, needed by doctest
544 #print "PYSRC:", '\n'.join(out) # dbg
543 #print "PYSRC:", '\n'.join(out) # dbg
545 return '\n'.join(out)
544 return '\n'.join(out)
@@ -1,8 +1,8 b''
1 ''' 'Generic' functions for extending IPython.
1 """Generic functions for extending IPython.
2
2
3 See http://cheeseshop.python.org/pypi/simplegeneric.
3 See http://cheeseshop.python.org/pypi/simplegeneric.
4
4
5 Here is an example from genutils.py:
5 Here is an example from genutils.py::
6
6
7 def print_lsstring(arg):
7 def print_lsstring(arg):
8 "Prettier (non-repr-like) and more informative printer for LSString"
8 "Prettier (non-repr-like) and more informative printer for LSString"
@@ -10,45 +10,34 b' Here is an example from genutils.py:'
10 print arg
10 print arg
11
11
12 print_lsstring = result_display.when_type(LSString)(print_lsstring)
12 print_lsstring = result_display.when_type(LSString)(print_lsstring)
13 """
13
14
14 (Yes, the nasty syntax is for python 2.3 compatibility. Your own extensions
15 from IPython.core.error import TryNext
15 can use the niftier decorator syntax introduced in Python 2.4).
16 '''
17
18 from IPython.core.ipapi import TryNext
19 from IPython.external.simplegeneric import generic
16 from IPython.external.simplegeneric import generic
20
17
18 @generic
21 def result_display(result):
19 def result_display(result):
22 """ print the result of computation """
20 """Print the result of computation."""
23 raise TryNext
21 raise TryNext
24
22
25 result_display = generic(result_display)
23 @generic
26
27 def inspect_object(obj):
24 def inspect_object(obj):
28 """ Called when you do obj? """
25 """Called when you do obj?"""
29 raise TryNext
26 raise TryNext
30 inspect_object = generic(inspect_object)
31
27
28 @generic
32 def complete_object(obj, prev_completions):
29 def complete_object(obj, prev_completions):
33 """ Custom completer dispatching for python objects
30 """Custom completer dispatching for python objects.
34
31
35 obj is the object itself.
32 Parameters
36 prev_completions is the list of attributes discovered so far.
33 ----------
37
34 obj : object
35 The object to complete.
36 prev_completions : list
37 List of attributes discovered so far.
38
38 This should return the list of attributes in obj. If you only wish to
39 This should return the list of attributes in obj. If you only wish to
39 add to the attributes already discovered normally, return
40 add to the attributes already discovered normally, return
40 own_attrs + prev_completions.
41 own_attrs + prev_completions.
41 """
42 """
42
43 raise TryNext
43 raise TryNext
44 complete_object = generic(complete_object)
45
46 #import os
47 #def my_demo_complete_object(obj, prev_completions):
48 # """ Demo completer that adds 'foobar' to the completions suggested
49 # for any object that has attribute (path), e.g. 'os'"""
50 # if hasattr(obj,'path'):
51 # return prev_completions + ['foobar']
52 # raise TryNext
53 #
54 #my_demo_complete_object = complete_object.when_type(type(os))(my_demo_complete_object)
@@ -15,11 +15,7 b' these things are also convenient when working at the command line.'
15 #****************************************************************************
15 #****************************************************************************
16 # required modules from the Python standard library
16 # required modules from the Python standard library
17 import __main__
17 import __main__
18 import commands
18
19 try:
20 import doctest
21 except ImportError:
22 pass
23 import os
19 import os
24 import platform
20 import platform
25 import re
21 import re
@@ -27,7 +23,6 b' import shlex'
27 import shutil
23 import shutil
28 import subprocess
24 import subprocess
29 import sys
25 import sys
30 import tempfile
31 import time
26 import time
32 import types
27 import types
33 import warnings
28 import warnings
@@ -46,14 +41,10 b' else:'
46
41
47 # Other IPython utilities
42 # Other IPython utilities
48 import IPython
43 import IPython
49 from IPython.external.Itpl import Itpl,itpl,printpl
44 from IPython.external.Itpl import itpl,printpl
50 from IPython.utils import platutils
45 from IPython.utils import platutils
51 from IPython.utils import DPyGetOpt
52 from IPython.utils.generics import result_display
46 from IPython.utils.generics import result_display
53 from IPython.core import ipapi
54 from IPython.external.path import path
47 from IPython.external.path import path
55 if os.name == "nt":
56 from IPython.utils.winconsole import get_console_size
57
48
58 try:
49 try:
59 set
50 set
@@ -642,215 +633,6 b' def unquote_ends(istr):'
642 return istr
633 return istr
643
634
644 #----------------------------------------------------------------------------
635 #----------------------------------------------------------------------------
645 def process_cmdline(argv,names=[],defaults={},usage=''):
646 """ Process command-line options and arguments.
647
648 Arguments:
649
650 - argv: list of arguments, typically sys.argv.
651
652 - names: list of option names. See DPyGetOpt docs for details on options
653 syntax.
654
655 - defaults: dict of default values.
656
657 - usage: optional usage notice to print if a wrong argument is passed.
658
659 Return a dict of options and a list of free arguments."""
660
661 getopt = DPyGetOpt.DPyGetOpt()
662 getopt.setIgnoreCase(0)
663 getopt.parseConfiguration(names)
664
665 try:
666 getopt.processArguments(argv)
667 except DPyGetOpt.ArgumentError, exc:
668 print usage
669 warn('"%s"' % exc,level=4)
670
671 defaults.update(getopt.optionValues)
672 args = getopt.freeValues
673
674 return defaults,args
675
676 #----------------------------------------------------------------------------
677 def optstr2types(ostr):
678 """Convert a string of option names to a dict of type mappings.
679
680 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
681
682 This is used to get the types of all the options in a string formatted
683 with the conventions of DPyGetOpt. The 'type' None is used for options
684 which are strings (they need no further conversion). This function's main
685 use is to get a typemap for use with read_dict().
686 """
687
688 typeconv = {None:'',int:'',float:''}
689 typemap = {'s':None,'i':int,'f':float}
690 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
691
692 for w in ostr.split():
693 oname,alias,otype = opt_re.match(w).groups()
694 if otype == '' or alias == '!': # simple switches are integers too
695 otype = 'i'
696 typeconv[typemap[otype]] += oname + ' '
697 return typeconv
698
699 #----------------------------------------------------------------------------
700 def read_dict(filename,type_conv=None,**opt):
701 r"""Read a dictionary of key=value pairs from an input file, optionally
702 performing conversions on the resulting values.
703
704 read_dict(filename,type_conv,**opt) -> dict
705
706 Only one value per line is accepted, the format should be
707 # optional comments are ignored
708 key value\n
709
710 Args:
711
712 - type_conv: A dictionary specifying which keys need to be converted to
713 which types. By default all keys are read as strings. This dictionary
714 should have as its keys valid conversion functions for strings
715 (int,long,float,complex, or your own). The value for each key
716 (converter) should be a whitespace separated string containing the names
717 of all the entries in the file to be converted using that function. For
718 keys to be left alone, use None as the conversion function (only needed
719 with purge=1, see below).
720
721 - opt: dictionary with extra options as below (default in parens)
722
723 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
724 of the dictionary to be returned. If purge is going to be used, the
725 set of keys to be left as strings also has to be explicitly specified
726 using the (non-existent) conversion function None.
727
728 fs(None): field separator. This is the key/value separator to be used
729 when parsing the file. The None default means any whitespace [behavior
730 of string.split()].
731
732 strip(0): if 1, strip string values of leading/trailinig whitespace.
733
734 warn(1): warning level if requested keys are not found in file.
735 - 0: silently ignore.
736 - 1: inform but proceed.
737 - 2: raise KeyError exception.
738
739 no_empty(0): if 1, remove keys with whitespace strings as a value.
740
741 unique([]): list of keys (or space separated string) which can't be
742 repeated. If one such key is found in the file, each new instance
743 overwrites the previous one. For keys not listed here, the behavior is
744 to make a list of all appearances.
745
746 Example:
747
748 If the input file test.ini contains (we put it in a string to keep the test
749 self-contained):
750
751 >>> test_ini = '''\
752 ... i 3
753 ... x 4.5
754 ... y 5.5
755 ... s hi ho'''
756
757 Then we can use it as follows:
758 >>> type_conv={int:'i',float:'x',None:'s'}
759
760 >>> d = read_dict(test_ini)
761
762 >>> sorted(d.items())
763 [('i', '3'), ('s', 'hi ho'), ('x', '4.5'), ('y', '5.5')]
764
765 >>> d = read_dict(test_ini,type_conv)
766
767 >>> sorted(d.items())
768 [('i', 3), ('s', 'hi ho'), ('x', 4.5), ('y', '5.5')]
769
770 >>> d = read_dict(test_ini,type_conv,purge=True)
771
772 >>> sorted(d.items())
773 [('i', 3), ('s', 'hi ho'), ('x', 4.5)]
774 """
775
776 # starting config
777 opt.setdefault('purge',0)
778 opt.setdefault('fs',None) # field sep defaults to any whitespace
779 opt.setdefault('strip',0)
780 opt.setdefault('warn',1)
781 opt.setdefault('no_empty',0)
782 opt.setdefault('unique','')
783 if type(opt['unique']) in StringTypes:
784 unique_keys = qw(opt['unique'])
785 elif type(opt['unique']) in (types.TupleType,types.ListType):
786 unique_keys = opt['unique']
787 else:
788 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
789
790 dict = {}
791
792 # first read in table of values as strings
793 if '\n' in filename:
794 lines = filename.splitlines()
795 file = None
796 else:
797 file = open(filename,'r')
798 lines = file.readlines()
799 for line in lines:
800 line = line.strip()
801 if len(line) and line[0]=='#': continue
802 if len(line)>0:
803 lsplit = line.split(opt['fs'],1)
804 try:
805 key,val = lsplit
806 except ValueError:
807 key,val = lsplit[0],''
808 key = key.strip()
809 if opt['strip']: val = val.strip()
810 if val == "''" or val == '""': val = ''
811 if opt['no_empty'] and (val=='' or val.isspace()):
812 continue
813 # if a key is found more than once in the file, build a list
814 # unless it's in the 'unique' list. In that case, last found in file
815 # takes precedence. User beware.
816 try:
817 if dict[key] and key in unique_keys:
818 dict[key] = val
819 elif type(dict[key]) is types.ListType:
820 dict[key].append(val)
821 else:
822 dict[key] = [dict[key],val]
823 except KeyError:
824 dict[key] = val
825 # purge if requested
826 if opt['purge']:
827 accepted_keys = qwflat(type_conv.values())
828 for key in dict.keys():
829 if key in accepted_keys: continue
830 del(dict[key])
831 # now convert if requested
832 if type_conv==None: return dict
833 conversions = type_conv.keys()
834 try: conversions.remove(None)
835 except: pass
836 for convert in conversions:
837 for val in qw(type_conv[convert]):
838 try:
839 dict[val] = convert(dict[val])
840 except KeyError,e:
841 if opt['warn'] == 0:
842 pass
843 elif opt['warn'] == 1:
844 print >>sys.stderr, 'Warning: key',val,\
845 'not found in file',filename
846 elif opt['warn'] == 2:
847 raise KeyError,e
848 else:
849 raise ValueError,'Warning level must be 0,1 or 2'
850
851 return dict
852
853 #----------------------------------------------------------------------------
854 def flag_calls(func):
636 def flag_calls(func):
855 """Wrap a function to detect and flag when it gets called.
637 """Wrap a function to detect and flag when it gets called.
856
638
@@ -1368,16 +1150,6 b' def ask_yes_no(prompt,default=None):'
1368 return answers[ans]
1150 return answers[ans]
1369
1151
1370 #----------------------------------------------------------------------------
1152 #----------------------------------------------------------------------------
1371 def marquee(txt='',width=78,mark='*'):
1372 """Return the input string centered in a 'marquee'."""
1373 if not txt:
1374 return (mark*width)[:width]
1375 nmark = (width-len(txt)-2)/len(mark)/2
1376 if nmark < 0: nmark =0
1377 marks = mark*nmark
1378 return '%s %s %s' % (marks,txt,marks)
1379
1380 #----------------------------------------------------------------------------
1381 class EvalDict:
1153 class EvalDict:
1382 """
1154 """
1383 Emulate a dict which evaluates its contents in the caller's frame.
1155 Emulate a dict which evaluates its contents in the caller's frame.
@@ -1530,267 +1302,6 b' def native_line_ends(filename,backup=1):'
1530 except:
1302 except:
1531 pass
1303 pass
1532
1304
1533 #----------------------------------------------------------------------------
1534 def get_pager_cmd(pager_cmd = None):
1535 """Return a pager command.
1536
1537 Makes some attempts at finding an OS-correct one."""
1538
1539 if os.name == 'posix':
1540 default_pager_cmd = 'less -r' # -r for color control sequences
1541 elif os.name in ['nt','dos']:
1542 default_pager_cmd = 'type'
1543
1544 if pager_cmd is None:
1545 try:
1546 pager_cmd = os.environ['PAGER']
1547 except:
1548 pager_cmd = default_pager_cmd
1549 return pager_cmd
1550
1551 #-----------------------------------------------------------------------------
1552 def get_pager_start(pager,start):
1553 """Return the string for paging files with an offset.
1554
1555 This is the '+N' argument which less and more (under Unix) accept.
1556 """
1557
1558 if pager in ['less','more']:
1559 if start:
1560 start_string = '+' + str(start)
1561 else:
1562 start_string = ''
1563 else:
1564 start_string = ''
1565 return start_string
1566
1567 #----------------------------------------------------------------------------
1568 # (X)emacs on W32 doesn't like to be bypassed with msvcrt.getch()
1569 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
1570 import msvcrt
1571 def page_more():
1572 """ Smart pausing between pages
1573
1574 @return: True if need print more lines, False if quit
1575 """
1576 Term.cout.write('---Return to continue, q to quit--- ')
1577 ans = msvcrt.getch()
1578 if ans in ("q", "Q"):
1579 result = False
1580 else:
1581 result = True
1582 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1583 return result
1584 else:
1585 def page_more():
1586 ans = raw_input('---Return to continue, q to quit--- ')
1587 if ans.lower().startswith('q'):
1588 return False
1589 else:
1590 return True
1591
1592 esc_re = re.compile(r"(\x1b[^m]+m)")
1593
1594 def page_dumb(strng,start=0,screen_lines=25):
1595 """Very dumb 'pager' in Python, for when nothing else works.
1596
1597 Only moves forward, same interface as page(), except for pager_cmd and
1598 mode."""
1599
1600 out_ln = strng.splitlines()[start:]
1601 screens = chop(out_ln,screen_lines-1)
1602 if len(screens) == 1:
1603 print >>Term.cout, os.linesep.join(screens[0])
1604 else:
1605 last_escape = ""
1606 for scr in screens[0:-1]:
1607 hunk = os.linesep.join(scr)
1608 print >>Term.cout, last_escape + hunk
1609 if not page_more():
1610 return
1611 esc_list = esc_re.findall(hunk)
1612 if len(esc_list) > 0:
1613 last_escape = esc_list[-1]
1614 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1615
1616 #----------------------------------------------------------------------------
1617 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1618 """Print a string, piping through a pager after a certain length.
1619
1620 The screen_lines parameter specifies the number of *usable* lines of your
1621 terminal screen (total lines minus lines you need to reserve to show other
1622 information).
1623
1624 If you set screen_lines to a number <=0, page() will try to auto-determine
1625 your screen size and will only use up to (screen_size+screen_lines) for
1626 printing, paging after that. That is, if you want auto-detection but need
1627 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1628 auto-detection without any lines reserved simply use screen_lines = 0.
1629
1630 If a string won't fit in the allowed lines, it is sent through the
1631 specified pager command. If none given, look for PAGER in the environment,
1632 and ultimately default to less.
1633
1634 If no system pager works, the string is sent through a 'dumb pager'
1635 written in python, very simplistic.
1636 """
1637
1638 # Some routines may auto-compute start offsets incorrectly and pass a
1639 # negative value. Offset to 0 for robustness.
1640 start = max(0,start)
1641
1642 # first, try the hook
1643 ip = ipapi.get()
1644 if ip:
1645 try:
1646 ip.IP.hooks.show_in_pager(strng)
1647 return
1648 except ipapi.TryNext:
1649 pass
1650
1651 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1652 TERM = os.environ.get('TERM','dumb')
1653 if TERM in ['dumb','emacs'] and os.name != 'nt':
1654 print strng
1655 return
1656 # chop off the topmost part of the string we don't want to see
1657 str_lines = strng.split(os.linesep)[start:]
1658 str_toprint = os.linesep.join(str_lines)
1659 num_newlines = len(str_lines)
1660 len_str = len(str_toprint)
1661
1662 # Dumb heuristics to guesstimate number of on-screen lines the string
1663 # takes. Very basic, but good enough for docstrings in reasonable
1664 # terminals. If someone later feels like refining it, it's not hard.
1665 numlines = max(num_newlines,int(len_str/80)+1)
1666
1667 if os.name == "nt":
1668 screen_lines_def = get_console_size(defaulty=25)[1]
1669 else:
1670 screen_lines_def = 25 # default value if we can't auto-determine
1671
1672 # auto-determine screen size
1673 if screen_lines <= 0:
1674 if TERM=='xterm':
1675 use_curses = USE_CURSES
1676 else:
1677 # curses causes problems on many terminals other than xterm.
1678 use_curses = False
1679 if use_curses:
1680 # There is a bug in curses, where *sometimes* it fails to properly
1681 # initialize, and then after the endwin() call is made, the
1682 # terminal is left in an unusable state. Rather than trying to
1683 # check everytime for this (by requesting and comparing termios
1684 # flags each time), we just save the initial terminal state and
1685 # unconditionally reset it every time. It's cheaper than making
1686 # the checks.
1687 term_flags = termios.tcgetattr(sys.stdout)
1688 scr = curses.initscr()
1689 screen_lines_real,screen_cols = scr.getmaxyx()
1690 curses.endwin()
1691 # Restore terminal state in case endwin() didn't.
1692 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
1693 # Now we have what we needed: the screen size in rows/columns
1694 screen_lines += screen_lines_real
1695 #print '***Screen size:',screen_lines_real,'lines x',\
1696 #screen_cols,'columns.' # dbg
1697 else:
1698 screen_lines += screen_lines_def
1699
1700 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1701 if numlines <= screen_lines :
1702 #print '*** normal print' # dbg
1703 print >>Term.cout, str_toprint
1704 else:
1705 # Try to open pager and default to internal one if that fails.
1706 # All failure modes are tagged as 'retval=1', to match the return
1707 # value of a failed system command. If any intermediate attempt
1708 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1709 pager_cmd = get_pager_cmd(pager_cmd)
1710 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1711 if os.name == 'nt':
1712 if pager_cmd.startswith('type'):
1713 # The default WinXP 'type' command is failing on complex strings.
1714 retval = 1
1715 else:
1716 tmpname = tempfile.mktemp('.txt')
1717 tmpfile = file(tmpname,'wt')
1718 tmpfile.write(strng)
1719 tmpfile.close()
1720 cmd = "%s < %s" % (pager_cmd,tmpname)
1721 if os.system(cmd):
1722 retval = 1
1723 else:
1724 retval = None
1725 os.remove(tmpname)
1726 else:
1727 try:
1728 retval = None
1729 # if I use popen4, things hang. No idea why.
1730 #pager,shell_out = os.popen4(pager_cmd)
1731 pager = os.popen(pager_cmd,'w')
1732 pager.write(strng)
1733 pager.close()
1734 retval = pager.close() # success returns None
1735 except IOError,msg: # broken pipe when user quits
1736 if msg.args == (32,'Broken pipe'):
1737 retval = None
1738 else:
1739 retval = 1
1740 except OSError:
1741 # Other strange problems, sometimes seen in Win2k/cygwin
1742 retval = 1
1743 if retval is not None:
1744 page_dumb(strng,screen_lines=screen_lines)
1745
1746 #----------------------------------------------------------------------------
1747 def page_file(fname,start = 0, pager_cmd = None):
1748 """Page a file, using an optional pager command and starting line.
1749 """
1750
1751 pager_cmd = get_pager_cmd(pager_cmd)
1752 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1753
1754 try:
1755 if os.environ['TERM'] in ['emacs','dumb']:
1756 raise EnvironmentError
1757 xsys(pager_cmd + ' ' + fname)
1758 except:
1759 try:
1760 if start > 0:
1761 start -= 1
1762 page(open(fname).read(),start)
1763 except:
1764 print 'Unable to show file',`fname`
1765
1766
1767 #----------------------------------------------------------------------------
1768 def snip_print(str,width = 75,print_full = 0,header = ''):
1769 """Print a string snipping the midsection to fit in width.
1770
1771 print_full: mode control:
1772 - 0: only snip long strings
1773 - 1: send to page() directly.
1774 - 2: snip long strings and ask for full length viewing with page()
1775 Return 1 if snipping was necessary, 0 otherwise."""
1776
1777 if print_full == 1:
1778 page(header+str)
1779 return 0
1780
1781 print header,
1782 if len(str) < width:
1783 print str
1784 snip = 0
1785 else:
1786 whalf = int((width -5)/2)
1787 print str[:whalf] + ' <...> ' + str[-whalf:]
1788 snip = 1
1789 if snip and print_full == 2:
1790 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1791 page(str)
1792 return snip
1793
1794 #****************************************************************************
1305 #****************************************************************************
1795 # lists, dicts and structures
1306 # lists, dicts and structures
1796
1307
@@ -2259,6 +1770,8 b' def list_strings(arg):'
2259 if isinstance(arg,basestring): return [arg]
1770 if isinstance(arg,basestring): return [arg]
2260 else: return arg
1771 else: return arg
2261
1772
1773
1774 #----------------------------------------------------------------------------
2262 def marquee(txt='',width=78,mark='*'):
1775 def marquee(txt='',width=78,mark='*'):
2263 """Return the input string centered in a 'marquee'.
1776 """Return the input string centered in a 'marquee'.
2264
1777
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
This diff has been collapsed as it changes many lines, (793 lines changed) Show them Hide them
General Comments 0
You need to be logged in to leave comments. Login now