Show More
The requested changes are too big and content was truncated. Show full diff
@@ -0,0 +1,68 b'' | |||||
|
1 | import IPython.ipapi | |||
|
2 | ip = IPython.ipapi.get() | |||
|
3 | ||||
|
4 | import os,pprint | |||
|
5 | ||||
|
6 | def export(filename = None): | |||
|
7 | ||||
|
8 | lines = ['import IPython.ipapi', 'ip = IPython.ipapi.get()',''] | |||
|
9 | ||||
|
10 | vars = ip.db.keys('autorestore/*') | |||
|
11 | vars.sort() | |||
|
12 | varstomove = [] | |||
|
13 | get = ip.db.get | |||
|
14 | ||||
|
15 | macros = [] | |||
|
16 | variables = [] | |||
|
17 | ||||
|
18 | for var in vars: | |||
|
19 | k = os.path.basename(var) | |||
|
20 | v = get(var) | |||
|
21 | ||||
|
22 | if k.startswith('_'): | |||
|
23 | continue | |||
|
24 | if isinstance(v, IPython.macro.Macro): | |||
|
25 | macros.append((k,v)) | |||
|
26 | if type(v) in [int, str, float]: | |||
|
27 | variables.append((k,v)) | |||
|
28 | ||||
|
29 | ||||
|
30 | ||||
|
31 | if macros: | |||
|
32 | lines.extend(['# === Macros ===' ,'']) | |||
|
33 | for k,v in macros: | |||
|
34 | lines.append("ip.defmacro('%s'," % k) | |||
|
35 | for line in v.value.splitlines(): | |||
|
36 | lines.append(' ' + repr(line+'\n')) | |||
|
37 | lines.extend([')', '']) | |||
|
38 | ||||
|
39 | if variables: | |||
|
40 | lines.extend(['','# === Variables ===','']) | |||
|
41 | for k,v in variables: | |||
|
42 | varstomove.append(k) | |||
|
43 | lines.append('%s = %s' % (k,repr(v))) | |||
|
44 | ||||
|
45 | lines.append('ip.to_user_ns("%s")' % (' '.join(varstomove))) | |||
|
46 | ||||
|
47 | bkms = ip.db.get('bookmarks',{}) | |||
|
48 | ||||
|
49 | if bkms: | |||
|
50 | lines.extend(['','# === Bookmarks ===','']) | |||
|
51 | lines.append("ip.db['bookmarks'] = %s " % pprint.pformat(bkms, indent = 2) ) | |||
|
52 | ||||
|
53 | aliases = ip.db.get('stored_aliases', {} ) | |||
|
54 | ||||
|
55 | if aliases: | |||
|
56 | lines.extend(['','# === Alias definitions ===','']) | |||
|
57 | for k,v in aliases.items(): | |||
|
58 | lines.append("ip.defalias('%s', %s)" % (k, repr(v[1]))) | |||
|
59 | ||||
|
60 | ||||
|
61 | ||||
|
62 | out = '\n'.join(lines) | |||
|
63 | ||||
|
64 | if filename: | |||
|
65 | open(filename,'w').write(out) | |||
|
66 | else: | |||
|
67 | print out | |||
|
68 |
@@ -1,405 +1,405 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 | # contains the most recently instantiated IPApi |
|
83 | # contains the most recently instantiated IPApi | |
84 |
|
84 | |||
85 | class IPythonNotRunning: |
|
85 | class IPythonNotRunning: | |
86 | """Dummy do-nothing class. |
|
86 | """Dummy do-nothing class. | |
87 |
|
87 | |||
88 | Instances of this class return a dummy attribute on all accesses, which |
|
88 | Instances of this class return a dummy attribute on all accesses, which | |
89 | can be called and warns. This makes it easier to write scripts which use |
|
89 | can be called and warns. This makes it easier to write scripts which use | |
90 | the ipapi.get() object for informational purposes to operate both with and |
|
90 | the ipapi.get() object for informational purposes to operate both with and | |
91 | without ipython. Obviously code which uses the ipython object for |
|
91 | without ipython. Obviously code which uses the ipython object for | |
92 | computations will not work, but this allows a wider range of code to |
|
92 | computations will not work, but this allows a wider range of code to | |
93 | transparently work whether ipython is being used or not.""" |
|
93 | transparently work whether ipython is being used or not.""" | |
94 |
|
94 | |||
95 | def __init__(self,warn=True): |
|
95 | def __init__(self,warn=True): | |
96 | if warn: |
|
96 | if warn: | |
97 | self.dummy = self._dummy_warn |
|
97 | self.dummy = self._dummy_warn | |
98 | else: |
|
98 | else: | |
99 | self.dummy = self._dummy_silent |
|
99 | self.dummy = self._dummy_silent | |
100 |
|
100 | |||
101 | def __str__(self): |
|
101 | def __str__(self): | |
102 | return "<IPythonNotRunning>" |
|
102 | return "<IPythonNotRunning>" | |
103 |
|
103 | |||
104 | __repr__ = __str__ |
|
104 | __repr__ = __str__ | |
105 |
|
105 | |||
106 | def __getattr__(self,name): |
|
106 | def __getattr__(self,name): | |
107 | return self.dummy |
|
107 | return self.dummy | |
108 |
|
108 | |||
109 | def _dummy_warn(self,*args,**kw): |
|
109 | def _dummy_warn(self,*args,**kw): | |
110 | """Dummy function, which doesn't do anything but warn.""" |
|
110 | """Dummy function, which doesn't do anything but warn.""" | |
111 |
|
111 | |||
112 | warn("IPython is not running, this is a dummy no-op function") |
|
112 | warn("IPython is not running, this is a dummy no-op function") | |
113 |
|
113 | |||
114 | def _dummy_silent(self,*args,**kw): |
|
114 | def _dummy_silent(self,*args,**kw): | |
115 | """Dummy function, which doesn't do anything and emits no warnings.""" |
|
115 | """Dummy function, which doesn't do anything and emits no warnings.""" | |
116 | pass |
|
116 | pass | |
117 |
|
117 | |||
118 | _recent = None |
|
118 | _recent = None | |
119 |
|
119 | |||
120 |
|
120 | |||
121 | def get(allow_dummy=False,dummy_warn=True): |
|
121 | def get(allow_dummy=False,dummy_warn=True): | |
122 | """Get an IPApi object. |
|
122 | """Get an IPApi object. | |
123 |
|
123 | |||
124 | If allow_dummy is true, returns an instance of IPythonNotRunning |
|
124 | If allow_dummy is true, returns an instance of IPythonNotRunning | |
125 | instead of None if not running under IPython. |
|
125 | instead of None if not running under IPython. | |
126 |
|
126 | |||
127 | If dummy_warn is false, the dummy instance will be completely silent. |
|
127 | If dummy_warn is false, the dummy instance will be completely silent. | |
128 |
|
128 | |||
129 | Running this should be the first thing you do when writing extensions that |
|
129 | Running this should be the first thing you do when writing extensions that | |
130 | can be imported as normal modules. You can then direct all the |
|
130 | can be imported as normal modules. You can then direct all the | |
131 | configuration operations against the returned object. |
|
131 | configuration operations against the returned object. | |
132 | """ |
|
132 | """ | |
133 | global _recent |
|
133 | global _recent | |
134 | if allow_dummy and not _recent: |
|
134 | if allow_dummy and not _recent: | |
135 | _recent = IPythonNotRunning(dummy_warn) |
|
135 | _recent = IPythonNotRunning(dummy_warn) | |
136 | return _recent |
|
136 | return _recent | |
137 |
|
137 | |||
138 | class IPApi: |
|
138 | class IPApi: | |
139 | """ The actual API class for configuring IPython |
|
139 | """ The actual API class for configuring IPython | |
140 |
|
140 | |||
141 | You should do all of the IPython configuration by getting an IPApi object |
|
141 | You should do all of the IPython configuration by getting an IPApi object | |
142 | with IPython.ipapi.get() and using the attributes and methods of the |
|
142 | with IPython.ipapi.get() and using the attributes and methods of the | |
143 | returned object.""" |
|
143 | returned object.""" | |
144 |
|
144 | |||
145 | def __init__(self,ip): |
|
145 | def __init__(self,ip): | |
146 |
|
146 | |||
147 | # All attributes exposed here are considered to be the public API of |
|
147 | # All attributes exposed here are considered to be the public API of | |
148 | # IPython. As needs dictate, some of these may be wrapped as |
|
148 | # IPython. As needs dictate, some of these may be wrapped as | |
149 | # properties. |
|
149 | # properties. | |
150 |
|
150 | |||
151 | self.magic = ip.ipmagic |
|
151 | self.magic = ip.ipmagic | |
152 |
|
152 | |||
153 | self.system = ip.ipsystem |
|
153 | self.system = ip.ipsystem | |
154 |
|
154 | |||
155 | self.set_hook = ip.set_hook |
|
155 | self.set_hook = ip.set_hook | |
156 |
|
156 | |||
157 | self.set_custom_exc = ip.set_custom_exc |
|
157 | self.set_custom_exc = ip.set_custom_exc | |
158 |
|
158 | |||
159 | self.user_ns = ip.user_ns |
|
159 | self.user_ns = ip.user_ns | |
160 |
|
160 | |||
161 | self.set_crash_handler = ip.set_crash_handler |
|
161 | self.set_crash_handler = ip.set_crash_handler | |
162 |
|
162 | |||
163 | # Session-specific data store, which can be used to store |
|
163 | # Session-specific data store, which can be used to store | |
164 | # data that should persist through the ipython session. |
|
164 | # data that should persist through the ipython session. | |
165 | self.meta = ip.meta |
|
165 | self.meta = ip.meta | |
166 |
|
166 | |||
167 | # The ipython instance provided |
|
167 | # The ipython instance provided | |
168 | self.IP = ip |
|
168 | self.IP = ip | |
169 |
|
169 | |||
170 | global _recent |
|
170 | global _recent | |
171 | _recent = self |
|
171 | _recent = self | |
172 |
|
172 | |||
173 | # Use a property for some things which are added to the instance very |
|
173 | # Use a property for some things which are added to the instance very | |
174 | # late. I don't have time right now to disentangle the initialization |
|
174 | # late. I don't have time right now to disentangle the initialization | |
175 | # order issues, so a property lets us delay item extraction while |
|
175 | # order issues, so a property lets us delay item extraction while | |
176 | # providing a normal attribute API. |
|
176 | # providing a normal attribute API. | |
177 | def get_db(self): |
|
177 | def get_db(self): | |
178 | """A handle to persistent dict-like database (a PickleShareDB object)""" |
|
178 | """A handle to persistent dict-like database (a PickleShareDB object)""" | |
179 | return self.IP.db |
|
179 | return self.IP.db | |
180 |
|
180 | |||
181 | db = property(get_db,None,None,get_db.__doc__) |
|
181 | db = property(get_db,None,None,get_db.__doc__) | |
182 |
|
182 | |||
183 | def get_options(self): |
|
183 | def get_options(self): | |
184 | """All configurable variables.""" |
|
184 | """All configurable variables.""" | |
185 |
|
185 | |||
186 | # catch typos by disabling new attribute creation. If new attr creation |
|
186 | # catch typos by disabling new attribute creation. If new attr creation | |
187 | # is in fact wanted (e.g. when exposing new options), do allow_new_attr(True) |
|
187 | # is in fact wanted (e.g. when exposing new options), do allow_new_attr(True) | |
188 | # for the received rc struct. |
|
188 | # for the received rc struct. | |
189 |
|
189 | |||
190 | self.IP.rc.allow_new_attr(False) |
|
190 | self.IP.rc.allow_new_attr(False) | |
191 | return self.IP.rc |
|
191 | return self.IP.rc | |
192 |
|
192 | |||
193 | options = property(get_options,None,None,get_options.__doc__) |
|
193 | options = property(get_options,None,None,get_options.__doc__) | |
194 |
|
194 | |||
195 | def expose_magic(self,magicname, func): |
|
195 | def expose_magic(self,magicname, func): | |
196 | ''' Expose own function as magic function for ipython |
|
196 | ''' Expose own function as magic function for ipython | |
197 |
|
197 | |||
198 | def foo_impl(self,parameter_s=''): |
|
198 | def foo_impl(self,parameter_s=''): | |
199 | """My very own magic!. (Use docstrings, IPython reads them).""" |
|
199 | """My very own magic!. (Use docstrings, IPython reads them).""" | |
200 | print 'Magic function. Passed parameter is between < >: <'+parameter_s+'>' |
|
200 | print 'Magic function. Passed parameter is between < >: <'+parameter_s+'>' | |
201 | print 'The self object is:',self |
|
201 | print 'The self object is:',self | |
202 |
|
202 | |||
203 | ipapi.expose_magic("foo",foo_impl) |
|
203 | ipapi.expose_magic("foo",foo_impl) | |
204 | ''' |
|
204 | ''' | |
205 |
|
205 | |||
206 | import new |
|
206 | import new | |
207 | im = new.instancemethod(func,self.IP, self.IP.__class__) |
|
207 | im = new.instancemethod(func,self.IP, self.IP.__class__) | |
208 | setattr(self.IP, "magic_" + magicname, im) |
|
208 | setattr(self.IP, "magic_" + magicname, im) | |
209 |
|
209 | |||
210 | def ex(self,cmd): |
|
210 | def ex(self,cmd): | |
211 | """ Execute a normal python statement in user namespace """ |
|
211 | """ Execute a normal python statement in user namespace """ | |
212 | exec cmd in self.user_ns |
|
212 | exec cmd in self.user_ns | |
213 |
|
213 | |||
214 | def ev(self,expr): |
|
214 | def ev(self,expr): | |
215 | """ Evaluate python expression expr in user namespace |
|
215 | """ Evaluate python expression expr in user namespace | |
216 |
|
216 | |||
217 | Returns the result of evaluation""" |
|
217 | Returns the result of evaluation""" | |
218 | return eval(expr,self.user_ns) |
|
218 | return eval(expr,self.user_ns) | |
219 |
|
219 | |||
220 | def runlines(self,lines): |
|
220 | def runlines(self,lines): | |
221 | """ Run the specified lines in interpreter, honoring ipython directives. |
|
221 | """ Run the specified lines in interpreter, honoring ipython directives. | |
222 |
|
222 | |||
223 | This allows %magic and !shell escape notations. |
|
223 | This allows %magic and !shell escape notations. | |
224 |
|
224 | |||
225 | Takes either all lines in one string or list of lines. |
|
225 | Takes either all lines in one string or list of lines. | |
226 | """ |
|
226 | """ | |
227 | if isinstance(lines,basestring): |
|
227 | if isinstance(lines,basestring): | |
228 | self.IP.runlines(lines) |
|
228 | self.IP.runlines(lines) | |
229 | else: |
|
229 | else: | |
230 | self.IP.runlines('\n'.join(lines)) |
|
230 | self.IP.runlines('\n'.join(lines)) | |
231 |
|
231 | |||
232 | def to_user_ns(self,vars): |
|
232 | def to_user_ns(self,vars): | |
233 | """Inject a group of variables into the IPython user namespace. |
|
233 | """Inject a group of variables into the IPython user namespace. | |
234 |
|
234 | |||
235 | Inputs: |
|
235 | Inputs: | |
236 |
|
236 | |||
237 | - vars: string with variable names separated by whitespace |
|
237 | - vars: string with variable names separated by whitespace | |
238 |
|
238 | |||
239 | This utility routine is meant to ease interactive debugging work, |
|
239 | This utility routine is meant to ease interactive debugging work, | |
240 | where you want to easily propagate some internal variable in your code |
|
240 | where you want to easily propagate some internal variable in your code | |
241 | up to the interactive namespace for further exploration. |
|
241 | up to the interactive namespace for further exploration. | |
242 |
|
242 | |||
243 | When you run code via %run, globals in your script become visible at |
|
243 | When you run code via %run, globals in your script become visible at | |
244 | the interactive prompt, but this doesn't happen for locals inside your |
|
244 | the interactive prompt, but this doesn't happen for locals inside your | |
245 | own functions and methods. Yet when debugging, it is common to want |
|
245 | own functions and methods. Yet when debugging, it is common to want | |
246 | to explore some internal variables further at the interactive propmt. |
|
246 | to explore some internal variables further at the interactive propmt. | |
247 |
|
247 | |||
248 | Examples: |
|
248 | Examples: | |
249 |
|
249 | |||
250 | To use this, you first must obtain a handle on the ipython object as |
|
250 | To use this, you first must obtain a handle on the ipython object as | |
251 | indicated above, via: |
|
251 | indicated above, via: | |
252 |
|
252 | |||
253 | import IPython.ipapi |
|
253 | import IPython.ipapi | |
254 | ip = IPython.ipapi.get() |
|
254 | ip = IPython.ipapi.get() | |
255 |
|
255 | |||
256 | Once this is done, inside a routine foo() where you want to expose |
|
256 | Once this is done, inside a routine foo() where you want to expose | |
257 | variables x and y, you do the following: |
|
257 | variables x and y, you do the following: | |
258 |
|
258 | |||
259 | def foo(): |
|
259 | def foo(): | |
260 | ... |
|
260 | ... | |
261 | x = your_computation() |
|
261 | x = your_computation() | |
262 | y = something_else() |
|
262 | y = something_else() | |
263 |
|
263 | |||
264 | # This pushes x and y to the interactive prompt immediately, even |
|
264 | # This pushes x and y to the interactive prompt immediately, even | |
265 | # if this routine crashes on the next line after: |
|
265 | # if this routine crashes on the next line after: | |
266 | ip.to_user_ns('x y') |
|
266 | ip.to_user_ns('x y') | |
267 | ... |
|
267 | ... | |
268 | # return |
|
268 | # return | |
269 |
|
269 | |||
270 | If you need to rename variables, just use ip.user_ns with dict |
|
270 | If you need to rename variables, just use ip.user_ns with dict | |
271 | and update: |
|
271 | and update: | |
272 |
|
272 | |||
273 | # exposes variables 'foo' as 'x' and 'bar' as 'y' in IPython |
|
273 | # exposes variables 'foo' as 'x' and 'bar' as 'y' in IPython | |
274 | # user namespace |
|
274 | # user namespace | |
275 | ip.user_ns.update(dict(x=foo,y=bar)) |
|
275 | ip.user_ns.update(dict(x=foo,y=bar)) | |
276 | """ |
|
276 | """ | |
277 |
|
277 | |||
278 | # print 'vars given:',vars # dbg |
|
278 | # print 'vars given:',vars # dbg | |
279 | # Get the caller's frame to evaluate the given names in |
|
279 | # Get the caller's frame to evaluate the given names in | |
280 | cf = sys._getframe(1) |
|
280 | cf = sys._getframe(1) | |
281 |
|
281 | |||
282 | user_ns = self.user_ns |
|
282 | user_ns = self.user_ns | |
283 |
|
283 | |||
284 | for name in vars.split(): |
|
284 | for name in vars.split(): | |
285 | try: |
|
285 | try: | |
286 | user_ns[name] = eval(name,cf.f_globals,cf.f_locals) |
|
286 | user_ns[name] = eval(name,cf.f_globals,cf.f_locals) | |
287 | except: |
|
287 | except: | |
288 | error('could not get var. %s from %s' % |
|
288 | error('could not get var. %s from %s' % | |
289 | (name,cf.f_code.co_name)) |
|
289 | (name,cf.f_code.co_name)) | |
290 |
|
290 | |||
291 | def expand_alias(self,line): |
|
291 | def expand_alias(self,line): | |
292 | """ Expand an alias in the command line |
|
292 | """ Expand an alias in the command line | |
293 |
|
293 | |||
294 | Returns the provided command line, possibly with the first word |
|
294 | Returns the provided command line, possibly with the first word | |
295 | (command) translated according to alias expansion rules. |
|
295 | (command) translated according to alias expansion rules. | |
296 |
|
296 | |||
297 | [ipython]|16> _ip.expand_aliases("np myfile.txt") |
|
297 | [ipython]|16> _ip.expand_aliases("np myfile.txt") | |
298 | <16> 'q:/opt/np/notepad++.exe myfile.txt' |
|
298 | <16> 'q:/opt/np/notepad++.exe myfile.txt' | |
299 | """ |
|
299 | """ | |
300 |
|
300 | |||
301 | pre,fn,rest = self.IP.split_user_input(line) |
|
301 | pre,fn,rest = self.IP.split_user_input(line) | |
302 | res = pre + self.IP.expand_aliases(fn,rest) |
|
302 | res = pre + self.IP.expand_aliases(fn,rest) | |
303 |
|
303 | |||
304 | def defalias(self, name, cmd): |
|
304 | def defalias(self, name, cmd): | |
305 | """ Define a new alias |
|
305 | """ Define a new alias | |
306 |
|
306 | |||
307 | _ip.defalias('bb','bldmake bldfiles') |
|
307 | _ip.defalias('bb','bldmake bldfiles') | |
308 |
|
308 | |||
309 | Creates a new alias named 'bb' in ipython user namespace |
|
309 | Creates a new alias named 'bb' in ipython user namespace | |
310 | """ |
|
310 | """ | |
311 |
|
311 | |||
312 |
|
312 | |||
313 | nargs = cmd.count('%s') |
|
313 | nargs = cmd.count('%s') | |
314 | if nargs>0 and cmd.find('%l')>=0: |
|
314 | if nargs>0 and cmd.find('%l')>=0: | |
315 | raise Exception('The %s and %l specifiers are mutually exclusive ' |
|
315 | raise Exception('The %s and %l specifiers are mutually exclusive ' | |
316 | 'in alias definitions.') |
|
316 | 'in alias definitions.') | |
317 |
|
317 | |||
318 | else: # all looks OK |
|
318 | else: # all looks OK | |
319 | self.IP.alias_table[name] = (nargs,cmd) |
|
319 | self.IP.alias_table[name] = (nargs,cmd) | |
320 |
|
320 | |||
321 | def defmacro(self, *args): |
|
321 | def defmacro(self, *args): | |
322 | """ Define a new macro |
|
322 | """ Define a new macro | |
323 |
|
323 | |||
324 | 2 forms of calling: |
|
324 | 2 forms of calling: | |
325 |
|
325 | |||
326 | mac = _ip.defmacro('print "hello"\nprint "world"') |
|
326 | mac = _ip.defmacro('print "hello"\nprint "world"') | |
327 |
|
327 | |||
328 | (doesn't put the created macro on user namespace) |
|
328 | (doesn't put the created macro on user namespace) | |
329 |
|
329 | |||
330 | _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb') |
|
330 | _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb') | |
331 |
|
331 | |||
332 | (creates a macro named 'build' in user namespace) |
|
332 | (creates a macro named 'build' in user namespace) | |
333 | """ |
|
333 | """ | |
334 |
|
334 | |||
335 | import IPython.macro |
|
335 | import IPython.macro | |
336 |
|
|
336 | ||
337 | if len(args) == 1: |
|
337 | if len(args) == 1: | |
338 | return IPython.macro.Macro(args[0]) |
|
338 | return IPython.macro.Macro(args[0]) | |
339 | elif len(args) == 2: |
|
339 | elif len(args) == 2: | |
340 | self.user_ns[args[0]] = IPython.macro.Macro(args[1]) |
|
340 | self.user_ns[args[0]] = IPython.macro.Macro(args[1]) | |
341 | else: |
|
341 | else: | |
342 | return Exception("_ip.defmacro must be called with 1 or 2 arguments") |
|
342 | return Exception("_ip.defmacro must be called with 1 or 2 arguments") | |
343 |
|
343 | |||
344 |
|
344 | |||
345 |
|
345 | |||
346 | def launch_new_instance(user_ns = None): |
|
346 | def launch_new_instance(user_ns = None): | |
347 | """ Make and start a new ipython instance. |
|
347 | """ Make and start a new ipython instance. | |
348 |
|
348 | |||
349 | This can be called even without having an already initialized |
|
349 | This can be called even without having an already initialized | |
350 | ipython session running. |
|
350 | ipython session running. | |
351 |
|
351 | |||
352 | This is also used as the egg entry point for the 'ipython' script. |
|
352 | This is also used as the egg entry point for the 'ipython' script. | |
353 |
|
353 | |||
354 | """ |
|
354 | """ | |
355 | ses = make_session(user_ns) |
|
355 | ses = make_session(user_ns) | |
356 | ses.mainloop() |
|
356 | ses.mainloop() | |
357 |
|
357 | |||
358 |
|
358 | |||
359 | def make_user_ns(user_ns = None): |
|
359 | def make_user_ns(user_ns = None): | |
360 | """Return a valid user interactive namespace. |
|
360 | """Return a valid user interactive namespace. | |
361 |
|
361 | |||
362 | This builds a dict with the minimal information needed to operate as a |
|
362 | This builds a dict with the minimal information needed to operate as a | |
363 | valid IPython user namespace, which you can pass to the various embedding |
|
363 | valid IPython user namespace, which you can pass to the various embedding | |
364 | classes in ipython. |
|
364 | classes in ipython. | |
365 | """ |
|
365 | """ | |
366 |
|
366 | |||
367 | if user_ns is None: |
|
367 | if user_ns is None: | |
368 | # Set __name__ to __main__ to better match the behavior of the |
|
368 | # Set __name__ to __main__ to better match the behavior of the | |
369 | # normal interpreter. |
|
369 | # normal interpreter. | |
370 | user_ns = {'__name__' :'__main__', |
|
370 | user_ns = {'__name__' :'__main__', | |
371 | '__builtins__' : __builtin__, |
|
371 | '__builtins__' : __builtin__, | |
372 | } |
|
372 | } | |
373 | else: |
|
373 | else: | |
374 | user_ns.setdefault('__name__','__main__') |
|
374 | user_ns.setdefault('__name__','__main__') | |
375 | user_ns.setdefault('__builtins__',__builtin__) |
|
375 | user_ns.setdefault('__builtins__',__builtin__) | |
376 |
|
376 | |||
377 | return user_ns |
|
377 | return user_ns | |
378 |
|
378 | |||
379 |
|
379 | |||
380 | def make_user_global_ns(ns = None): |
|
380 | def make_user_global_ns(ns = None): | |
381 | """Return a valid user global namespace. |
|
381 | """Return a valid user global namespace. | |
382 |
|
382 | |||
383 | Similar to make_user_ns(), but global namespaces are really only needed in |
|
383 | Similar to make_user_ns(), but global namespaces are really only needed in | |
384 | embedded applications, where there is a distinction between the user's |
|
384 | embedded applications, where there is a distinction between the user's | |
385 | interactive namespace and the global one where ipython is running.""" |
|
385 | interactive namespace and the global one where ipython is running.""" | |
386 |
|
386 | |||
387 | if ns is None: ns = {} |
|
387 | if ns is None: ns = {} | |
388 | return ns |
|
388 | return ns | |
389 |
|
389 | |||
390 |
|
390 | |||
391 | def make_session(user_ns = None): |
|
391 | def make_session(user_ns = None): | |
392 | """Makes, but does not launch an IPython session. |
|
392 | """Makes, but does not launch an IPython session. | |
393 |
|
393 | |||
394 | Later on you can call obj.mainloop() on the returned object. |
|
394 | Later on you can call obj.mainloop() on the returned object. | |
395 |
|
395 | |||
396 | Inputs: |
|
396 | Inputs: | |
397 |
|
397 | |||
398 | - user_ns(None): a dict to be used as the user's namespace with initial |
|
398 | - user_ns(None): a dict to be used as the user's namespace with initial | |
399 | data. |
|
399 | data. | |
400 |
|
400 | |||
401 | WARNING: This should *not* be run when a session exists already.""" |
|
401 | WARNING: This should *not* be run when a session exists already.""" | |
402 |
|
402 | |||
403 | import IPython |
|
403 | import IPython | |
404 | return IPython.Shell.start(user_ns) |
|
404 | return IPython.Shell.start(user_ns) | |
405 |
|
405 |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
General Comments 0
You need to be logged in to leave comments.
Login now