Show More
@@ -1,596 +1,596 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 | try: # Python 2.3 compatibility |
|
67 | try: # Python 2.3 compatibility | |
68 | set |
|
68 | set | |
69 | except NameError: |
|
69 | except NameError: | |
70 | import sets |
|
70 | import sets | |
71 | set = sets.Set |
|
71 | set = sets.Set | |
72 |
|
72 | |||
73 | # our own |
|
73 | # our own | |
74 | #from IPython.genutils import warn,error |
|
74 | #from IPython.genutils import warn,error | |
75 |
|
75 | |||
76 | class TryNext(Exception): |
|
76 | class TryNext(Exception): | |
77 | """Try next hook exception. |
|
77 | """Try next hook exception. | |
78 |
|
78 | |||
79 | Raise this in your hook function to indicate that the next hook handler |
|
79 | Raise this in your hook function to indicate that the next hook handler | |
80 | should be used to handle the operation. If you pass arguments to the |
|
80 | should be used to handle the operation. If you pass arguments to the | |
81 | constructor those arguments will be used by the next hook instead of the |
|
81 | constructor those arguments will be used by the next hook instead of the | |
82 | original ones. |
|
82 | original ones. | |
83 | """ |
|
83 | """ | |
84 |
|
84 | |||
85 | def __init__(self, *args, **kwargs): |
|
85 | def __init__(self, *args, **kwargs): | |
86 | self.args = args |
|
86 | self.args = args | |
87 | self.kwargs = kwargs |
|
87 | self.kwargs = kwargs | |
88 |
|
88 | |||
89 | class UsageError(Exception): |
|
89 | class UsageError(Exception): | |
90 | """ Error in magic function arguments, etc. |
|
90 | """ Error in magic function arguments, etc. | |
91 |
|
91 | |||
92 | Something that probably won't warrant a full traceback, but should |
|
92 | Something that probably won't warrant a full traceback, but should | |
93 | nevertheless interrupt a macro / batch file. |
|
93 | nevertheless interrupt a macro / batch file. | |
94 | """ |
|
94 | """ | |
95 |
|
95 | |||
96 | class IPyAutocall: |
|
96 | class IPyAutocall: | |
97 | """ Instances of this class are always autocalled |
|
97 | """ Instances of this class are always autocalled | |
98 |
|
98 | |||
99 | This happens regardless of 'autocall' variable state. Use this to |
|
99 | This happens regardless of 'autocall' variable state. Use this to | |
100 | develop macro-like mechanisms. |
|
100 | develop macro-like mechanisms. | |
101 | """ |
|
101 | """ | |
102 |
|
102 | |||
103 | def set_ip(self,ip): |
|
103 | def set_ip(self,ip): | |
104 | """ Will be used to set _ip point to current ipython instance b/f call |
|
104 | """ Will be used to set _ip point to current ipython instance b/f call | |
105 |
|
105 | |||
106 | Override this method if you don't want this to happen. |
|
106 | Override this method if you don't want this to happen. | |
107 |
|
107 | |||
108 | """ |
|
108 | """ | |
109 | self._ip = ip |
|
109 | self._ip = ip | |
110 |
|
110 | |||
111 |
|
111 | |||
112 | # contains the most recently instantiated IPApi |
|
112 | # contains the most recently instantiated IPApi | |
113 |
|
113 | |||
114 | class IPythonNotRunning: |
|
114 | class IPythonNotRunning: | |
115 | """Dummy do-nothing class. |
|
115 | """Dummy do-nothing class. | |
116 |
|
116 | |||
117 | Instances of this class return a dummy attribute on all accesses, which |
|
117 | Instances of this class return a dummy attribute on all accesses, which | |
118 | can be called and warns. This makes it easier to write scripts which use |
|
118 | can be called and warns. This makes it easier to write scripts which use | |
119 | the ipapi.get() object for informational purposes to operate both with and |
|
119 | the ipapi.get() object for informational purposes to operate both with and | |
120 | without ipython. Obviously code which uses the ipython object for |
|
120 | without ipython. Obviously code which uses the ipython object for | |
121 | computations will not work, but this allows a wider range of code to |
|
121 | computations will not work, but this allows a wider range of code to | |
122 | transparently work whether ipython is being used or not.""" |
|
122 | transparently work whether ipython is being used or not.""" | |
123 |
|
123 | |||
124 | def __init__(self,warn=True): |
|
124 | def __init__(self,warn=True): | |
125 | if warn: |
|
125 | if warn: | |
126 | self.dummy = self._dummy_warn |
|
126 | self.dummy = self._dummy_warn | |
127 | else: |
|
127 | else: | |
128 | self.dummy = self._dummy_silent |
|
128 | self.dummy = self._dummy_silent | |
129 |
|
129 | |||
130 | def __str__(self): |
|
130 | def __str__(self): | |
131 | return "<IPythonNotRunning>" |
|
131 | return "<IPythonNotRunning>" | |
132 |
|
132 | |||
133 | __repr__ = __str__ |
|
133 | __repr__ = __str__ | |
134 |
|
134 | |||
135 | def __getattr__(self,name): |
|
135 | def __getattr__(self,name): | |
136 | return self.dummy |
|
136 | return self.dummy | |
137 |
|
137 | |||
138 | def _dummy_warn(self,*args,**kw): |
|
138 | def _dummy_warn(self,*args,**kw): | |
139 | """Dummy function, which doesn't do anything but warn.""" |
|
139 | """Dummy function, which doesn't do anything but warn.""" | |
140 |
|
140 | |||
141 | print ("IPython is not running, this is a dummy no-op function") |
|
141 | print ("IPython is not running, this is a dummy no-op function") | |
142 |
|
142 | |||
143 | def _dummy_silent(self,*args,**kw): |
|
143 | def _dummy_silent(self,*args,**kw): | |
144 | """Dummy function, which doesn't do anything and emits no warnings.""" |
|
144 | """Dummy function, which doesn't do anything and emits no warnings.""" | |
145 | pass |
|
145 | pass | |
146 |
|
146 | |||
147 | _recent = None |
|
147 | _recent = None | |
148 |
|
148 | |||
149 |
|
149 | |||
150 | def get(allow_dummy=False,dummy_warn=True): |
|
150 | def get(allow_dummy=False,dummy_warn=True): | |
151 | """Get an IPApi object. |
|
151 | """Get an IPApi object. | |
152 |
|
152 | |||
153 | If allow_dummy is true, returns an instance of IPythonNotRunning |
|
153 | If allow_dummy is true, returns an instance of IPythonNotRunning | |
154 | instead of None if not running under IPython. |
|
154 | instead of None if not running under IPython. | |
155 |
|
155 | |||
156 | If dummy_warn is false, the dummy instance will be completely silent. |
|
156 | If dummy_warn is false, the dummy instance will be completely silent. | |
157 |
|
157 | |||
158 | Running this should be the first thing you do when writing extensions that |
|
158 | Running this should be the first thing you do when writing extensions that | |
159 | can be imported as normal modules. You can then direct all the |
|
159 | can be imported as normal modules. You can then direct all the | |
160 | configuration operations against the returned object. |
|
160 | configuration operations against the returned object. | |
161 | """ |
|
161 | """ | |
162 | global _recent |
|
162 | global _recent | |
163 | if allow_dummy and not _recent: |
|
163 | if allow_dummy and not _recent: | |
164 | _recent = IPythonNotRunning(dummy_warn) |
|
164 | _recent = IPythonNotRunning(dummy_warn) | |
165 | return _recent |
|
165 | return _recent | |
166 |
|
166 | |||
167 | class IPApi: |
|
167 | class IPApi: | |
168 | """ The actual API class for configuring IPython |
|
168 | """ The actual API class for configuring IPython | |
169 |
|
169 | |||
170 | You should do all of the IPython configuration by getting an IPApi object |
|
170 | You should do all of the IPython configuration by getting an IPApi object | |
171 | with IPython.ipapi.get() and using the attributes and methods of the |
|
171 | with IPython.ipapi.get() and using the attributes and methods of the | |
172 | returned object.""" |
|
172 | returned object.""" | |
173 |
|
173 | |||
174 | def __init__(self,ip): |
|
174 | def __init__(self,ip): | |
175 |
|
175 | |||
176 | # All attributes exposed here are considered to be the public API of |
|
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 |
|
177 | # IPython. As needs dictate, some of these may be wrapped as | |
178 | # properties. |
|
178 | # properties. | |
179 |
|
179 | |||
180 | self.magic = ip.ipmagic |
|
180 | self.magic = ip.ipmagic | |
181 |
|
181 | |||
182 | self.system = ip.system |
|
182 | self.system = ip.system | |
183 |
|
183 | |||
184 | self.set_hook = ip.set_hook |
|
184 | self.set_hook = ip.set_hook | |
185 |
|
185 | |||
186 | self.set_custom_exc = ip.set_custom_exc |
|
186 | self.set_custom_exc = ip.set_custom_exc | |
187 |
|
187 | |||
188 | self.user_ns = ip.user_ns |
|
188 | self.user_ns = ip.user_ns | |
189 | self.user_ns['_ip'] = self |
|
189 | self.user_ns['_ip'] = self | |
190 |
|
190 | |||
191 | self.set_crash_handler = ip.set_crash_handler |
|
191 | self.set_crash_handler = ip.set_crash_handler | |
192 |
|
192 | |||
193 | # Session-specific data store, which can be used to store |
|
193 | # Session-specific data store, which can be used to store | |
194 | # data that should persist through the ipython session. |
|
194 | # data that should persist through the ipython session. | |
195 | self.meta = ip.meta |
|
195 | self.meta = ip.meta | |
196 |
|
196 | |||
197 | # The ipython instance provided |
|
197 | # The ipython instance provided | |
198 | self.IP = ip |
|
198 | self.IP = ip | |
199 |
|
199 | |||
200 | self.extensions = {} |
|
200 | self.extensions = {} | |
201 |
|
201 | |||
202 | self.dbg = DebugTools(self) |
|
202 | self.dbg = DebugTools(self) | |
203 |
|
203 | |||
204 | global _recent |
|
204 | global _recent | |
205 | _recent = self |
|
205 | _recent = self | |
206 |
|
206 | |||
207 | # Use a property for some things which are added to the instance very |
|
207 | # Use a property for some things which are added to the instance very | |
208 | # late. I don't have time right now to disentangle the initialization |
|
208 | # late. I don't have time right now to disentangle the initialization | |
209 | # order issues, so a property lets us delay item extraction while |
|
209 | # order issues, so a property lets us delay item extraction while | |
210 | # providing a normal attribute API. |
|
210 | # providing a normal attribute API. | |
211 | def get_db(self): |
|
211 | def get_db(self): | |
212 | """A handle to persistent dict-like database (a PickleShareDB object)""" |
|
212 | """A handle to persistent dict-like database (a PickleShareDB object)""" | |
213 | return self.IP.db |
|
213 | return self.IP.db | |
214 |
|
214 | |||
215 | db = property(get_db,None,None,get_db.__doc__) |
|
215 | db = property(get_db,None,None,get_db.__doc__) | |
216 |
|
216 | |||
217 | def get_options(self): |
|
217 | def get_options(self): | |
218 | """All configurable variables.""" |
|
218 | """All configurable variables.""" | |
219 |
|
219 | |||
220 | # catch typos by disabling new attribute creation. If new attr creation |
|
220 | # catch typos by disabling new attribute creation. If new attr creation | |
221 | # is in fact wanted (e.g. when exposing new options), do allow_new_attr(True) |
|
221 | # is in fact wanted (e.g. when exposing new options), do allow_new_attr(True) | |
222 | # for the received rc struct. |
|
222 | # for the received rc struct. | |
223 |
|
223 | |||
224 | self.IP.rc.allow_new_attr(False) |
|
224 | self.IP.rc.allow_new_attr(False) | |
225 | return self.IP.rc |
|
225 | return self.IP.rc | |
226 |
|
226 | |||
227 | options = property(get_options,None,None,get_options.__doc__) |
|
227 | options = property(get_options,None,None,get_options.__doc__) | |
228 |
|
228 | |||
229 | def expose_magic(self,magicname, func): |
|
229 | def expose_magic(self,magicname, func): | |
230 | ''' Expose own function as magic function for ipython |
|
230 | ''' Expose own function as magic function for ipython | |
231 |
|
231 | |||
232 | def foo_impl(self,parameter_s=''): |
|
232 | def foo_impl(self,parameter_s=''): | |
233 | """My very own magic!. (Use docstrings, IPython reads them).""" |
|
233 | """My very own magic!. (Use docstrings, IPython reads them).""" | |
234 | print 'Magic function. Passed parameter is between < >: <'+parameter_s+'>' |
|
234 | print 'Magic function. Passed parameter is between < >: <'+parameter_s+'>' | |
235 | print 'The self object is:',self |
|
235 | print 'The self object is:',self | |
236 |
|
236 | |||
237 | ipapi.expose_magic("foo",foo_impl) |
|
237 | ipapi.expose_magic("foo",foo_impl) | |
238 | ''' |
|
238 | ''' | |
239 |
|
239 | |||
240 | import new |
|
240 | import new | |
241 | im = new.instancemethod(func,self.IP, self.IP.__class__) |
|
241 | im = new.instancemethod(func,self.IP, self.IP.__class__) | |
242 | old = getattr(self.IP, "magic_" + magicname, None) |
|
242 | old = getattr(self.IP, "magic_" + magicname, None) | |
243 | if old: |
|
243 | if old: | |
244 | self.dbg.debug_stack("Magic redefinition '%s', old %s" % (magicname, |
|
244 | self.dbg.debug_stack("Magic redefinition '%s', old %s" % (magicname, | |
245 | old)) |
|
245 | old)) | |
246 |
|
246 | |||
247 | setattr(self.IP, "magic_" + magicname, im) |
|
247 | setattr(self.IP, "magic_" + magicname, im) | |
248 |
|
248 | |||
249 | def ex(self,cmd): |
|
249 | def ex(self,cmd): | |
250 | """ Execute a normal python statement in user namespace """ |
|
250 | """ Execute a normal python statement in user namespace """ | |
251 | exec cmd in self.user_ns |
|
251 | exec cmd in self.user_ns | |
252 |
|
252 | |||
253 | def ev(self,expr): |
|
253 | def ev(self,expr): | |
254 | """ Evaluate python expression expr in user namespace |
|
254 | """ Evaluate python expression expr in user namespace | |
255 |
|
255 | |||
256 | Returns the result of evaluation""" |
|
256 | Returns the result of evaluation""" | |
257 | return eval(expr,self.user_ns) |
|
257 | return eval(expr,self.user_ns) | |
258 |
|
258 | |||
259 | def runlines(self,lines): |
|
259 | def runlines(self,lines): | |
260 | """ Run the specified lines in interpreter, honoring ipython directives. |
|
260 | """ Run the specified lines in interpreter, honoring ipython directives. | |
261 |
|
261 | |||
262 | This allows %magic and !shell escape notations. |
|
262 | This allows %magic and !shell escape notations. | |
263 |
|
263 | |||
264 | Takes either all lines in one string or list of lines. |
|
264 | Takes either all lines in one string or list of lines. | |
265 | """ |
|
265 | """ | |
266 |
|
266 | |||
267 | def cleanup_ipy_script(script): |
|
267 | def cleanup_ipy_script(script): | |
268 | """ Make a script safe for _ip.runlines() |
|
268 | """ Make a script safe for _ip.runlines() | |
269 |
|
269 | |||
270 | - Removes empty lines |
|
270 | - Removes empty lines | |
271 | - Suffixes all indented blocks that end with unindented lines with empty lines |
|
271 | - Suffixes all indented blocks that end with unindented lines with empty lines | |
272 |
|
272 | |||
273 | """ |
|
273 | """ | |
274 | res = [] |
|
274 | res = [] | |
275 | lines = script.splitlines() |
|
275 | lines = script.splitlines() | |
276 | level = 0 |
|
276 | level = 0 | |
277 | for l in lines: |
|
277 | for l in lines: | |
278 | stripped = l.lstrip() |
|
278 | stripped = l.lstrip() | |
279 | if not l.strip(): |
|
279 | if not l.strip(): | |
280 | continue |
|
280 | continue | |
281 | newlevel = len(l) - len(stripped) |
|
281 | newlevel = len(l) - len(stripped) | |
282 | if level > 0 and newlevel == 0: |
|
282 | if level > 0 and newlevel == 0: | |
283 | # add empty line |
|
283 | # add empty line | |
284 | res.append('') |
|
284 | res.append('') | |
285 | res.append(l) |
|
285 | res.append(l) | |
286 | level = newlevel |
|
286 | level = newlevel | |
287 | return '\n'.join(res) + '\n' |
|
287 | return '\n'.join(res) + '\n' | |
288 |
|
288 | |||
289 | if isinstance(lines,basestring): |
|
289 | if isinstance(lines,basestring): | |
290 | script = lines |
|
290 | script = lines | |
291 | else: |
|
291 | else: | |
292 | script = '\n'.join(lines) |
|
292 | script = '\n'.join(lines) | |
293 | clean=cleanup_ipy_script(script) |
|
293 | clean=cleanup_ipy_script(script) | |
294 |
|
294 | |||
295 | self.IP.runlines(clean) |
|
295 | self.IP.runlines(clean) | |
296 | def to_user_ns(self,vars, interactive = True): |
|
296 | def to_user_ns(self,vars, interactive = True): | |
297 | """Inject a group of variables into the IPython user namespace. |
|
297 | """Inject a group of variables into the IPython user namespace. | |
298 |
|
298 | |||
299 | Inputs: |
|
299 | Inputs: | |
300 |
|
300 | |||
301 | - vars: string with variable names separated by whitespace, or a |
|
301 | - vars: string with variable names separated by whitespace, or a | |
302 | dict with name/value pairs. |
|
302 | dict with name/value pairs. | |
303 |
|
303 | |||
304 | - interactive: if True (default), the var will be listed with |
|
304 | - interactive: if True (default), the var will be listed with | |
305 | %whos et. al. |
|
305 | %whos et. al. | |
306 |
|
306 | |||
307 | This utility routine is meant to ease interactive debugging work, |
|
307 | This utility routine is meant to ease interactive debugging work, | |
308 | where you want to easily propagate some internal variable in your code |
|
308 | where you want to easily propagate some internal variable in your code | |
309 | up to the interactive namespace for further exploration. |
|
309 | up to the interactive namespace for further exploration. | |
310 |
|
310 | |||
311 | When you run code via %run, globals in your script become visible at |
|
311 | When you run code via %run, globals in your script become visible at | |
312 | the interactive prompt, but this doesn't happen for locals inside your |
|
312 | the interactive prompt, but this doesn't happen for locals inside your | |
313 | own functions and methods. Yet when debugging, it is common to want |
|
313 | own functions and methods. Yet when debugging, it is common to want | |
314 | to explore some internal variables further at the interactive propmt. |
|
314 | to explore some internal variables further at the interactive propmt. | |
315 |
|
315 | |||
316 | Examples: |
|
316 | Examples: | |
317 |
|
317 | |||
318 | To use this, you first must obtain a handle on the ipython object as |
|
318 | To use this, you first must obtain a handle on the ipython object as | |
319 | indicated above, via: |
|
319 | indicated above, via: | |
320 |
|
320 | |||
321 | import IPython.ipapi |
|
321 | import IPython.ipapi | |
322 | ip = IPython.ipapi.get() |
|
322 | ip = IPython.ipapi.get() | |
323 |
|
323 | |||
324 | Once this is done, inside a routine foo() where you want to expose |
|
324 | Once this is done, inside a routine foo() where you want to expose | |
325 | variables x and y, you do the following: |
|
325 | variables x and y, you do the following: | |
326 |
|
326 | |||
327 | def foo(): |
|
327 | def foo(): | |
328 | ... |
|
328 | ... | |
329 | x = your_computation() |
|
329 | x = your_computation() | |
330 | y = something_else() |
|
330 | y = something_else() | |
331 |
|
331 | |||
332 | # This pushes x and y to the interactive prompt immediately, even |
|
332 | # This pushes x and y to the interactive prompt immediately, even | |
333 | # if this routine crashes on the next line after: |
|
333 | # if this routine crashes on the next line after: | |
334 | ip.to_user_ns('x y') |
|
334 | ip.to_user_ns('x y') | |
335 | ... |
|
335 | ... | |
336 |
|
336 | |||
337 | # To expose *ALL* the local variables from the function, use: |
|
337 | # To expose *ALL* the local variables from the function, use: | |
338 | ip.to_user_ns(locals()) |
|
338 | ip.to_user_ns(locals()) | |
339 |
|
339 | |||
340 | ... |
|
340 | ... | |
341 | # return |
|
341 | # return | |
342 |
|
342 | |||
343 |
|
343 | |||
344 | If you need to rename variables, the dict input makes it easy. For |
|
344 | If you need to rename variables, the dict input makes it easy. For | |
345 | example, this call exposes variables 'foo' as 'x' and 'bar' as 'y' |
|
345 | example, this call exposes variables 'foo' as 'x' and 'bar' as 'y' | |
346 | in IPython user namespace: |
|
346 | in IPython user namespace: | |
347 |
|
347 | |||
348 | ip.to_user_ns(dict(x=foo,y=bar)) |
|
348 | ip.to_user_ns(dict(x=foo,y=bar)) | |
349 | """ |
|
349 | """ | |
350 |
|
350 | |||
351 | # print 'vars given:',vars # dbg |
|
351 | # print 'vars given:',vars # dbg | |
352 |
|
352 | |||
353 | # We need a dict of name/value pairs to do namespace updates. |
|
353 | # We need a dict of name/value pairs to do namespace updates. | |
354 | if isinstance(vars,dict): |
|
354 | if isinstance(vars,dict): | |
355 | # If a dict was given, no need to change anything. |
|
355 | # If a dict was given, no need to change anything. | |
356 | vdict = vars |
|
356 | vdict = vars | |
357 | elif isinstance(vars,basestring): |
|
357 | elif isinstance(vars,basestring): | |
358 | # If a string with names was given, get the caller's frame to |
|
358 | # If a string with names was given, get the caller's frame to | |
359 | # evaluate the given names in |
|
359 | # evaluate the given names in | |
360 | cf = sys._getframe(1) |
|
360 | cf = sys._getframe(1) | |
361 | vdict = {} |
|
361 | vdict = {} | |
362 | for name in vars.split(): |
|
362 | for name in vars.split(): | |
363 | try: |
|
363 | try: | |
364 | vdict[name] = eval(name,cf.f_globals,cf.f_locals) |
|
364 | vdict[name] = eval(name,cf.f_globals,cf.f_locals) | |
365 | except: |
|
365 | except: | |
366 | print ('could not get var. %s from %s' % |
|
366 | print ('could not get var. %s from %s' % | |
367 | (name,cf.f_code.co_name)) |
|
367 | (name,cf.f_code.co_name)) | |
368 | else: |
|
368 | else: | |
369 | raise ValueError('vars must be a string or a dict') |
|
369 | raise ValueError('vars must be a string or a dict') | |
370 |
|
370 | |||
371 | # Propagate variables to user namespace |
|
371 | # Propagate variables to user namespace | |
372 | self.user_ns.update(vdict) |
|
372 | self.user_ns.update(vdict) | |
373 |
|
373 | |||
374 | # And configure interactive visibility |
|
374 | # And configure interactive visibility | |
375 | config_ns = self.IP.user_config_ns |
|
375 | config_ns = self.IP.user_config_ns | |
376 | if interactive: |
|
376 | if interactive: | |
377 | for name,val in vdict.iteritems(): |
|
377 | for name,val in vdict.iteritems(): | |
378 | config_ns.pop(name,None) |
|
378 | config_ns.pop(name,None) | |
379 | else: |
|
379 | else: | |
380 | for name,val in vdict.iteritems(): |
|
380 | for name,val in vdict.iteritems(): | |
381 | config_ns[name] = val |
|
381 | config_ns[name] = val | |
382 |
|
382 | |||
383 |
|
383 | |||
384 | def expand_alias(self,line): |
|
384 | def expand_alias(self,line): | |
385 | """ Expand an alias in the command line |
|
385 | """ Expand an alias in the command line | |
386 |
|
386 | |||
387 | Returns the provided command line, possibly with the first word |
|
387 | Returns the provided command line, possibly with the first word | |
388 | (command) translated according to alias expansion rules. |
|
388 | (command) translated according to alias expansion rules. | |
389 |
|
389 | |||
390 | [ipython]|16> _ip.expand_aliases("np myfile.txt") |
|
390 | [ipython]|16> _ip.expand_aliases("np myfile.txt") | |
391 | <16> 'q:/opt/np/notepad++.exe myfile.txt' |
|
391 | <16> 'q:/opt/np/notepad++.exe myfile.txt' | |
392 | """ |
|
392 | """ | |
393 |
|
393 | |||
394 | pre,fn,rest = self.IP.split_user_input(line) |
|
394 | pre,fn,rest = self.IP.split_user_input(line) | |
395 | res = pre + self.IP.expand_aliases(fn,rest) |
|
395 | res = pre + self.IP.expand_aliases(fn,rest) | |
396 | return res |
|
396 | return res | |
397 |
|
397 | |||
398 | def itpl(self, s, depth = 1): |
|
398 | def itpl(self, s, depth = 1): | |
399 | """ Expand Itpl format string s. |
|
399 | """ Expand Itpl format string s. | |
400 |
|
400 | |||
401 | Only callable from command line (i.e. prefilter results); |
|
401 | Only callable from command line (i.e. prefilter results); | |
402 | If you use in your scripts, you need to use a bigger depth! |
|
402 | If you use in your scripts, you need to use a bigger depth! | |
403 | """ |
|
403 | """ | |
404 | return self.IP.var_expand(s, depth) |
|
404 | return self.IP.var_expand(s, depth) | |
405 |
|
405 | |||
406 | def defalias(self, name, cmd): |
|
406 | def defalias(self, name, cmd): | |
407 | """ Define a new alias |
|
407 | """ Define a new alias | |
408 |
|
408 | |||
409 | _ip.defalias('bb','bldmake bldfiles') |
|
409 | _ip.defalias('bb','bldmake bldfiles') | |
410 |
|
410 | |||
411 | Creates a new alias named 'bb' in ipython user namespace |
|
411 | Creates a new alias named 'bb' in ipython user namespace | |
412 | """ |
|
412 | """ | |
413 |
|
413 | |||
414 | self.dbg.check_hotname(name) |
|
414 | self.dbg.check_hotname(name) | |
415 |
|
415 | |||
416 |
|
416 | |||
417 | if name in self.IP.alias_table: |
|
417 | if name in self.IP.alias_table: | |
418 | self.dbg.debug_stack("Alias redefinition: '%s' => '%s' (old '%s')" % |
|
418 | self.dbg.debug_stack("Alias redefinition: '%s' => '%s' (old '%s')" % | |
419 | (name, cmd, self.IP.alias_table[name])) |
|
419 | (name, cmd, self.IP.alias_table[name])) | |
420 |
|
420 | |||
421 |
|
421 | |||
422 | if callable(cmd): |
|
422 | if callable(cmd): | |
423 | self.IP.alias_table[name] = cmd |
|
423 | self.IP.alias_table[name] = cmd | |
424 | import IPython.shadowns |
|
424 | import IPython.shadowns | |
425 | setattr(IPython.shadowns, name,cmd) |
|
425 | setattr(IPython.shadowns, name,cmd) | |
426 | return |
|
426 | return | |
427 |
|
427 | |||
428 | if isinstance(cmd,basestring): |
|
428 | if isinstance(cmd,basestring): | |
429 | nargs = cmd.count('%s') |
|
429 | nargs = cmd.count('%s') | |
430 | if nargs>0 and cmd.find('%l')>=0: |
|
430 | if nargs>0 and cmd.find('%l')>=0: | |
431 | raise Exception('The %s and %l specifiers are mutually exclusive ' |
|
431 | raise Exception('The %s and %l specifiers are mutually exclusive ' | |
432 | 'in alias definitions.') |
|
432 | 'in alias definitions.') | |
433 |
|
433 | |||
434 | self.IP.alias_table[name] = (nargs,cmd) |
|
434 | self.IP.alias_table[name] = (nargs,cmd) | |
435 | return |
|
435 | return | |
436 |
|
436 | |||
437 | # just put it in - it's probably (0,'foo') |
|
437 | # just put it in - it's probably (0,'foo') | |
438 | self.IP.alias_table[name] = cmd |
|
438 | self.IP.alias_table[name] = cmd | |
439 |
|
439 | |||
440 | def defmacro(self, *args): |
|
440 | def defmacro(self, *args): | |
441 | """ Define a new macro |
|
441 | """ Define a new macro | |
442 |
|
442 | |||
443 | 2 forms of calling: |
|
443 | 2 forms of calling: | |
444 |
|
444 | |||
445 | mac = _ip.defmacro('print "hello"\nprint "world"') |
|
445 | mac = _ip.defmacro('print "hello"\nprint "world"') | |
446 |
|
446 | |||
447 | (doesn't put the created macro on user namespace) |
|
447 | (doesn't put the created macro on user namespace) | |
448 |
|
448 | |||
449 | _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb') |
|
449 | _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb') | |
450 |
|
450 | |||
451 | (creates a macro named 'build' in user namespace) |
|
451 | (creates a macro named 'build' in user namespace) | |
452 | """ |
|
452 | """ | |
453 |
|
453 | |||
454 | import IPython.macro |
|
454 | import IPython.macro | |
455 |
|
455 | |||
456 | if len(args) == 1: |
|
456 | if len(args) == 1: | |
457 | return IPython.macro.Macro(args[0]) |
|
457 | return IPython.macro.Macro(args[0]) | |
458 | elif len(args) == 2: |
|
458 | elif len(args) == 2: | |
459 | self.user_ns[args[0]] = IPython.macro.Macro(args[1]) |
|
459 | self.user_ns[args[0]] = IPython.macro.Macro(args[1]) | |
460 | else: |
|
460 | else: | |
461 | return Exception("_ip.defmacro must be called with 1 or 2 arguments") |
|
461 | return Exception("_ip.defmacro must be called with 1 or 2 arguments") | |
462 |
|
462 | |||
463 | def set_next_input(self, s): |
|
463 | def set_next_input(self, s): | |
464 | """ Sets the 'default' input string for the next command line. |
|
464 | """ Sets the 'default' input string for the next command line. | |
465 |
|
465 | |||
466 | Requires readline. |
|
466 | Requires readline. | |
467 |
|
467 | |||
468 | Example: |
|
468 | Example: | |
469 |
|
469 | |||
470 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
470 | [D:\ipython]|1> _ip.set_next_input("Hello Word") | |
471 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
471 | [D:\ipython]|2> Hello Word_ # cursor is here | |
472 | """ |
|
472 | """ | |
473 |
|
473 | |||
474 | self.IP.rl_next_input = s |
|
474 | self.IP.rl_next_input = s | |
475 |
|
475 | |||
476 | def load(self, mod): |
|
476 | def load(self, mod): | |
477 | """ Load an extension. |
|
477 | """ Load an extension. | |
478 |
|
478 | |||
479 | Some modules should (or must) be 'load()':ed, rather than just imported. |
|
479 | Some modules should (or must) be 'load()':ed, rather than just imported. | |
480 |
|
480 | |||
481 | Loading will do: |
|
481 | Loading will do: | |
482 |
|
482 | |||
483 | - run init_ipython(ip) |
|
483 | - run init_ipython(ip) | |
484 | - run ipython_firstrun(ip) |
|
484 | - run ipython_firstrun(ip) | |
485 |
|
485 | |||
486 | """ |
|
486 | """ | |
487 | if mod in self.extensions: |
|
487 | if mod in self.extensions: | |
488 | # just to make sure we don't init it twice |
|
488 | # just to make sure we don't init it twice | |
489 | # note that if you 'load' a module that has already been |
|
489 | # note that if you 'load' a module that has already been | |
490 | # imported, init_ipython gets run anyway |
|
490 | # imported, init_ipython gets run anyway | |
491 |
|
491 | |||
492 | return self.extensions[mod] |
|
492 | return self.extensions[mod] | |
493 | __import__(mod) |
|
493 | __import__(mod) | |
494 | m = sys.modules[mod] |
|
494 | m = sys.modules[mod] | |
495 | if hasattr(m,'init_ipython'): |
|
495 | if hasattr(m,'init_ipython'): | |
496 | m.init_ipython(self) |
|
496 | m.init_ipython(self) | |
497 |
|
497 | |||
498 | if hasattr(m,'ipython_firstrun'): |
|
498 | if hasattr(m,'ipython_firstrun'): | |
499 | already_loaded = self.db.get('firstrun_done', set()) |
|
499 | already_loaded = self.db.get('firstrun_done', set()) | |
500 | if mod not in already_loaded: |
|
500 | if mod not in already_loaded: | |
501 | m.ipython_firstrun(self) |
|
501 | m.ipython_firstrun(self) | |
502 | already_loaded.add(mod) |
|
502 | already_loaded.add(mod) | |
503 | self.db['firstrun_done'] = already_loaded |
|
503 | self.db['firstrun_done'] = already_loaded | |
504 |
|
504 | |||
505 | self.extensions[mod] = m |
|
505 | self.extensions[mod] = m | |
506 | return m |
|
506 | return m | |
507 |
|
507 | |||
508 |
|
508 | |||
509 | class DebugTools: |
|
509 | class DebugTools: | |
510 | """ Used for debugging mishaps in api usage |
|
510 | """ Used for debugging mishaps in api usage | |
511 |
|
511 | |||
512 | So far, tracing redefinitions is supported. |
|
512 | So far, tracing redefinitions is supported. | |
513 | """ |
|
513 | """ | |
514 |
|
514 | |||
515 | def __init__(self, ip): |
|
515 | def __init__(self, ip): | |
516 | self.ip = ip |
|
516 | self.ip = ip | |
517 | self.debugmode = False |
|
517 | self.debugmode = False | |
518 | self.hotnames = set() |
|
518 | self.hotnames = set() | |
519 |
|
519 | |||
520 | def hotname(self, name_to_catch): |
|
520 | def hotname(self, name_to_catch): | |
521 | self.hotnames.add(name_to_catch) |
|
521 | self.hotnames.add(name_to_catch) | |
522 |
|
522 | |||
523 | def debug_stack(self, msg = None): |
|
523 | def debug_stack(self, msg = None): | |
524 | if not self.debugmode: |
|
524 | if not self.debugmode: | |
525 | return |
|
525 | return | |
526 |
|
526 | |||
527 | import traceback |
|
527 | import traceback | |
528 | if msg is not None: |
|
528 | if msg is not None: | |
529 | print '====== %s ========' % msg |
|
529 | print '====== %s ========' % msg | |
530 | traceback.print_stack() |
|
530 | traceback.print_stack() | |
531 |
|
531 | |||
532 | def check_hotname(self,name): |
|
532 | def check_hotname(self,name): | |
533 | if name in self.hotnames: |
|
533 | if name in self.hotnames: | |
534 | self.debug_stack( "HotName '%s' caught" % name) |
|
534 | self.debug_stack( "HotName '%s' caught" % name) | |
535 |
|
535 | |||
536 | def launch_new_instance(user_ns = None): |
|
536 | def launch_new_instance(user_ns = None,shellclass = None): | |
537 | """ Make and start a new ipython instance. |
|
537 | """ Make and start a new ipython instance. | |
538 |
|
538 | |||
539 | This can be called even without having an already initialized |
|
539 | This can be called even without having an already initialized | |
540 | ipython session running. |
|
540 | ipython session running. | |
541 |
|
541 | |||
542 | This is also used as the egg entry point for the 'ipython' script. |
|
542 | This is also used as the egg entry point for the 'ipython' script. | |
543 |
|
543 | |||
544 | """ |
|
544 | """ | |
545 | ses = make_session(user_ns) |
|
545 | ses = make_session(user_ns,shellclass) | |
546 | ses.mainloop() |
|
546 | ses.mainloop() | |
547 |
|
547 | |||
548 |
|
548 | |||
549 | def make_user_ns(user_ns = None): |
|
549 | def make_user_ns(user_ns = None): | |
550 | """Return a valid user interactive namespace. |
|
550 | """Return a valid user interactive namespace. | |
551 |
|
551 | |||
552 | This builds a dict with the minimal information needed to operate as a |
|
552 | This builds a dict with the minimal information needed to operate as a | |
553 | valid IPython user namespace, which you can pass to the various embedding |
|
553 | valid IPython user namespace, which you can pass to the various embedding | |
554 | classes in ipython. |
|
554 | classes in ipython. | |
555 | """ |
|
555 | """ | |
556 |
|
556 | |||
557 | if user_ns is None: |
|
557 | if user_ns is None: | |
558 | # Set __name__ to __main__ to better match the behavior of the |
|
558 | # Set __name__ to __main__ to better match the behavior of the | |
559 | # normal interpreter. |
|
559 | # normal interpreter. | |
560 | user_ns = {'__name__' :'__main__', |
|
560 | user_ns = {'__name__' :'__main__', | |
561 | '__builtins__' : __builtin__, |
|
561 | '__builtins__' : __builtin__, | |
562 | } |
|
562 | } | |
563 | else: |
|
563 | else: | |
564 | user_ns.setdefault('__name__','__main__') |
|
564 | user_ns.setdefault('__name__','__main__') | |
565 | user_ns.setdefault('__builtins__',__builtin__) |
|
565 | user_ns.setdefault('__builtins__',__builtin__) | |
566 |
|
566 | |||
567 | return user_ns |
|
567 | return user_ns | |
568 |
|
568 | |||
569 |
|
569 | |||
570 | def make_user_global_ns(ns = None): |
|
570 | def make_user_global_ns(ns = None): | |
571 | """Return a valid user global namespace. |
|
571 | """Return a valid user global namespace. | |
572 |
|
572 | |||
573 | Similar to make_user_ns(), but global namespaces are really only needed in |
|
573 | Similar to make_user_ns(), but global namespaces are really only needed in | |
574 | embedded applications, where there is a distinction between the user's |
|
574 | embedded applications, where there is a distinction between the user's | |
575 | interactive namespace and the global one where ipython is running.""" |
|
575 | interactive namespace and the global one where ipython is running.""" | |
576 |
|
576 | |||
577 | if ns is None: ns = {} |
|
577 | if ns is None: ns = {} | |
578 | return ns |
|
578 | return ns | |
579 |
|
579 | |||
580 |
|
580 | |||
581 | def make_session(user_ns = None): |
|
581 | def make_session(user_ns = None, shellclass = None): | |
582 | """Makes, but does not launch an IPython session. |
|
582 | """Makes, but does not launch an IPython session. | |
583 |
|
583 | |||
584 | Later on you can call obj.mainloop() on the returned object. |
|
584 | Later on you can call obj.mainloop() on the returned object. | |
585 |
|
585 | |||
586 | Inputs: |
|
586 | Inputs: | |
587 |
|
587 | |||
588 | - user_ns(None): a dict to be used as the user's namespace with initial |
|
588 | - user_ns(None): a dict to be used as the user's namespace with initial | |
589 | data. |
|
589 | data. | |
590 |
|
590 | |||
591 | WARNING: This should *not* be run when a session exists already.""" |
|
591 | WARNING: This should *not* be run when a session exists already.""" | |
592 |
|
592 | |||
593 | import IPython.Shell |
|
593 | import IPython.Shell | |
|
594 | if shellclass is None: | |||
594 | return IPython.Shell.start(user_ns) |
|
595 | return IPython.Shell.start(user_ns) | |
595 |
|
596 | return shellclass(user_ns = user_ns) | ||
596 |
|
@@ -1,32 +1,42 b'' | |||||
1 | """ An example of one way to embed IPython in your own application |
|
1 | """ An example of one way to embed IPython in your own application | |
2 |
|
2 | |||
3 | This basically means starting up IPython with some of your programs objects visible in the IPython |
|
3 | This basically means starting up IPython with some of your programs objects visible in the IPython | |
4 | user namespace. |
|
4 | user namespace. | |
5 |
|
5 | |||
6 | """ |
|
6 | """ | |
7 |
|
7 | |||
8 | import sys |
|
8 | import sys | |
9 |
sys.path. |
|
9 | sys.path.insert(1,'..') | |
10 |
|
10 | |||
11 | import IPython.ipapi |
|
11 | import IPython.ipapi | |
12 |
|
12 | |||
13 | my_ns = dict(a=10) |
|
|||
14 |
|
13 | |||
|
14 | ||||
|
15 | def test_session(shellclass): | |||
|
16 | print "*****************\nLaunch shell for",shellclass | |||
|
17 | my_ns = dict(a=10) | |||
15 | ses = IPython.ipapi.make_session(my_ns) |
|
18 | ses = IPython.ipapi.make_session(my_ns) | |
16 |
|
19 | |||
17 | # Now get the ipapi instance, to be stored somewhere in your program for manipulation of the running |
|
20 | # Now get the ipapi instance, to be stored somewhere in your program for manipulation of the running | |
18 | # IPython session. See http://ipython.scipy.org/moin/IpythonExtensionApi |
|
21 | # IPython session. See http://ipython.scipy.org/moin/IpythonExtensionApi | |
19 |
|
22 | |||
20 | ip = ses.IP.getapi() |
|
23 | ip = ses.IP.getapi() | |
21 |
|
24 | |||
22 | # let's play with the ipapi a bit, creating a magic function for a soon-to-be-started IPython |
|
25 | # let's play with the ipapi a bit, creating a magic function for a soon-to-be-started IPython | |
23 | def mymagic_f(self,s): |
|
26 | def mymagic_f(self,s): | |
24 | print "mymagic says",s |
|
27 | print "mymagic says",s | |
25 |
|
28 | |||
26 | ip.expose_magic("mymagic",mymagic_f) |
|
29 | ip.expose_magic("mymagic",mymagic_f) | |
27 |
|
30 | |||
28 | # And finally, start the IPython interaction! This will block until you say Exit. |
|
31 | # And finally, start the IPython interaction! This will block until you say Exit. | |
29 |
|
32 | |||
30 | ses.mainloop() |
|
33 | ses.mainloop() | |
31 |
|
34 | |||
32 |
print "IPython session f |
|
35 | print "IPython session for shell ",shellclass," finished! namespace content:" | |
|
36 | for k,v in my_ns.items(): | |||
|
37 | print k,':',str(v)[:80].rstrip() | |||
|
38 | ||||
|
39 | import IPython.Shell | |||
|
40 | ||||
|
41 | test_session(shellclass = None) | |||
|
42 | test_session(IPython.Shell._select_shell(['ipython', '-q4thread'])) |
General Comments 0
You need to be logged in to leave comments.
Login now