##// END OF EJS Templates
switch to _ip.load -> init_ipython(ip) approach for loading IPython modules
vivainio -
Show More
@@ -1,24 +1,24 b''
1 """ System wide configuration file for IPython.
1 """ System wide configuration file for IPython.
2
2
3 This will be imported by ipython for all users.
3 This will be imported by ipython for all users.
4
4
5 After this ipy_user_conf.py is imported, user specific configuration
5 After this ipy_user_conf.py is imported, user specific configuration
6 should reside there.
6 should reside there.
7
7
8 """
8 """
9
9
10 import IPython.ipapi
10 import IPython.ipapi
11 ip = IPython.ipapi.get()
11 ip = IPython.ipapi.get()
12
12
13 # add system wide configuration information, import extensions etc. here.
13 # add system wide configuration information, import extensions etc. here.
14 # nothing here is essential
14 # nothing here is essential
15
15
16 import sys
16 import sys
17
17
18 import ext_rescapture # var = !ls and var = %magic
18 import ext_rescapture # var = !ls and var = %magic
19 import pspersistence # %store magic
19 import pspersistence # %store magic
20 import clearcmd # %clear
20 import clearcmd # %clear
21
21
22 import ipy_stock_completers
22 import ipy_stock_completers
23
23
24 import IPython.history
24 ip.load('IPython.history')
@@ -1,172 +1,173 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 """ History related magics and functionality """
3 """ History related magics and functionality """
4
4
5 import IPython.ipapi
6 ip = IPython.ipapi.get(allow_dummy = True)
7
8 import fnmatch
5 import fnmatch
9
6
10 def magic_history(self, parameter_s = ''):
7 def magic_history(self, parameter_s = ''):
11 """Print input history (_i<n> variables), with most recent last.
8 """Print input history (_i<n> variables), with most recent last.
12
9
13 %history -> print at most 40 inputs (some may be multi-line)\\
10 %history -> print at most 40 inputs (some may be multi-line)\\
14 %history n -> print at most n inputs\\
11 %history n -> print at most n inputs\\
15 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
12 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
16
13
17 Each input's number <n> is shown, and is accessible as the
14 Each input's number <n> is shown, and is accessible as the
18 automatically generated variable _i<n>. Multi-line statements are
15 automatically generated variable _i<n>. Multi-line statements are
19 printed starting at a new line for easy copy/paste.
16 printed starting at a new line for easy copy/paste.
20
17
21
18
22 Options:
19 Options:
23
20
24 -n: do NOT print line numbers. This is useful if you want to get a
21 -n: do NOT print line numbers. This is useful if you want to get a
25 printout of many lines which can be directly pasted into a text
22 printout of many lines which can be directly pasted into a text
26 editor.
23 editor.
27
24
28 This feature is only available if numbered prompts are in use.
25 This feature is only available if numbered prompts are in use.
29
26
30 -t: print the 'translated' history, as IPython understands it. IPython
27 -t: print the 'translated' history, as IPython understands it. IPython
31 filters your input and converts it all into valid Python source before
28 filters your input and converts it all into valid Python source before
32 executing it (things like magics or aliases are turned into function
29 executing it (things like magics or aliases are turned into function
33 calls, for example). With this option, you'll see the native history
30 calls, for example). With this option, you'll see the native history
34 instead of the user-entered version: '%cd /' will be seen as
31 instead of the user-entered version: '%cd /' will be seen as
35 '_ip.magic("%cd /")' instead of '%cd /'.
32 '_ip.magic("%cd /")' instead of '%cd /'.
36
33
37 -g: treat the arg as a pattern to grep for in (full) history
34 -g: treat the arg as a pattern to grep for in (full) history
38
35
39 """
36 """
40
37
41 shell = self.shell
38 shell = self.shell
42 if not shell.outputcache.do_full_cache:
39 if not shell.outputcache.do_full_cache:
43 print 'This feature is only available if numbered prompts are in use.'
40 print 'This feature is only available if numbered prompts are in use.'
44 return
41 return
45 opts,args = self.parse_options(parameter_s,'gnt',mode='list')
42 opts,args = self.parse_options(parameter_s,'gnt',mode='list')
46
43
47 if not opts.has_key('t'):
44 if not opts.has_key('t'):
48 input_hist = shell.input_hist_raw
45 input_hist = shell.input_hist_raw
49 else:
46 else:
50 input_hist = shell.input_hist
47 input_hist = shell.input_hist
51
48
52 default_length = 40
49 default_length = 40
53 pattern = None
50 pattern = None
54 if opts.has_key('g'):
51 if opts.has_key('g'):
55 init = 1
52 init = 1
56 final = len(input_hist)
53 final = len(input_hist)
57 head, pattern = parameter_s.split(None,1)
54 head, pattern = parameter_s.split(None,1)
58 pattern = "*" + pattern + "*"
55 pattern = "*" + pattern + "*"
59 elif len(args) == 0:
56 elif len(args) == 0:
60 final = len(input_hist)
57 final = len(input_hist)
61 init = max(1,final-default_length)
58 init = max(1,final-default_length)
62 elif len(args) == 1:
59 elif len(args) == 1:
63 final = len(input_hist)
60 final = len(input_hist)
64 init = max(1,final-int(args[0]))
61 init = max(1,final-int(args[0]))
65 elif len(args) == 2:
62 elif len(args) == 2:
66 init,final = map(int,args)
63 init,final = map(int,args)
67 else:
64 else:
68 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
65 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
69 print self.magic_hist.__doc__
66 print self.magic_hist.__doc__
70 return
67 return
71 width = len(str(final))
68 width = len(str(final))
72 line_sep = ['','\n']
69 line_sep = ['','\n']
73 print_nums = not opts.has_key('n')
70 print_nums = not opts.has_key('n')
74 for in_num in range(init,final):
71 for in_num in range(init,final):
75 inline = input_hist[in_num]
72 inline = input_hist[in_num]
76 if pattern is not None and not fnmatch.fnmatch(inline, pattern):
73 if pattern is not None and not fnmatch.fnmatch(inline, pattern):
77 continue
74 continue
78
75
79 multiline = int(inline.count('\n') > 1)
76 multiline = int(inline.count('\n') > 1)
80 if print_nums:
77 if print_nums:
81 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
78 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
82 print inline,
79 print inline,
83
80
84 ip.expose_magic("history",magic_history)
81
85
82
86 def magic_hist(self, parameter_s=''):
83 def magic_hist(self, parameter_s=''):
87 """Alternate name for %history."""
84 """Alternate name for %history."""
88 return self.magic_history(parameter_s)
85 return self.magic_history(parameter_s)
89
86
90 ip.expose_magic("hist",magic_hist)
87
91
88
92 def rep_f(self, arg):
89 def rep_f(self, arg):
93 r""" Repeat a command, or get command to input line for editing
90 r""" Repeat a command, or get command to input line for editing
94
91
95 - %rep (no arguments):
92 - %rep (no arguments):
96
93
97 Place a string version of last input to the next input prompt. Allows you
94 Place a string version of last input to the next input prompt. Allows you
98 to create elaborate command lines without using copy-paste::
95 to create elaborate command lines without using copy-paste::
99
96
100 $ l = ["hei", "vaan"]
97 $ l = ["hei", "vaan"]
101 $ "".join(l)
98 $ "".join(l)
102 ==> heivaan
99 ==> heivaan
103 $ %rep
100 $ %rep
104 $ heivaan_ <== cursor blinking
101 $ heivaan_ <== cursor blinking
105
102
106 %rep 45
103 %rep 45
107
104
108 Place history line 45 to next input prompt. Use %hist to find out the number.
105 Place history line 45 to next input prompt. Use %hist to find out the number.
109
106
110 %rep 1-4 6-7 3
107 %rep 1-4 6-7 3
111
108
112 Repeat the specified lines immediately. Input slice syntax is the same as
109 Repeat the specified lines immediately. Input slice syntax is the same as
113 in %macro and %save.
110 in %macro and %save.
114
111
115 """
112 """
116
113
117
114
118 opts,args = self.parse_options(arg,'',mode='list')
115 opts,args = self.parse_options(arg,'',mode='list')
119
116 ip = self.api
120 if not args:
117 if not args:
121 ip.set_next_input(str(ip.user_ns["_"]))
118 ip.set_next_input(str(ip.user_ns["_"]))
122 return
119 return
123
120
124 if len(args) == 1:
121 if len(args) == 1:
125 try:
122 try:
126 num = int(args[0])
123 num = int(args[0])
127 ip.set_next_input(str(ip.IP.input_hist_raw[num]).rstrip())
124 ip.set_next_input(str(ip.IP.input_hist_raw[num]).rstrip())
128 return
125 return
129 except ValueError:
126 except ValueError:
130 pass
127 pass
131
128
132
129
133 lines = self.extract_input_slices(args, True)
130 lines = self.extract_input_slices(args, True)
134 print "lines",lines
131 print "lines",lines
135 ip.runlines(lines)
132 ip.runlines(lines)
136
133
137 ip.expose_magic("rep",rep_f)
138
134
139 _sentinel = object()
135 _sentinel = object()
140
136
141 class ShadowHist:
137 class ShadowHist:
142 def __init__(self,db):
138 def __init__(self,db):
143 # cmd => idx mapping
139 # cmd => idx mapping
144 self.curidx = 0
140 self.curidx = 0
145 self.db = db
141 self.db = db
146
142
147 def inc_idx(self):
143 def inc_idx(self):
148 idx = self.db.hget('shadowhist', '__histidx', 0)
144 idx = self.db.hget('shadowhist', '__histidx', 0)
149 self.db.hset('shadowhist', '__histidx', idx + 1)
145 self.db.hset('shadowhist', '__histidx', idx + 1)
150 return idx
146 return idx
151
147
152 def add(self, ent):
148 def add(self, ent):
153 old = self.db.hget('shadowhist', ent, _sentinel)
149 old = self.db.hget('shadowhist', ent, _sentinel)
154 if old is not _sentinel:
150 if old is not _sentinel:
155 return
151 return
156 newidx = self.inc_idx()
152 newidx = self.inc_idx()
157 print "new",newidx
153 print "new",newidx
158 self.db.hset('shadowhist',ent, newidx)
154 self.db.hset('shadowhist',ent, newidx)
159
155
160 def all(self):
156 def all(self):
161 d = self.db.hdict('shadowhist')
157 d = self.db.hdict('shadowhist')
162 items = [(i,s) for (s,i) in d.items()]
158 items = [(i,s) for (s,i) in d.items()]
163 items.sort()
159 items.sort()
164 return items
160 return items
165
161
166 def test_shist():
162 def test_shist():
167 s = ShadowHist(ip.db)
163 s = ShadowHist(ip.db)
168 s.add('hello')
164 s.add('hello')
169 s.add('world')
165 s.add('world')
170 print "all",s.all()
166 print "all",s.all()
167
168 def init_ipython(ip):
169 ip.expose_magic("rep",rep_f)
170 ip.expose_magic("hist",magic_hist)
171 ip.expose_magic("history",magic_history)
171
172
172 # test_shist()
173 # test_shist()
@@ -1,442 +1,450 b''
1 ''' IPython customization API
1 ''' IPython customization API
2
2
3 Your one-stop module for configuring & extending ipython
3 Your one-stop module for configuring & extending ipython
4
4
5 The API will probably break when ipython 1.0 is released, but so
5 The API will probably break when ipython 1.0 is released, but so
6 will the other configuration method (rc files).
6 will the other configuration method (rc files).
7
7
8 All names prefixed by underscores are for internal use, not part
8 All names prefixed by underscores are for internal use, not part
9 of the public api.
9 of the public api.
10
10
11 Below is an example that you can just put to a module and import from ipython.
11 Below is an example that you can just put to a module and import from ipython.
12
12
13 A good practice is to install the config script below as e.g.
13 A good practice is to install the config script below as e.g.
14
14
15 ~/.ipython/my_private_conf.py
15 ~/.ipython/my_private_conf.py
16
16
17 And do
17 And do
18
18
19 import_mod my_private_conf
19 import_mod my_private_conf
20
20
21 in ~/.ipython/ipythonrc
21 in ~/.ipython/ipythonrc
22
22
23 That way the module is imported at startup and you can have all your
23 That way the module is imported at startup and you can have all your
24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
25 stuff) in there.
25 stuff) in there.
26
26
27 -----------------------------------------------
27 -----------------------------------------------
28 import IPython.ipapi
28 import IPython.ipapi
29 ip = IPython.ipapi.get()
29 ip = IPython.ipapi.get()
30
30
31 def ankka_f(self, arg):
31 def ankka_f(self, arg):
32 print "Ankka",self,"says uppercase:",arg.upper()
32 print "Ankka",self,"says uppercase:",arg.upper()
33
33
34 ip.expose_magic("ankka",ankka_f)
34 ip.expose_magic("ankka",ankka_f)
35
35
36 ip.magic('alias sayhi echo "Testing, hi ok"')
36 ip.magic('alias sayhi echo "Testing, hi ok"')
37 ip.magic('alias helloworld echo "Hello world"')
37 ip.magic('alias helloworld echo "Hello world"')
38 ip.system('pwd')
38 ip.system('pwd')
39
39
40 ip.ex('import re')
40 ip.ex('import re')
41 ip.ex("""
41 ip.ex("""
42 def funcci(a,b):
42 def funcci(a,b):
43 print a+b
43 print a+b
44 print funcci(3,4)
44 print funcci(3,4)
45 """)
45 """)
46 ip.ex("funcci(348,9)")
46 ip.ex("funcci(348,9)")
47
47
48 def jed_editor(self,filename, linenum=None):
48 def jed_editor(self,filename, linenum=None):
49 print "Calling my own editor, jed ... via hook!"
49 print "Calling my own editor, jed ... via hook!"
50 import os
50 import os
51 if linenum is None: linenum = 0
51 if linenum is None: linenum = 0
52 os.system('jed +%d %s' % (linenum, filename))
52 os.system('jed +%d %s' % (linenum, filename))
53 print "exiting jed"
53 print "exiting jed"
54
54
55 ip.set_hook('editor',jed_editor)
55 ip.set_hook('editor',jed_editor)
56
56
57 o = ip.options
57 o = ip.options
58 o.autocall = 2 # FULL autocall mode
58 o.autocall = 2 # FULL autocall mode
59
59
60 print "done!"
60 print "done!"
61 '''
61 '''
62
62
63 # stdlib imports
63 # stdlib imports
64 import __builtin__
64 import __builtin__
65 import sys
65 import sys
66
66
67 # our own
67 # our own
68 #from IPython.genutils import warn,error
68 #from IPython.genutils import warn,error
69
69
70 class TryNext(Exception):
70 class TryNext(Exception):
71 """Try next hook exception.
71 """Try next hook exception.
72
72
73 Raise this in your hook function to indicate that the next hook handler
73 Raise this in your hook function to indicate that the next hook handler
74 should be used to handle the operation. If you pass arguments to the
74 should be used to handle the operation. If you pass arguments to the
75 constructor those arguments will be used by the next hook instead of the
75 constructor those arguments will be used by the next hook instead of the
76 original ones.
76 original ones.
77 """
77 """
78
78
79 def __init__(self, *args, **kwargs):
79 def __init__(self, *args, **kwargs):
80 self.args = args
80 self.args = args
81 self.kwargs = kwargs
81 self.kwargs = kwargs
82
82
83 class IPyAutocall:
83 class IPyAutocall:
84 """ Instances of this class are always autocalled
84 """ Instances of this class are always autocalled
85
85
86 This happens regardless of 'autocall' variable state. Use this to
86 This happens regardless of 'autocall' variable state. Use this to
87 develop macro-like mechanisms.
87 develop macro-like mechanisms.
88 """
88 """
89
89
90 def set_ip(self,ip):
90 def set_ip(self,ip):
91 """ Will be used to set _ip point to current ipython instance b/f call
91 """ Will be used to set _ip point to current ipython instance b/f call
92
92
93 Override this method if you don't want this to happen.
93 Override this method if you don't want this to happen.
94
94
95 """
95 """
96 self._ip = ip
96 self._ip = ip
97
97
98
98
99 # contains the most recently instantiated IPApi
99 # contains the most recently instantiated IPApi
100
100
101 class IPythonNotRunning:
101 class IPythonNotRunning:
102 """Dummy do-nothing class.
102 """Dummy do-nothing class.
103
103
104 Instances of this class return a dummy attribute on all accesses, which
104 Instances of this class return a dummy attribute on all accesses, which
105 can be called and warns. This makes it easier to write scripts which use
105 can be called and warns. This makes it easier to write scripts which use
106 the ipapi.get() object for informational purposes to operate both with and
106 the ipapi.get() object for informational purposes to operate both with and
107 without ipython. Obviously code which uses the ipython object for
107 without ipython. Obviously code which uses the ipython object for
108 computations will not work, but this allows a wider range of code to
108 computations will not work, but this allows a wider range of code to
109 transparently work whether ipython is being used or not."""
109 transparently work whether ipython is being used or not."""
110
110
111 def __init__(self,warn=True):
111 def __init__(self,warn=True):
112 if warn:
112 if warn:
113 self.dummy = self._dummy_warn
113 self.dummy = self._dummy_warn
114 else:
114 else:
115 self.dummy = self._dummy_silent
115 self.dummy = self._dummy_silent
116
116
117 def __str__(self):
117 def __str__(self):
118 return "<IPythonNotRunning>"
118 return "<IPythonNotRunning>"
119
119
120 __repr__ = __str__
120 __repr__ = __str__
121
121
122 def __getattr__(self,name):
122 def __getattr__(self,name):
123 return self.dummy
123 return self.dummy
124
124
125 def _dummy_warn(self,*args,**kw):
125 def _dummy_warn(self,*args,**kw):
126 """Dummy function, which doesn't do anything but warn."""
126 """Dummy function, which doesn't do anything but warn."""
127
127
128 print ("IPython is not running, this is a dummy no-op function")
128 print ("IPython is not running, this is a dummy no-op function")
129
129
130 def _dummy_silent(self,*args,**kw):
130 def _dummy_silent(self,*args,**kw):
131 """Dummy function, which doesn't do anything and emits no warnings."""
131 """Dummy function, which doesn't do anything and emits no warnings."""
132 pass
132 pass
133
133
134 _recent = None
134 _recent = None
135
135
136
136
137 def get(allow_dummy=False,dummy_warn=True):
137 def get(allow_dummy=False,dummy_warn=True):
138 """Get an IPApi object.
138 """Get an IPApi object.
139
139
140 If allow_dummy is true, returns an instance of IPythonNotRunning
140 If allow_dummy is true, returns an instance of IPythonNotRunning
141 instead of None if not running under IPython.
141 instead of None if not running under IPython.
142
142
143 If dummy_warn is false, the dummy instance will be completely silent.
143 If dummy_warn is false, the dummy instance will be completely silent.
144
144
145 Running this should be the first thing you do when writing extensions that
145 Running this should be the first thing you do when writing extensions that
146 can be imported as normal modules. You can then direct all the
146 can be imported as normal modules. You can then direct all the
147 configuration operations against the returned object.
147 configuration operations against the returned object.
148 """
148 """
149 global _recent
149 global _recent
150 if allow_dummy and not _recent:
150 if allow_dummy and not _recent:
151 _recent = IPythonNotRunning(dummy_warn)
151 _recent = IPythonNotRunning(dummy_warn)
152 return _recent
152 return _recent
153
153
154 class IPApi:
154 class IPApi:
155 """ The actual API class for configuring IPython
155 """ The actual API class for configuring IPython
156
156
157 You should do all of the IPython configuration by getting an IPApi object
157 You should do all of the IPython configuration by getting an IPApi object
158 with IPython.ipapi.get() and using the attributes and methods of the
158 with IPython.ipapi.get() and using the attributes and methods of the
159 returned object."""
159 returned object."""
160
160
161 def __init__(self,ip):
161 def __init__(self,ip):
162
162
163 # All attributes exposed here are considered to be the public API of
163 # All attributes exposed here are considered to be the public API of
164 # IPython. As needs dictate, some of these may be wrapped as
164 # IPython. As needs dictate, some of these may be wrapped as
165 # properties.
165 # properties.
166
166
167 self.magic = ip.ipmagic
167 self.magic = ip.ipmagic
168
168
169 self.system = ip.system
169 self.system = ip.system
170
170
171 self.set_hook = ip.set_hook
171 self.set_hook = ip.set_hook
172
172
173 self.set_custom_exc = ip.set_custom_exc
173 self.set_custom_exc = ip.set_custom_exc
174
174
175 self.user_ns = ip.user_ns
175 self.user_ns = ip.user_ns
176
176
177 self.set_crash_handler = ip.set_crash_handler
177 self.set_crash_handler = ip.set_crash_handler
178
178
179 # Session-specific data store, which can be used to store
179 # Session-specific data store, which can be used to store
180 # data that should persist through the ipython session.
180 # data that should persist through the ipython session.
181 self.meta = ip.meta
181 self.meta = ip.meta
182
182
183 # The ipython instance provided
183 # The ipython instance provided
184 self.IP = ip
184 self.IP = ip
185
185
186 global _recent
186 global _recent
187 _recent = self
187 _recent = self
188
188
189 # Use a property for some things which are added to the instance very
189 # Use a property for some things which are added to the instance very
190 # late. I don't have time right now to disentangle the initialization
190 # late. I don't have time right now to disentangle the initialization
191 # order issues, so a property lets us delay item extraction while
191 # order issues, so a property lets us delay item extraction while
192 # providing a normal attribute API.
192 # providing a normal attribute API.
193 def get_db(self):
193 def get_db(self):
194 """A handle to persistent dict-like database (a PickleShareDB object)"""
194 """A handle to persistent dict-like database (a PickleShareDB object)"""
195 return self.IP.db
195 return self.IP.db
196
196
197 db = property(get_db,None,None,get_db.__doc__)
197 db = property(get_db,None,None,get_db.__doc__)
198
198
199 def get_options(self):
199 def get_options(self):
200 """All configurable variables."""
200 """All configurable variables."""
201
201
202 # catch typos by disabling new attribute creation. If new attr creation
202 # catch typos by disabling new attribute creation. If new attr creation
203 # is in fact wanted (e.g. when exposing new options), do allow_new_attr(True)
203 # is in fact wanted (e.g. when exposing new options), do allow_new_attr(True)
204 # for the received rc struct.
204 # for the received rc struct.
205
205
206 self.IP.rc.allow_new_attr(False)
206 self.IP.rc.allow_new_attr(False)
207 return self.IP.rc
207 return self.IP.rc
208
208
209 options = property(get_options,None,None,get_options.__doc__)
209 options = property(get_options,None,None,get_options.__doc__)
210
210
211 def expose_magic(self,magicname, func):
211 def expose_magic(self,magicname, func):
212 ''' Expose own function as magic function for ipython
212 ''' Expose own function as magic function for ipython
213
213
214 def foo_impl(self,parameter_s=''):
214 def foo_impl(self,parameter_s=''):
215 """My very own magic!. (Use docstrings, IPython reads them)."""
215 """My very own magic!. (Use docstrings, IPython reads them)."""
216 print 'Magic function. Passed parameter is between < >: <'+parameter_s+'>'
216 print 'Magic function. Passed parameter is between < >: <'+parameter_s+'>'
217 print 'The self object is:',self
217 print 'The self object is:',self
218
218
219 ipapi.expose_magic("foo",foo_impl)
219 ipapi.expose_magic("foo",foo_impl)
220 '''
220 '''
221
221
222 import new
222 import new
223 im = new.instancemethod(func,self.IP, self.IP.__class__)
223 im = new.instancemethod(func,self.IP, self.IP.__class__)
224 setattr(self.IP, "magic_" + magicname, im)
224 setattr(self.IP, "magic_" + magicname, im)
225
225
226 def ex(self,cmd):
226 def ex(self,cmd):
227 """ Execute a normal python statement in user namespace """
227 """ Execute a normal python statement in user namespace """
228 exec cmd in self.user_ns
228 exec cmd in self.user_ns
229
229
230 def ev(self,expr):
230 def ev(self,expr):
231 """ Evaluate python expression expr in user namespace
231 """ Evaluate python expression expr in user namespace
232
232
233 Returns the result of evaluation"""
233 Returns the result of evaluation"""
234 return eval(expr,self.user_ns)
234 return eval(expr,self.user_ns)
235
235
236 def runlines(self,lines):
236 def runlines(self,lines):
237 """ Run the specified lines in interpreter, honoring ipython directives.
237 """ Run the specified lines in interpreter, honoring ipython directives.
238
238
239 This allows %magic and !shell escape notations.
239 This allows %magic and !shell escape notations.
240
240
241 Takes either all lines in one string or list of lines.
241 Takes either all lines in one string or list of lines.
242 """
242 """
243 if isinstance(lines,basestring):
243 if isinstance(lines,basestring):
244 self.IP.runlines(lines)
244 self.IP.runlines(lines)
245 else:
245 else:
246 self.IP.runlines('\n'.join(lines))
246 self.IP.runlines('\n'.join(lines))
247
247
248 def to_user_ns(self,vars, interactive = True):
248 def to_user_ns(self,vars, interactive = True):
249 """Inject a group of variables into the IPython user namespace.
249 """Inject a group of variables into the IPython user namespace.
250
250
251 Inputs:
251 Inputs:
252
252
253 - vars: string with variable names separated by whitespace
253 - vars: string with variable names separated by whitespace
254
254
255 - interactive: if True (default), the var will be listed with
255 - interactive: if True (default), the var will be listed with
256 %whos et. al.
256 %whos et. al.
257
257
258 This utility routine is meant to ease interactive debugging work,
258 This utility routine is meant to ease interactive debugging work,
259 where you want to easily propagate some internal variable in your code
259 where you want to easily propagate some internal variable in your code
260 up to the interactive namespace for further exploration.
260 up to the interactive namespace for further exploration.
261
261
262 When you run code via %run, globals in your script become visible at
262 When you run code via %run, globals in your script become visible at
263 the interactive prompt, but this doesn't happen for locals inside your
263 the interactive prompt, but this doesn't happen for locals inside your
264 own functions and methods. Yet when debugging, it is common to want
264 own functions and methods. Yet when debugging, it is common to want
265 to explore some internal variables further at the interactive propmt.
265 to explore some internal variables further at the interactive propmt.
266
266
267 Examples:
267 Examples:
268
268
269 To use this, you first must obtain a handle on the ipython object as
269 To use this, you first must obtain a handle on the ipython object as
270 indicated above, via:
270 indicated above, via:
271
271
272 import IPython.ipapi
272 import IPython.ipapi
273 ip = IPython.ipapi.get()
273 ip = IPython.ipapi.get()
274
274
275 Once this is done, inside a routine foo() where you want to expose
275 Once this is done, inside a routine foo() where you want to expose
276 variables x and y, you do the following:
276 variables x and y, you do the following:
277
277
278 def foo():
278 def foo():
279 ...
279 ...
280 x = your_computation()
280 x = your_computation()
281 y = something_else()
281 y = something_else()
282
282
283 # This pushes x and y to the interactive prompt immediately, even
283 # This pushes x and y to the interactive prompt immediately, even
284 # if this routine crashes on the next line after:
284 # if this routine crashes on the next line after:
285 ip.to_user_ns('x y')
285 ip.to_user_ns('x y')
286 ...
286 ...
287 # return
287 # return
288
288
289 If you need to rename variables, just use ip.user_ns with dict
289 If you need to rename variables, just use ip.user_ns with dict
290 and update:
290 and update:
291
291
292 # exposes variables 'foo' as 'x' and 'bar' as 'y' in IPython
292 # exposes variables 'foo' as 'x' and 'bar' as 'y' in IPython
293 # user namespace
293 # user namespace
294 ip.user_ns.update(dict(x=foo,y=bar))
294 ip.user_ns.update(dict(x=foo,y=bar))
295 """
295 """
296
296
297 # print 'vars given:',vars # dbg
297 # print 'vars given:',vars # dbg
298 # Get the caller's frame to evaluate the given names in
298 # Get the caller's frame to evaluate the given names in
299 cf = sys._getframe(1)
299 cf = sys._getframe(1)
300
300
301 user_ns = self.user_ns
301 user_ns = self.user_ns
302 config_ns = self.IP.user_config_ns
302 config_ns = self.IP.user_config_ns
303 for name in vars.split():
303 for name in vars.split():
304 try:
304 try:
305 val = eval(name,cf.f_globals,cf.f_locals)
305 val = eval(name,cf.f_globals,cf.f_locals)
306 user_ns[name] = val
306 user_ns[name] = val
307 if not interactive:
307 if not interactive:
308 config_ns[name] = val
308 config_ns[name] = val
309 else:
309 else:
310 config_ns.pop(name,None)
310 config_ns.pop(name,None)
311 except:
311 except:
312 print ('could not get var. %s from %s' %
312 print ('could not get var. %s from %s' %
313 (name,cf.f_code.co_name))
313 (name,cf.f_code.co_name))
314
314
315 def expand_alias(self,line):
315 def expand_alias(self,line):
316 """ Expand an alias in the command line
316 """ Expand an alias in the command line
317
317
318 Returns the provided command line, possibly with the first word
318 Returns the provided command line, possibly with the first word
319 (command) translated according to alias expansion rules.
319 (command) translated according to alias expansion rules.
320
320
321 [ipython]|16> _ip.expand_aliases("np myfile.txt")
321 [ipython]|16> _ip.expand_aliases("np myfile.txt")
322 <16> 'q:/opt/np/notepad++.exe myfile.txt'
322 <16> 'q:/opt/np/notepad++.exe myfile.txt'
323 """
323 """
324
324
325 pre,fn,rest = self.IP.split_user_input(line)
325 pre,fn,rest = self.IP.split_user_input(line)
326 res = pre + self.IP.expand_aliases(fn,rest)
326 res = pre + self.IP.expand_aliases(fn,rest)
327 return res
327 return res
328
328
329 def defalias(self, name, cmd):
329 def defalias(self, name, cmd):
330 """ Define a new alias
330 """ Define a new alias
331
331
332 _ip.defalias('bb','bldmake bldfiles')
332 _ip.defalias('bb','bldmake bldfiles')
333
333
334 Creates a new alias named 'bb' in ipython user namespace
334 Creates a new alias named 'bb' in ipython user namespace
335 """
335 """
336
336
337
337
338 nargs = cmd.count('%s')
338 nargs = cmd.count('%s')
339 if nargs>0 and cmd.find('%l')>=0:
339 if nargs>0 and cmd.find('%l')>=0:
340 raise Exception('The %s and %l specifiers are mutually exclusive '
340 raise Exception('The %s and %l specifiers are mutually exclusive '
341 'in alias definitions.')
341 'in alias definitions.')
342
342
343 else: # all looks OK
343 else: # all looks OK
344 self.IP.alias_table[name] = (nargs,cmd)
344 self.IP.alias_table[name] = (nargs,cmd)
345
345
346 def defmacro(self, *args):
346 def defmacro(self, *args):
347 """ Define a new macro
347 """ Define a new macro
348
348
349 2 forms of calling:
349 2 forms of calling:
350
350
351 mac = _ip.defmacro('print "hello"\nprint "world"')
351 mac = _ip.defmacro('print "hello"\nprint "world"')
352
352
353 (doesn't put the created macro on user namespace)
353 (doesn't put the created macro on user namespace)
354
354
355 _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb')
355 _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb')
356
356
357 (creates a macro named 'build' in user namespace)
357 (creates a macro named 'build' in user namespace)
358 """
358 """
359
359
360 import IPython.macro
360 import IPython.macro
361
361
362 if len(args) == 1:
362 if len(args) == 1:
363 return IPython.macro.Macro(args[0])
363 return IPython.macro.Macro(args[0])
364 elif len(args) == 2:
364 elif len(args) == 2:
365 self.user_ns[args[0]] = IPython.macro.Macro(args[1])
365 self.user_ns[args[0]] = IPython.macro.Macro(args[1])
366 else:
366 else:
367 return Exception("_ip.defmacro must be called with 1 or 2 arguments")
367 return Exception("_ip.defmacro must be called with 1 or 2 arguments")
368
368
369 def set_next_input(self, s):
369 def set_next_input(self, s):
370 """ Sets the 'default' input string for the next command line.
370 """ Sets the 'default' input string for the next command line.
371
371
372 Requires readline.
372 Requires readline.
373
373
374 Example:
374 Example:
375
375
376 [D:\ipython]|1> _ip.set_next_input("Hello Word")
376 [D:\ipython]|1> _ip.set_next_input("Hello Word")
377 [D:\ipython]|2> Hello Word_ # cursor is here
377 [D:\ipython]|2> Hello Word_ # cursor is here
378 """
378 """
379
379
380 self.IP.rl_next_input = s
380 self.IP.rl_next_input = s
381
382 def load(self, mod):
383 if mod in sys.modules:
384 return
385 __import__(mod)
386 m = sys.modules[mod]
387 if hasattr(m,'init_ipython'):
388 m.init_ipython(self)
381
389
382
390
383 def launch_new_instance(user_ns = None):
391 def launch_new_instance(user_ns = None):
384 """ Make and start a new ipython instance.
392 """ Make and start a new ipython instance.
385
393
386 This can be called even without having an already initialized
394 This can be called even without having an already initialized
387 ipython session running.
395 ipython session running.
388
396
389 This is also used as the egg entry point for the 'ipython' script.
397 This is also used as the egg entry point for the 'ipython' script.
390
398
391 """
399 """
392 ses = make_session(user_ns)
400 ses = make_session(user_ns)
393 ses.mainloop()
401 ses.mainloop()
394
402
395
403
396 def make_user_ns(user_ns = None):
404 def make_user_ns(user_ns = None):
397 """Return a valid user interactive namespace.
405 """Return a valid user interactive namespace.
398
406
399 This builds a dict with the minimal information needed to operate as a
407 This builds a dict with the minimal information needed to operate as a
400 valid IPython user namespace, which you can pass to the various embedding
408 valid IPython user namespace, which you can pass to the various embedding
401 classes in ipython.
409 classes in ipython.
402 """
410 """
403
411
404 if user_ns is None:
412 if user_ns is None:
405 # Set __name__ to __main__ to better match the behavior of the
413 # Set __name__ to __main__ to better match the behavior of the
406 # normal interpreter.
414 # normal interpreter.
407 user_ns = {'__name__' :'__main__',
415 user_ns = {'__name__' :'__main__',
408 '__builtins__' : __builtin__,
416 '__builtins__' : __builtin__,
409 }
417 }
410 else:
418 else:
411 user_ns.setdefault('__name__','__main__')
419 user_ns.setdefault('__name__','__main__')
412 user_ns.setdefault('__builtins__',__builtin__)
420 user_ns.setdefault('__builtins__',__builtin__)
413
421
414 return user_ns
422 return user_ns
415
423
416
424
417 def make_user_global_ns(ns = None):
425 def make_user_global_ns(ns = None):
418 """Return a valid user global namespace.
426 """Return a valid user global namespace.
419
427
420 Similar to make_user_ns(), but global namespaces are really only needed in
428 Similar to make_user_ns(), but global namespaces are really only needed in
421 embedded applications, where there is a distinction between the user's
429 embedded applications, where there is a distinction between the user's
422 interactive namespace and the global one where ipython is running."""
430 interactive namespace and the global one where ipython is running."""
423
431
424 if ns is None: ns = {}
432 if ns is None: ns = {}
425 return ns
433 return ns
426
434
427
435
428 def make_session(user_ns = None):
436 def make_session(user_ns = None):
429 """Makes, but does not launch an IPython session.
437 """Makes, but does not launch an IPython session.
430
438
431 Later on you can call obj.mainloop() on the returned object.
439 Later on you can call obj.mainloop() on the returned object.
432
440
433 Inputs:
441 Inputs:
434
442
435 - user_ns(None): a dict to be used as the user's namespace with initial
443 - user_ns(None): a dict to be used as the user's namespace with initial
436 data.
444 data.
437
445
438 WARNING: This should *not* be run when a session exists already."""
446 WARNING: This should *not* be run when a session exists already."""
439
447
440 import IPython
448 import IPython
441 return IPython.Shell.start(user_ns)
449 return IPython.Shell.start(user_ns)
442
450
General Comments 0
You need to be logged in to leave comments. Login now