##// END OF EJS Templates
Defaults rename, clean up api to use properties or direct access rather than...
fperez -
Show More
@@ -16,7 +16,7 b' def clear_f(self,arg):'
16 api = self.getapi()
16 api = self.getapi()
17 for target in arg.split():
17 for target in arg.split():
18 if target == 'out':
18 if target == 'out':
19 print "Flushing output cache (%d entries)" % len(api.user_ns()['_oh'])
19 print "Flushing output cache (%d entries)" % len(api.user_ns['_oh'])
20 self.outputcache.flush()
20 self.outputcache.flush()
21 elif target == 'in':
21 elif target == 'in':
22 print "Flushing input history"
22 print "Flushing input history"
@@ -39,11 +39,11 b' def hnd_syscmd(line,mo):'
39 return itpl('$var = _ip.magic($expr)')
39 return itpl('$var = _ip.magic($expr)')
40
40
41 def install_re_handler(pat, hnd):
41 def install_re_handler(pat, hnd):
42 ip.meta().re_prefilters.append((re.compile(pat), hnd))
42 ip.meta.re_prefilters.append((re.compile(pat), hnd))
43
43
44 def init_handlers():
44 def init_handlers():
45
45
46 ip.meta().re_prefilters = []
46 ip.meta.re_prefilters = []
47
47
48 install_re_handler('(?P<varname>[\w\.]+)\s*=\s*%(?P<cmd>.*)',
48 install_re_handler('(?P<varname>[\w\.]+)\s*=\s*%(?P<cmd>.*)',
49 hnd_magic
49 hnd_magic
@@ -56,11 +56,11 b' def init_handlers():'
56 init_handlers()
56 init_handlers()
57
57
58 def regex_prefilter_f(self,line):
58 def regex_prefilter_f(self,line):
59 for pat, handler in ip.meta().re_prefilters:
59 for pat, handler in ip.meta.re_prefilters:
60 mo = pat.match(line)
60 mo = pat.match(line)
61 if mo:
61 if mo:
62 return handler(line,mo)
62 return handler(line,mo)
63
63
64 raise IPython.ipapi.TryNext
64 raise IPython.ipapi.TryNext
65
65
66 ip.set_hook('input_prefilter', regex_prefilter_f) No newline at end of file
66 ip.set_hook('input_prefilter', regex_prefilter_f)
@@ -259,7 +259,7 b' def item(iterator, index, default=noitem):'
259 def getglobals(g):
259 def getglobals(g):
260 if g is None:
260 if g is None:
261 if ipapi is not None:
261 if ipapi is not None:
262 return ipapi.get().user_ns()
262 return ipapi.get().user_ns
263 else:
263 else:
264 return globals()
264 return globals()
265 return g
265 return g
1 NO CONTENT: file renamed from IPython/Extensions/ipy_sane_defaults.py to IPython/Extensions/ipy_defaults.py
NO CONTENT: file renamed from IPython/Extensions/ipy_sane_defaults.py to IPython/Extensions/ipy_defaults.py
@@ -21,4 +21,4 b' import pspersistence # %store magic'
21 import clearcmd # %clear
21 import clearcmd # %clear
22 # Basic readline config
22 # Basic readline config
23
23
24 o = ip.options() No newline at end of file
24 o = ip.options
@@ -17,14 +17,14 b' from IPython.FakeModule import FakeModule'
17
17
18 def restore_aliases(self):
18 def restore_aliases(self):
19 ip = self.getapi()
19 ip = self.getapi()
20 staliases = ip.getdb().get('stored_aliases', {})
20 staliases = ip.db.get('stored_aliases', {})
21 for k,v in staliases.items():
21 for k,v in staliases.items():
22 #print "restore alias",k,v # dbg
22 #print "restore alias",k,v # dbg
23 self.alias_table[k] = v
23 self.alias_table[k] = v
24
24
25
25
26 def refresh_variables(ip):
26 def refresh_variables(ip):
27 db = ip.getdb()
27 db = ip.db
28 for key in db.keys('autorestore/*'):
28 for key in db.keys('autorestore/*'):
29 # strip autorestore
29 # strip autorestore
30 justkey = os.path.basename(key)
30 justkey = os.path.basename(key)
@@ -35,7 +35,7 b' def refresh_variables(ip):'
35 print "The error was:",sys.exc_info()[0]
35 print "The error was:",sys.exc_info()[0]
36 else:
36 else:
37 #print "restored",justkey,"=",obj #dbg
37 #print "restored",justkey,"=",obj #dbg
38 ip.user_ns()[justkey] = obj
38 ip.user_ns[justkey] = obj
39
39
40
40
41
41
@@ -83,7 +83,7 b" def magic_store(self, parameter_s=''):"
83 opts,argsl = self.parse_options(parameter_s,'drz',mode='string')
83 opts,argsl = self.parse_options(parameter_s,'drz',mode='string')
84 args = argsl.split(None,1)
84 args = argsl.split(None,1)
85 ip = self.getapi()
85 ip = self.getapi()
86 db = ip.getdb()
86 db = ip.db
87 # delete
87 # delete
88 if opts.has_key('d'):
88 if opts.has_key('d'):
89 try:
89 try:
@@ -148,7 +148,7 b" def magic_store(self, parameter_s=''):"
148
148
149 # %store foo
149 # %store foo
150 try:
150 try:
151 obj = ip.user_ns()[args[0]]
151 obj = ip.user_ns[args[0]]
152 except KeyError:
152 except KeyError:
153 # it might be an alias
153 # it might be an alias
154 if args[0] in self.alias_table:
154 if args[0] in self.alias_table:
@@ -1,7 +1,7 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3
3
4 $Id: Magic.py 1209 2006-03-12 20:34:28Z vivainio $"""
4 $Id: Magic.py 1314 2006-05-19 18:24:14Z fperez $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
@@ -26,6 +26,7 b' import inspect'
26 import os
26 import os
27 import pdb
27 import pdb
28 import pydoc
28 import pydoc
29 import shlex
29 import sys
30 import sys
30 import re
31 import re
31 import tempfile
32 import tempfile
@@ -317,7 +318,7 b' license. To use profiling, please install"python2.3-profiler" from non-free.""")'
317 if len(args) >= 1:
318 if len(args) >= 1:
318 # If the list of inputs only has 0 or 1 thing in it, there's no
319 # If the list of inputs only has 0 or 1 thing in it, there's no
319 # need to look for options
320 # need to look for options
320 argv = shlex_split(arg_str)
321 argv = shlex.split(arg_str)
321 # Do regular option processing
322 # Do regular option processing
322 try:
323 try:
323 opts,args = getopt(argv,opt_str,*long_opts)
324 opts,args = getopt(argv,opt_str,*long_opts)
@@ -1654,12 +1655,10 b' Currently the magic system has the following functions:\\n"""'
1654 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1655 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1655 else:
1656 else:
1656 order = 3
1657 order = 3
1657 print "%d loops, best of %d: %.*g %s per loop" % (number, repeat, precision,
1658 print "%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1659 precision,
1658 best * scaling[order],
1660 best * scaling[order],
1659 units[order])
1661 units[order])
1660
1661
1662
1663
1662
1664 def magic_time(self,parameter_s = ''):
1663 def magic_time(self,parameter_s = ''):
1665 """Time execution of a Python statement or expression.
1664 """Time execution of a Python statement or expression.
@@ -1669,9 +1668,8 b' Currently the magic system has the following functions:\\n"""'
1669 is always reported as 0, since it can not be measured.
1668 is always reported as 0, since it can not be measured.
1670
1669
1671 This function provides very basic timing functionality. In Python
1670 This function provides very basic timing functionality. In Python
1672 2.3, the timeit module offers more control and sophistication, but for
1671 2.3, the timeit module offers more control and sophistication, so this
1673 now IPython supports Python 2.2, so we can not rely on timeit being
1672 could be rewritten to use it (patches welcome).
1674 present.
1675
1673
1676 Some examples:
1674 Some examples:
1677
1675
@@ -2005,7 +2003,10 b' Currently the magic system has the following functions:\\n"""'
2005 # custom exceptions
2003 # custom exceptions
2006 class DataIsObject(Exception): pass
2004 class DataIsObject(Exception): pass
2007
2005
2008 opts,args = self.parse_options(parameter_s,'prx')
2006 opts,args = self.parse_options(parameter_s,'prxn=i')
2007
2008 print 'opt.n: <%r>' % opts.n # dbg
2009
2009 # Set a few locals from the options for convenience:
2010 # Set a few locals from the options for convenience:
2010 opts_p = opts.has_key('p')
2011 opts_p = opts.has_key('p')
2011 opts_r = opts.has_key('r')
2012 opts_r = opts.has_key('r')
@@ -2421,7 +2422,7 b' Defaulting color scheme to \'NoColor\'"""'
2421 # Call again init_auto_alias() so we get 'rm -i' and other
2422 # Call again init_auto_alias() so we get 'rm -i' and other
2422 # modified aliases since %rehashx will probably clobber them
2423 # modified aliases since %rehashx will probably clobber them
2423 self.shell.init_auto_alias()
2424 self.shell.init_auto_alias()
2424 db = self.getapi().getdb()
2425 db = self.getapi().db
2425 db['syscmdlist'] = syscmdlist
2426 db['syscmdlist'] = syscmdlist
2426 finally:
2427 finally:
2427 os.chdir(savedir)
2428 os.chdir(savedir)
@@ -2936,7 +2937,7 b' Defaulting color scheme to \'NoColor\'"""'
2936 ipinstallation = path(IPython.__file__).dirname()
2937 ipinstallation = path(IPython.__file__).dirname()
2937 upgrade_script = sys.executable + " " + ipinstallation / 'upgrade_dir.py'
2938 upgrade_script = sys.executable + " " + ipinstallation / 'upgrade_dir.py'
2938 src_config = ipinstallation / 'UserConfig'
2939 src_config = ipinstallation / 'UserConfig'
2939 userdir = path(ip.options().ipythondir)
2940 userdir = path(ip.options.ipythondir)
2940 cmd = upgrade_script + " " + src_config + " " + userdir
2941 cmd = upgrade_script + " " + src_config + " " + userdir
2941 print ">",cmd
2942 print ">",cmd
2942 shell(cmd)
2943 shell(cmd)
@@ -1,26 +1,23 b''
1 """ Shell mode for ipython
1 """Shell mode for IPython.
2
2
3 Start ipython in shell mode by invoking "ipython -p sh"
3 Start ipython in shell mode by invoking "ipython -p sh"
4
4
5 (the old version, "ipython -p pysh" still works but this is the more "modern"
5 (the old version, "ipython -p pysh" still works but this is the more "modern"
6 shell mode and is recommended for users who don't care about pysh-mode
6 shell mode and is recommended for users who don't care about pysh-mode
7 compatibility)
7 compatibility)
8
9
10 """
8 """
11
9
12
13 from IPython import ipapi
10 from IPython import ipapi
14 import os,textwrap
11 import os,textwrap
15
12
16 # The import below effectively obsoletes your old-style ipythonrc[.ini],
13 # The import below effectively obsoletes your old-style ipythonrc[.ini],
17 # so consider yourself warned!
14 # so consider yourself warned!
18
15
19 import ipy_sane_defaults
16 import ipy_defaults
20
17
21 def main():
18 def main():
22 ip = ipapi.get()
19 ip = ipapi.get()
23 o = ip.options()
20 o = ip.options
24 # autocall to "full" mode (smart mode is default, I like full mode)
21 # autocall to "full" mode (smart mode is default, I like full mode)
25
22
26 o.autocall = 2
23 o.autocall = 2
@@ -66,7 +63,7 b' def main():'
66
63
67 # now alias all syscommands
64 # now alias all syscommands
68
65
69 db = ip.getdb()
66 db = ip.db
70
67
71 syscmds = db.get("syscmdlist",[] )
68 syscmds = db.get("syscmdlist",[] )
72 if not syscmds:
69 if not syscmds:
@@ -20,10 +20,10 b' import IPython.ipapi'
20 ip = IPython.ipapi.get()
20 ip = IPython.ipapi.get()
21
21
22 # You probably want to uncomment this if you did %upgrade -nolegacy
22 # You probably want to uncomment this if you did %upgrade -nolegacy
23 # import ipy_sane_defaults
23 # import ipy_defaults
24
24
25 def main():
25 def main():
26 o = ip.options()
26 o = ip.options
27 # An example on how to set options
27 # An example on how to set options
28 #o.autocall = 1
28 #o.autocall = 1
29
29
@@ -25,9 +25,9 b' IPython tries to:'
25
25
26 iii - serve as an embeddable, ready to go interpreter for your own programs.
26 iii - serve as an embeddable, ready to go interpreter for your own programs.
27
27
28 IPython requires Python 2.2 or newer.
28 IPython requires Python 2.3 or newer.
29
29
30 $Id: __init__.py 1110 2006-01-30 20:43:30Z vivainio $"""
30 $Id: __init__.py 1314 2006-05-19 18:24:14Z fperez $"""
31
31
32 #*****************************************************************************
32 #*****************************************************************************
33 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
33 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
@@ -69,6 +69,7 b' import glob'
69 import keyword
69 import keyword
70 import os
70 import os
71 import re
71 import re
72 import shlex
72 import sys
73 import sys
73 import IPython.rlineimpl as readline
74 import IPython.rlineimpl as readline
74
75
@@ -80,8 +81,7 b' try:'
80 except NameError:
81 except NameError:
81 from sets import Set as set
82 from sets import Set as set
82
83
83
84 from IPython.genutils import debugx
84 from IPython.genutils import shlex_split,debugx
85
85
86 __all__ = ['Completer','IPCompleter']
86 __all__ = ['Completer','IPCompleter']
87
87
@@ -346,7 +346,7 b' class IPCompleter(Completer):'
346 lbuf = self.lbuf
346 lbuf = self.lbuf
347 open_quotes = 0 # track strings with open quotes
347 open_quotes = 0 # track strings with open quotes
348 try:
348 try:
349 lsplit = shlex_split(lbuf)[-1]
349 lsplit = shlex.split(lbuf)[-1]
350 except ValueError:
350 except ValueError:
351 # typically an unmatched ", or backslash without escaped char.
351 # typically an unmatched ", or backslash without escaped char.
352 if lbuf.count('"')==1:
352 if lbuf.count('"')==1:
@@ -122,10 +122,11 b" print 'bye!'"
122 import exceptions
122 import exceptions
123 import os
123 import os
124 import re
124 import re
125 import shlex
125 import sys
126 import sys
126
127
127 from IPython.PyColorize import Parser
128 from IPython.PyColorize import Parser
128 from IPython.genutils import marquee, shlex_split, file_read, file_readlines
129 from IPython.genutils import marquee, file_read, file_readlines
129
130
130 __all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']
131 __all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']
131
132
@@ -165,7 +166,7 b' class Demo:'
165 """
166 """
166
167
167 self.fname = fname
168 self.fname = fname
168 self.sys_argv = [fname] + shlex_split(arg_str)
169 self.sys_argv = [fname] + shlex.split(arg_str)
169 self.auto_all = auto_all
170 self.auto_all = auto_all
170
171
171 # get a few things from ipython. While it's a bit ugly design-wise,
172 # get a few things from ipython. While it's a bit ugly design-wise,
@@ -5,7 +5,7 b' General purpose utilities.'
5 This is a grab-bag of stuff I find useful in most programs I write. Some of
5 This is a grab-bag of stuff I find useful in most programs I write. Some of
6 these things are also convenient when working at the command line.
6 these things are also convenient when working at the command line.
7
7
8 $Id: genutils.py 1217 2006-03-16 21:49:01Z fperez $"""
8 $Id: genutils.py 1314 2006-05-19 18:24:14Z fperez $"""
9
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
11 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
@@ -14,8 +14,6 b' $Id: genutils.py 1217 2006-03-16 21:49:01Z fperez $"""'
14 # the file COPYING, distributed as part of this software.
14 # the file COPYING, distributed as part of this software.
15 #*****************************************************************************
15 #*****************************************************************************
16
16
17 from __future__ import generators # 2.2 compatibility
18
19 from IPython import Release
17 from IPython import Release
20 __author__ = '%s <%s>' % Release.authors['Fernando']
18 __author__ = '%s <%s>' % Release.authors['Fernando']
21 __license__ = Release.license
19 __license__ = Release.license
@@ -26,7 +24,6 b' import __main__'
26 import commands
24 import commands
27 import os
25 import os
28 import re
26 import re
29 import shlex
30 import shutil
27 import shutil
31 import sys
28 import sys
32 import tempfile
29 import tempfile
@@ -40,66 +37,6 b' from path import path'
40 if os.name == "nt":
37 if os.name == "nt":
41 from IPython.winconsole import get_console_size
38 from IPython.winconsole import get_console_size
42
39
43 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
44 # 2.2-friendly
45 try:
46 basestring
47 except NameError:
48 import types
49 basestring = (types.StringType, types.UnicodeType)
50 True = 1==1
51 False = 1==0
52
53 def enumerate(obj):
54 i = -1
55 for item in obj:
56 i += 1
57 yield i, item
58
59 # add these to the builtin namespace, so that all modules find them
60 import __builtin__
61 __builtin__.basestring = basestring
62 __builtin__.True = True
63 __builtin__.False = False
64 __builtin__.enumerate = enumerate
65
66 # Try to use shlex.split for converting an input string into a sys.argv-type
67 # list. This appeared in Python 2.3, so here's a quick backport for 2.2.
68 try:
69 shlex_split = shlex.split
70 except AttributeError:
71 _quotesre = re.compile(r'[\'"](.*)[\'"]')
72 _wordchars = ('abcdfeghijklmnopqrstuvwxyz'
73 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?'
74 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
75 '�����ÅÆÇ�ÉÊ�Ì�Î��ÑÒÓÔÕÖ�ÙÚ�Ü�Þ%s'
76 % os.sep)
77
78 def shlex_split(s):
79 """Simplified backport to Python 2.2 of shlex.split().
80
81 This is a quick and dirty hack, since the shlex module under 2.2 lacks
82 several of the features needed to really match the functionality of
83 shlex.split() in 2.3."""
84
85 lex = shlex.shlex(StringIO(s))
86 # Try to get options, extensions and path separators as characters
87 lex.wordchars = _wordchars
88 lex.commenters = ''
89 # Make a list out of the lexer by hand, since in 2.2 it's not an
90 # iterator.
91 lout = []
92 while 1:
93 token = lex.get_token()
94 if token == '':
95 break
96 # Try to handle quoted tokens correctly
97 quotes = _quotesre.match(token)
98 if quotes:
99 token = quotes.group(1)
100 lout.append(token)
101 return lout
102
103 #****************************************************************************
40 #****************************************************************************
104 # Exceptions
41 # Exceptions
105 class Error(Exception):
42 class Error(Exception):
@@ -1622,16 +1559,6 b" def list2dict2(lst,default=''):"
1622 def flatten(seq):
1559 def flatten(seq):
1623 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1560 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1624
1561
1625 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1626
1627 # if the x=0 isn't made, a *global* variable x is left over after calling
1628 # this function, with the value of the last element in the return
1629 # list. This does seem like a bug big time to me.
1630
1631 # the problem is fixed with the x=0, which seems to force the creation of
1632 # a local name
1633
1634 x = 0
1635 return [x for subseq in seq for x in subseq]
1562 return [x for subseq in seq for x in subseq]
1636
1563
1637 #----------------------------------------------------------------------------
1564 #----------------------------------------------------------------------------
@@ -25,7 +25,8 b' personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME'
25 stuff) in there.
25 stuff) in there.
26
26
27 -----------------------------------------------
27 -----------------------------------------------
28 import IPython.ipapi as ip
28 import IPython.ipapi
29 ip = IPython.ipapi.get()
29
30
30 def ankka_f(self, arg):
31 def ankka_f(self, arg):
31 print "Ankka",self,"says uppercase:",arg.upper()
32 print "Ankka",self,"says uppercase:",arg.upper()
@@ -53,55 +54,82 b' def jed_editor(self,filename, linenum=None):'
53
54
54 ip.set_hook('editor',jed_editor)
55 ip.set_hook('editor',jed_editor)
55
56
56 o = ip.options()
57 o = ip.options
57 o.autocall = 2 # FULL autocall mode
58 o.autocall = 2 # FULL autocall mode
58
59
59 print "done!"
60 print "done!"
60
61 '''
61 '''
62
62
63 # stdlib imports
64 import sys
65
66 # our own
67 from IPython.genutils import warn,error
63
68
64 class TryNext(Exception):
69 class TryNext(Exception):
65 """ Try next hook exception.
70 """Try next hook exception.
66
71
67 Raise this in your hook function to indicate that the next
72 Raise this in your hook function to indicate that the next hook handler
68 hook handler should be used to handle the operation.
73 should be used to handle the operation. If you pass arguments to the
69 If you pass arguments to the constructor those arguments will be
74 constructor those arguments will be used by the next hook instead of the
70 used by the next hook instead of the original ones.
75 original ones.
71 """
76 """
72
77
73 def __init__(self, *args, **kwargs):
78 def __init__(self, *args, **kwargs):
74 self.args = args
79 self.args = args
75 self.kwargs = kwargs
80 self.kwargs = kwargs
76
81
77
78 # contains the most recently instantiated IPApi
82 # contains the most recently instantiated IPApi
79 _recent = None
83
84 class IPythonNotRunning:
85 """Dummy do-nothing class.
86
87 Instances of this class return a dummy attribute on all accesses, which
88 can be called and warns. This makes it easier to write scripts which use
89 the ipapi.get() object for informational purposes to operate both with and
90 without ipython. Obviously code which uses the ipython object for
91 computations will not work, but this allows a wider range of code to
92 transparently work whether ipython is being used or not."""
93
94 def __str__(self):
95 return "<IPythonNotRunning>"
96
97 __repr__ = __str__
98
99 def __getattr__(self,name):
100 return self.dummy
101
102 def dummy(self,*args,**kw):
103 """Dummy function, which doesn't do anything but warn."""
104 warn("IPython is not running, this is a dummy no-op function")
105
106 _recent = IPythonNotRunning()
80
107
81 def get():
108 def get():
82 """ Get an IPApi object, or None if not running under ipython
109 """Get an IPApi object.
83
110
84 Running this should be the first thing you do when writing
111 Returns an instance of IPythonNotRunning if not running under IPython.
85 extensions that can be imported as normal modules. You can then
86 direct all the configuration operations against the returned
87 object.
88
112
113 Running this should be the first thing you do when writing extensions that
114 can be imported as normal modules. You can then direct all the
115 configuration operations against the returned object.
89 """
116 """
90
117
91 return _recent
118 return _recent
92
119
93
94
95 class IPApi:
120 class IPApi:
96 """ The actual API class for configuring IPython
121 """ The actual API class for configuring IPython
97
122
98 You should do all of the IPython configuration by getting
123 You should do all of the IPython configuration by getting an IPApi object
99 an IPApi object with IPython.ipapi.get() and using the provided
124 with IPython.ipapi.get() and using the attributes and methods of the
100 methods.
125 returned object."""
101
126
102 """
103 def __init__(self,ip):
127 def __init__(self,ip):
104
128
129 # All attributes exposed here are considered to be the public API of
130 # IPython. As needs dictate, some of these may be wrapped as
131 # properties.
132
105 self.magic = ip.ipmagic
133 self.magic = ip.ipmagic
106
134
107 self.system = ip.ipsystem
135 self.system = ip.ipsystem
@@ -109,19 +137,34 b' class IPApi:'
109 self.set_hook = ip.set_hook
137 self.set_hook = ip.set_hook
110
138
111 self.set_custom_exc = ip.set_custom_exc
139 self.set_custom_exc = ip.set_custom_exc
112
140
141 self.user_ns = ip.user_ns
142
143 # Session-specific data store, which can be used to store
144 # data that should persist through the ipython session.
145 self.meta = ip.meta
146
147 # The ipython instance provided
113 self.IP = ip
148 self.IP = ip
149
114 global _recent
150 global _recent
115 _recent = self
151 _recent = self
116
152
117
153 # Use a property for some things which are added to the instance very
118
154 # late. I don't have time right now to disentangle the initialization
119 def options(self):
155 # order issues, so a property lets us delay item extraction while
120 """ All configurable variables """
156 # providing a normal attribute API.
157 def get_db(self):
158 """A handle to persistent dict-like database (a PickleShareDB object)"""
159 return self.IP.db
160
161 db = property(get_db,None,None,get_db.__doc__)
162
163 def get_options(self):
164 """All configurable variables."""
121 return self.IP.rc
165 return self.IP.rc
122
166
123 def user_ns(self):
167 options = property(get_options,None,None,get_options.__doc__)
124 return self.IP.user_ns
125
168
126 def expose_magic(self,magicname, func):
169 def expose_magic(self,magicname, func):
127 ''' Expose own function as magic function for ipython
170 ''' Expose own function as magic function for ipython
@@ -138,31 +181,16 b' class IPApi:'
138 im = new.instancemethod(func,self.IP, self.IP.__class__)
181 im = new.instancemethod(func,self.IP, self.IP.__class__)
139 setattr(self.IP, "magic_" + magicname, im)
182 setattr(self.IP, "magic_" + magicname, im)
140
183
141
142 def ex(self,cmd):
184 def ex(self,cmd):
143 """ Execute a normal python statement in user namespace """
185 """ Execute a normal python statement in user namespace """
144 exec cmd in self.user_ns()
186 exec cmd in self.user_ns
145
187
146 def ev(self,expr):
188 def ev(self,expr):
147 """ Evaluate python expression expr in user namespace
189 """ Evaluate python expression expr in user namespace
148
190
149 Returns the result of evaluation"""
191 Returns the result of evaluation"""
150 return eval(expr,self.user_ns())
192 return eval(expr,self.user_ns)
151
193
152 def meta(self):
153 """ Get a session-specific data store
154
155 Object returned by this method can be used to store
156 data that should persist through the ipython session.
157 """
158 return self.IP.meta
159
160 def getdb(self):
161 """ Return a handle to persistent dict-like database
162
163 Return a PickleShareDB object.
164 """
165 return self.IP.db
166 def runlines(self,lines):
194 def runlines(self,lines):
167 """ Run the specified lines in interpreter, honoring ipython directives.
195 """ Run the specified lines in interpreter, honoring ipython directives.
168
196
@@ -175,6 +203,96 b' class IPApi:'
175 else:
203 else:
176 self.IP.runlines('\n'.join(lines))
204 self.IP.runlines('\n'.join(lines))
177
205
206 def to_user_ns(self,*vars):
207 """Inject a group of variables into the IPython user namespace.
208
209 Inputs:
210
211 - *vars: one or more variables from the caller's namespace to be put
212 into the interactive IPython namespace. The arguments can be given
213 in one of two forms, but ALL arguments must follow the same
214 convention (the first is checked and the rest are assumed to follow
215 it):
216
217 a) All strings, naming variables in the caller. These names are
218 evaluated in the caller's frame and put in, with the same name, in
219 the IPython namespace.
220
221 b) Pairs of (name, value), where the name is a string (a valid
222 python identifier). In this case, the value is put into the
223 IPython namespace labeled by the given name. This allows you to
224 rename your local variables so they don't collide with other names
225 you may already be using globally, or elsewhere and which you also
226 want to propagate.
227
228
229 This utility routine is meant to ease interactive debugging work,
230 where you want to easily propagate some internal variable in your code
231 up to the interactive namespace for further exploration.
232
233 When you run code via %run, globals in your script become visible at
234 the interactive prompt, but this doesn't happen for locals inside your
235 own functions and methods. Yet when debugging, it is common to want
236 to explore some internal variables further at the interactive propmt.
237
238 Examples:
239
240 To use this, you first must obtain a handle on the ipython object as
241 indicated above, via:
242
243 import IPython.ipapi
244 ip = IPython.ipapi.get()
245
246 Once this is done, inside a routine foo() where you want to expose
247 variables x and y, you do the following:
248
249 def foo():
250 ...
251 x = your_computation()
252 y = something_else()
253
254 # This pushes x and y to the interactive prompt immediately, even
255 # if this routine crashes on the next line after:
256 ip.to_user_ns('x','y')
257 ...
258 # return
259
260 The following example shows you how to rename variables to avoid
261 clashes:
262
263 def bar():
264 ...
265 x,y,z,w = foo()
266
267 # Push these variables with different names, so they don't
268 # overwrite x and y from before
269 ip.to_user_ns(('x1',x),('y1',y),('z1',z),('w1',w))
270 # which is more conveniently written as:
271 ip.to_user_ns(*zip(('x1','y1','z1','w1'),(x,y,z,w)))
272
273 ...
274 # return """
275
276 # print 'vars given:',vars # dbg
277 # Get the caller's frame to evaluate the given names in
278 cf = sys._getframe(1)
279
280 # XXX fix this after Ville replies...
281 user_ns = self.user_ns
282
283 if isinstance(vars[0],basestring):
284 # assume that all variables are given as strings
285 try:
286 for name in vars:
287 user_ns[name] = eval(name,cf.f_globals,cf.f_locals)
288 except:
289 error('could not get var. %s from %s' %
290 (name,cf.f_code.co_name))
291
292 else:
293 # assume they are all given as pairs of name,object
294 user_ns.update(dict(vars))
295
178
296
179 def launch_new_instance(user_ns = None):
297 def launch_new_instance(user_ns = None):
180 """ Create and start a new ipython instance.
298 """ Create and start a new ipython instance.
@@ -200,4 +318,4 b' def create_session(user_ns = None):'
200 if user_ns is not None:
318 if user_ns is not None:
201 user_ns["__name__"] = user_ns.get("__name__",'ipy_session')
319 user_ns["__name__"] = user_ns.get("__name__",'ipy_session')
202 import IPython
320 import IPython
203 return IPython.Shell.start(user_ns = user_ns) No newline at end of file
321 return IPython.Shell.start(user_ns = user_ns)
@@ -6,7 +6,7 b' Requires Python 2.3 or newer.'
6
6
7 This file contains all the classes and helper functions specific to IPython.
7 This file contains all the classes and helper functions specific to IPython.
8
8
9 $Id: iplib.py 1277 2006-05-02 10:31:55Z walter.doerwald $
9 $Id: iplib.py 1314 2006-05-19 18:24:14Z fperez $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
@@ -28,8 +28,6 b' $Id: iplib.py 1277 2006-05-02 10:31:55Z walter.doerwald $'
28 #****************************************************************************
28 #****************************************************************************
29 # Modules and globals
29 # Modules and globals
30
30
31 from __future__ import generators # for 2.2 backwards-compatibility
32
33 from IPython import Release
31 from IPython import Release
34 __author__ = '%s <%s>\n%s <%s>' % \
32 __author__ = '%s <%s>\n%s <%s>' % \
35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
@@ -196,10 +194,6 b' class InteractiveShell(object,Magic):'
196 # log system
194 # log system
197 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
195 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
198
196
199 # Produce a public API instance
200
201 self.api = IPython.ipapi.IPApi(self)
202
203 # some minimal strict typechecks. For some core data structures, I
197 # some minimal strict typechecks. For some core data structures, I
204 # want actual basic python types, not just anything that looks like
198 # want actual basic python types, not just anything that looks like
205 # one. This is especially true for namespaces.
199 # one. This is especially true for namespaces.
@@ -210,12 +204,6 b' class InteractiveShell(object,Magic):'
210 # Job manager (for jobs run as background threads)
204 # Job manager (for jobs run as background threads)
211 self.jobs = BackgroundJobManager()
205 self.jobs = BackgroundJobManager()
212
206
213 # track which builtins we add, so we can clean up later
214 self.builtins_added = {}
215 # This method will add the necessary builtins for operation, but
216 # tracking what it did via the builtins_added dict.
217 self.add_builtins()
218
219 # Do the intuitively correct thing for quit/exit: we remove the
207 # Do the intuitively correct thing for quit/exit: we remove the
220 # builtins if they exist, and our own magics will deal with this
208 # builtins if they exist, and our own magics will deal with this
221 try:
209 try:
@@ -599,6 +587,16 b' class InteractiveShell(object,Magic):'
599 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
587 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
600 # Call the actual (public) initializer
588 # Call the actual (public) initializer
601 self.init_auto_alias()
589 self.init_auto_alias()
590
591 # Produce a public API instance
592 self.api = IPython.ipapi.IPApi(self)
593
594 # track which builtins we add, so we can clean up later
595 self.builtins_added = {}
596 # This method will add the necessary builtins for operation, but
597 # tracking what it did via the builtins_added dict.
598 self.add_builtins()
599
602 # end __init__
600 # end __init__
603
601
604 def pre_config_initialization(self):
602 def pre_config_initialization(self):
@@ -612,7 +610,6 b' class InteractiveShell(object,Magic):'
612 rc = self.rc
610 rc = self.rc
613
611
614 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
612 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
615
616
613
617 def post_config_initialization(self):
614 def post_config_initialization(self):
618 """Post configuration init method
615 """Post configuration init method
General Comments 0
You need to be logged in to leave comments. Login now