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