Show More
The requested changes are too big and content was truncated. Show full diff
@@ -0,0 +1,311 b'' | |||
|
1 | # -*- coding: utf-8 -*- | |
|
2 | """ | |
|
3 | %jot magic for lightweight persistence. | |
|
4 | ||
|
5 | Stores variables in Struct with some notes in PicleShare database | |
|
6 | ||
|
7 | ||
|
8 | """ | |
|
9 | ||
|
10 | from datetime import datetime | |
|
11 | import IPython.ipapi | |
|
12 | ip = IPython.ipapi.get() | |
|
13 | ||
|
14 | import pickleshare | |
|
15 | ||
|
16 | import inspect,pickle,os,sys,textwrap | |
|
17 | from IPython.FakeModule import FakeModule | |
|
18 | from IPython.ipstruct import Struct | |
|
19 | ||
|
20 | ||
|
21 | def refresh_variables(ip, key=None): | |
|
22 | db = ip.db | |
|
23 | if key is None: | |
|
24 | keys = db.keys('jot/*') | |
|
25 | else: | |
|
26 | keys = db.keys('jot/'+key) | |
|
27 | for key in keys: | |
|
28 | # strip autorestore | |
|
29 | justkey = os.path.basename(key) | |
|
30 | print "Restoring from", justkey, "..." | |
|
31 | try: | |
|
32 | obj = db[key] | |
|
33 | except KeyError: | |
|
34 | print "Unable to restore variable '%s', ignoring (use %%jot -d to forget!)" % justkey | |
|
35 | print "The error was:",sys.exc_info()[0] | |
|
36 | else: | |
|
37 | #print "restored",justkey,"=",obj #dbg | |
|
38 | try: | |
|
39 | origname = obj.name | |
|
40 | except: | |
|
41 | ip.user_ns[justkey] = obj | |
|
42 | print "Restored", justkey | |
|
43 | else: | |
|
44 | ip.user_ns[origname] = obj['val'] | |
|
45 | print "Restored", origname | |
|
46 | ||
|
47 | def read_variables(ip, key=None): | |
|
48 | db = ip.db | |
|
49 | if key is None: | |
|
50 | return None | |
|
51 | else: | |
|
52 | keys = db.keys('jot/'+key) | |
|
53 | for key in keys: | |
|
54 | # strip autorestore | |
|
55 | justkey = os.path.basename(key) | |
|
56 | print "restoring from ", justkey | |
|
57 | try: | |
|
58 | obj = db[key] | |
|
59 | except KeyError: | |
|
60 | print "Unable to read variable '%s', ignoring (use %%jot -d to forget!)" % justkey | |
|
61 | print "The error was:",sys.exc_info()[0] | |
|
62 | else: | |
|
63 | return obj | |
|
64 | ||
|
65 | ||
|
66 | def detail_variables(ip, key=None): | |
|
67 | db, get = ip.db, ip.db.get | |
|
68 | ||
|
69 | if key is None: | |
|
70 | keys = db.keys('jot/*') | |
|
71 | else: | |
|
72 | keys = db.keys('jot/'+key) | |
|
73 | if keys: | |
|
74 | size = max(map(len,keys)) | |
|
75 | else: | |
|
76 | size = 0 | |
|
77 | ||
|
78 | fmthead = '%-'+str(size)+'s [%s]' | |
|
79 | fmtbody = 'Comment:\n %s' | |
|
80 | fmtdata = 'Data:\n %s, %s' | |
|
81 | for key in keys: | |
|
82 | v = get(key,'<unavailable>') | |
|
83 | justkey = os.path.basename(key) | |
|
84 | try: | |
|
85 | print fmthead % (justkey, datetime.ctime(v.get('time','<unavailable>'))) | |
|
86 | print fmtbody % (v.get('comment','<unavailable>')) | |
|
87 | d = v.get('val','unavailable') | |
|
88 | print fmtdata % (repr(type(d)), '') | |
|
89 | print repr(d)[0:200] | |
|
90 | ||
|
91 | ||
|
92 | except AttributeError: | |
|
93 | print fmt % (justkey, '<unavailable>', '<unavailable>', repr(v)[:50]) | |
|
94 | ||
|
95 | ||
|
96 | def intm(n): | |
|
97 | try: | |
|
98 | return int(n) | |
|
99 | except: | |
|
100 | return 0 | |
|
101 | ||
|
102 | def jot_obj(self, obj, name, comment=''): | |
|
103 | """ | |
|
104 | write obj data to the note database, with whatever that should be noted. | |
|
105 | """ | |
|
106 | had = self.db.keys('jot/'+name+'*') | |
|
107 | # if it the same name but a later version, we stupidly add a number to the | |
|
108 | # so the name doesn't collide. Any better idea? | |
|
109 | suffix = '' | |
|
110 | if len(had)>0: | |
|
111 | pre = os.path.commonprefix(had) | |
|
112 | suf = [n.split(pre)[1] for n in had] | |
|
113 | versions = map(intm, suf) | |
|
114 | suffix = str(max(versions)+1) | |
|
115 | ||
|
116 | uname = 'jot/'+name+suffix | |
|
117 | ||
|
118 | # which one works better? | |
|
119 | #all = ip.IP.shadowhist.all() | |
|
120 | all = ip.IP.shell.input_hist | |
|
121 | ||
|
122 | # We may actually want to make snapshot of files that are run-ned. | |
|
123 | ||
|
124 | # get the comment | |
|
125 | try: | |
|
126 | comment = ip.IP.magic_edit('-x').strip() | |
|
127 | except: | |
|
128 | print "No comment is recorded." | |
|
129 | comment = '' | |
|
130 | ||
|
131 | self.db[uname] = Struct({'val':obj, | |
|
132 | 'time' : datetime.now(), | |
|
133 | 'hist' : all, | |
|
134 | 'name' : name, | |
|
135 | 'comment' : comment,}) | |
|
136 | ||
|
137 | print "Jotted down notes for '%s' (%s)" % (uname, obj.__class__.__name__) | |
|
138 | ||
|
139 | ||
|
140 | ||
|
141 | def magic_jot(self, parameter_s=''): | |
|
142 | """Lightweight persistence for python variables. | |
|
143 | ||
|
144 | Example: | |
|
145 | ||
|
146 | ville@badger[~]|1> A = ['hello',10,'world']\\ | |
|
147 | ville@badger[~]|2> %jot A\\ | |
|
148 | ville@badger[~]|3> Exit | |
|
149 | ||
|
150 | (IPython session is closed and started again...) | |
|
151 | ||
|
152 | ville@badger:~$ ipython -p pysh\\ | |
|
153 | ville@badger[~]|1> print A | |
|
154 | ||
|
155 | ['hello', 10, 'world'] | |
|
156 | ||
|
157 | Usage: | |
|
158 | ||
|
159 | %jot - Show list of all variables and their current values\\ | |
|
160 | %jot -l - Show list of all variables and their current values in detail\\ | |
|
161 | %jot -l <var> - Show one variable and its current values in detail\\ | |
|
162 | %jot <var> - Store the *current* value of the variable to disk\\ | |
|
163 | %jot -d <var> - Remove the variable and its value from storage\\ | |
|
164 | %jot -z - Remove all variables from storage (disabled)\\ | |
|
165 | %jot -r <var> - Refresh/Load variable from jot (delete current vals)\\ | |
|
166 | %jot foo >a.txt - Store value of foo to new file a.txt\\ | |
|
167 | %jot foo >>a.txt - Append value of foo to file a.txt\\ | |
|
168 | ||
|
169 | It should be noted that if you change the value of a variable, you | |
|
170 | need to %note it again if you want to persist the new value. | |
|
171 | ||
|
172 | Note also that the variables will need to be pickleable; most basic | |
|
173 | python types can be safely %stored. | |
|
174 | ||
|
175 | """ | |
|
176 | ||
|
177 | opts,argsl = self.parse_options(parameter_s,'drzl',mode='string') | |
|
178 | args = argsl.split(None,1) | |
|
179 | ip = self.getapi() | |
|
180 | db = ip.db | |
|
181 | # delete | |
|
182 | if opts.has_key('d'): | |
|
183 | try: | |
|
184 | todel = args[0] | |
|
185 | except IndexError: | |
|
186 | error('You must provide the variable to forget') | |
|
187 | else: | |
|
188 | try: | |
|
189 | del db['jot/' + todel] | |
|
190 | except: | |
|
191 | error("Can't delete variable '%s'" % todel) | |
|
192 | # reset the whole database | |
|
193 | elif opts.has_key('z'): | |
|
194 | print "reseting the whole database has been disabled." | |
|
195 | #for k in db.keys('autorestore/*'): | |
|
196 | # del db[k] | |
|
197 | ||
|
198 | elif opts.has_key('r'): | |
|
199 | try: | |
|
200 | toret = args[0] | |
|
201 | except: | |
|
202 | print "restoring all the variables jotted down..." | |
|
203 | refresh_variables(ip) | |
|
204 | else: | |
|
205 | refresh_variables(ip, toret) | |
|
206 | ||
|
207 | elif opts.has_key('l'): | |
|
208 | try: | |
|
209 | tolist = args[0] | |
|
210 | except: | |
|
211 | print "List details for all the items." | |
|
212 | detail_variables(ip) | |
|
213 | else: | |
|
214 | print "Details for", tolist, ":" | |
|
215 | detail_variables(ip, tolist) | |
|
216 | ||
|
217 | # run without arguments -> list noted variables & notes | |
|
218 | elif not args: | |
|
219 | vars = self.db.keys('jot/*') | |
|
220 | vars.sort() | |
|
221 | if vars: | |
|
222 | size = max(map(len,vars)) - 4 | |
|
223 | else: | |
|
224 | size = 0 | |
|
225 | ||
|
226 | print 'Variables and their in-db values:' | |
|
227 | fmt = '%-'+str(size)+'s [%s] -> %s' | |
|
228 | get = db.get | |
|
229 | for var in vars: | |
|
230 | justkey = os.path.basename(var) | |
|
231 | v = get(var,'<unavailable>') | |
|
232 | try: | |
|
233 | print fmt % (justkey,\ | |
|
234 | datetime.ctime(v.get('time','<unavailable>')),\ | |
|
235 | v.get('comment','<unavailable>')[:70].replace('\n',' '),) | |
|
236 | except AttributeError: | |
|
237 | print fmt % (justkey, '<unavailable>', '<unavailable>', repr(v)[:50]) | |
|
238 | ||
|
239 | ||
|
240 | # default action - store the variable | |
|
241 | else: | |
|
242 | # %store foo >file.txt or >>file.txt | |
|
243 | if len(args) > 1 and args[1].startswith('>'): | |
|
244 | fnam = os.path.expanduser(args[1].lstrip('>').lstrip()) | |
|
245 | if args[1].startswith('>>'): | |
|
246 | fil = open(fnam,'a') | |
|
247 | else: | |
|
248 | fil = open(fnam,'w') | |
|
249 | obj = ip.ev(args[0]) | |
|
250 | print "Writing '%s' (%s) to file '%s'." % (args[0], | |
|
251 | obj.__class__.__name__, fnam) | |
|
252 | ||
|
253 | ||
|
254 | if not isinstance (obj,basestring): | |
|
255 | from pprint import pprint | |
|
256 | pprint(obj,fil) | |
|
257 | else: | |
|
258 | fil.write(obj) | |
|
259 | if not obj.endswith('\n'): | |
|
260 | fil.write('\n') | |
|
261 | ||
|
262 | fil.close() | |
|
263 | return | |
|
264 | ||
|
265 | # %note foo | |
|
266 | try: | |
|
267 | obj = ip.user_ns[args[0]] | |
|
268 | except KeyError: | |
|
269 | # this should not be alias, for aliases, use %store | |
|
270 | ||
|
271 | print "Error: %s doesn't exist." % args[0] | |
|
272 | ||
|
273 | print "Use %note -r <var> to retrieve variables. This should not be used " +\ | |
|
274 | "to store alias, for saving aliases, use %store" | |
|
275 | return | |
|
276 | else: | |
|
277 | if isinstance(inspect.getmodule(obj), FakeModule): | |
|
278 | print textwrap.dedent("""\ | |
|
279 | Warning:%s is %s | |
|
280 | Proper storage of interactively declared classes (or instances | |
|
281 | of those classes) is not possible! Only instances | |
|
282 | of classes in real modules on file system can be %%store'd. | |
|
283 | """ % (args[0], obj) ) | |
|
284 | return | |
|
285 | #pickled = pickle.dumps(obj) | |
|
286 | #self.db[ 'jot/' + args[0] ] = obj | |
|
287 | jot_obj(self, obj, args[0]) | |
|
288 | ||
|
289 | ||
|
290 | def magic_read(self, parameter_s=''): | |
|
291 | """ | |
|
292 | %read <var> - Load variable from data that is jotted down.\\ | |
|
293 | ||
|
294 | """ | |
|
295 | ||
|
296 | opts,argsl = self.parse_options(parameter_s,'drzl',mode='string') | |
|
297 | args = argsl.split(None,1) | |
|
298 | ip = self.getapi() | |
|
299 | db = ip.db | |
|
300 | #if opts.has_key('r'): | |
|
301 | try: | |
|
302 | toret = args[0] | |
|
303 | except: | |
|
304 | print "which record do you want to read out?" | |
|
305 | return | |
|
306 | else: | |
|
307 | return read_variables(ip, toret) | |
|
308 | ||
|
309 | ||
|
310 | ip.expose_magic('jot',magic_jot) | |
|
311 | ip.expose_magic('read',magic_read) |
@@ -0,0 +1,234 b'' | |||
|
1 | """ | |
|
2 | IPython extension: %lookfor command for searching docstrings | |
|
3 | ||
|
4 | """ | |
|
5 | # Pauli Virtanen <pav@iki.fi>, 2008. | |
|
6 | ||
|
7 | import re, inspect, pkgutil, pydoc | |
|
8 | ||
|
9 | #------------------------------------------------------------------------------ | |
|
10 | # Lookfor functionality | |
|
11 | #------------------------------------------------------------------------------ | |
|
12 | ||
|
13 | # Cache for lookfor: {id(module): {name: (docstring, kind, index), ...}...} | |
|
14 | # where kind: "func", "class", "module", "object" | |
|
15 | # and index: index in breadth-first namespace traversal | |
|
16 | _lookfor_caches = {} | |
|
17 | ||
|
18 | # regexp whose match indicates that the string may contain a function signature | |
|
19 | _function_signature_re = re.compile(r"[a-z_]+\(.*[,=].*\)", re.I) | |
|
20 | ||
|
21 | def lookfor(what, modules=None, import_modules=True, regenerate=False): | |
|
22 | """ | |
|
23 | Search for objects whose documentation contains all given words. | |
|
24 | Shows a summary of matching objects, sorted roughly by relevance. | |
|
25 | ||
|
26 | Parameters | |
|
27 | ---------- | |
|
28 | what : str | |
|
29 | String containing words to look for. | |
|
30 | ||
|
31 | module : str, module | |
|
32 | Module whose docstrings to go through. | |
|
33 | import_modules : bool | |
|
34 | Whether to import sub-modules in packages. | |
|
35 | Will import only modules in __all__ | |
|
36 | regenerate: bool | |
|
37 | Re-generate the docstring cache | |
|
38 | ||
|
39 | """ | |
|
40 | # Cache | |
|
41 | cache = {} | |
|
42 | for module in modules: | |
|
43 | try: | |
|
44 | c = _lookfor_generate_cache(module, import_modules, regenerate) | |
|
45 | cache.update(c) | |
|
46 | except ImportError: | |
|
47 | pass | |
|
48 | ||
|
49 | # Search | |
|
50 | # XXX: maybe using a real stemming search engine would be better? | |
|
51 | found = [] | |
|
52 | whats = str(what).lower().split() | |
|
53 | if not whats: return | |
|
54 | ||
|
55 | for name, (docstring, kind, index) in cache.iteritems(): | |
|
56 | if kind in ('module', 'object'): | |
|
57 | # don't show modules or objects | |
|
58 | continue | |
|
59 | ok = True | |
|
60 | doc = docstring.lower() | |
|
61 | for w in whats: | |
|
62 | if w not in doc: | |
|
63 | ok = False | |
|
64 | break | |
|
65 | if ok: | |
|
66 | found.append(name) | |
|
67 | ||
|
68 | # Relevance sort | |
|
69 | # XXX: this is full Harrison-Stetson heuristics now, | |
|
70 | # XXX: it probably could be improved | |
|
71 | ||
|
72 | kind_relevance = {'func': 1000, 'class': 1000, | |
|
73 | 'module': -1000, 'object': -1000} | |
|
74 | ||
|
75 | def relevance(name, docstr, kind, index): | |
|
76 | r = 0 | |
|
77 | # do the keywords occur within the start of the docstring? | |
|
78 | first_doc = "\n".join(docstr.lower().strip().split("\n")[:3]) | |
|
79 | r += sum([200 for w in whats if w in first_doc]) | |
|
80 | # do the keywords occur in the function name? | |
|
81 | r += sum([30 for w in whats if w in name]) | |
|
82 | # is the full name long? | |
|
83 | r += -len(name) * 5 | |
|
84 | # is the object of bad type? | |
|
85 | r += kind_relevance.get(kind, -1000) | |
|
86 | # is the object deep in namespace hierarchy? | |
|
87 | r += -name.count('.') * 10 | |
|
88 | r += max(-index / 100, -100) | |
|
89 | return r | |
|
90 | ||
|
91 | def relevance_sort(a, b): | |
|
92 | dr = relevance(b, *cache[b]) - relevance(a, *cache[a]) | |
|
93 | if dr != 0: return dr | |
|
94 | else: return cmp(a, b) | |
|
95 | found.sort(relevance_sort) | |
|
96 | ||
|
97 | # Pretty-print | |
|
98 | s = "Search results for '%s'" % (' '.join(whats)) | |
|
99 | help_text = [s, "-"*len(s)] | |
|
100 | for name in found: | |
|
101 | doc, kind, ix = cache[name] | |
|
102 | ||
|
103 | doclines = [line.strip() for line in doc.strip().split("\n") | |
|
104 | if line.strip()] | |
|
105 | ||
|
106 | # find a suitable short description | |
|
107 | try: | |
|
108 | first_doc = doclines[0].strip() | |
|
109 | if _function_signature_re.search(first_doc): | |
|
110 | first_doc = doclines[1].strip() | |
|
111 | except IndexError: | |
|
112 | first_doc = "" | |
|
113 | help_text.append("%s\n %s" % (name, first_doc)) | |
|
114 | ||
|
115 | # Output | |
|
116 | if len(help_text) > 10: | |
|
117 | pager = pydoc.getpager() | |
|
118 | pager("\n".join(help_text)) | |
|
119 | else: | |
|
120 | print "\n".join(help_text) | |
|
121 | ||
|
122 | def _lookfor_generate_cache(module, import_modules, regenerate): | |
|
123 | """ | |
|
124 | Generate docstring cache for given module. | |
|
125 | ||
|
126 | Parameters | |
|
127 | ---------- | |
|
128 | module : str, None, module | |
|
129 | Module for which to generate docstring cache | |
|
130 | import_modules : bool | |
|
131 | Whether to import sub-modules in packages. | |
|
132 | Will import only modules in __all__ | |
|
133 | regenerate: bool | |
|
134 | Re-generate the docstring cache | |
|
135 | ||
|
136 | Returns | |
|
137 | ------- | |
|
138 | cache : dict {obj_full_name: (docstring, kind, index), ...} | |
|
139 | Docstring cache for the module, either cached one (regenerate=False) | |
|
140 | or newly generated. | |
|
141 | ||
|
142 | """ | |
|
143 | global _lookfor_caches | |
|
144 | ||
|
145 | if module is None: | |
|
146 | module = "numpy" | |
|
147 | ||
|
148 | if isinstance(module, str): | |
|
149 | module = __import__(module) | |
|
150 | ||
|
151 | if id(module) in _lookfor_caches and not regenerate: | |
|
152 | return _lookfor_caches[id(module)] | |
|
153 | ||
|
154 | # walk items and collect docstrings | |
|
155 | cache = {} | |
|
156 | _lookfor_caches[id(module)] = cache | |
|
157 | seen = {} | |
|
158 | index = 0 | |
|
159 | stack = [(module.__name__, module)] | |
|
160 | while stack: | |
|
161 | name, item = stack.pop(0) | |
|
162 | if id(item) in seen: continue | |
|
163 | seen[id(item)] = True | |
|
164 | ||
|
165 | index += 1 | |
|
166 | kind = "object" | |
|
167 | ||
|
168 | if inspect.ismodule(item): | |
|
169 | kind = "module" | |
|
170 | try: | |
|
171 | _all = item.__all__ | |
|
172 | except AttributeError: | |
|
173 | _all = None | |
|
174 | # import sub-packages | |
|
175 | if import_modules and hasattr(item, '__path__'): | |
|
176 | for m in pkgutil.iter_modules(item.__path__): | |
|
177 | if _all is not None and m[1] not in _all: | |
|
178 | continue | |
|
179 | try: | |
|
180 | __import__("%s.%s" % (name, m[1])) | |
|
181 | except ImportError: | |
|
182 | continue | |
|
183 | for n, v in inspect.getmembers(item): | |
|
184 | if _all is not None and n not in _all: | |
|
185 | continue | |
|
186 | stack.append(("%s.%s" % (name, n), v)) | |
|
187 | elif inspect.isclass(item): | |
|
188 | kind = "class" | |
|
189 | for n, v in inspect.getmembers(item): | |
|
190 | stack.append(("%s.%s" % (name, n), v)) | |
|
191 | elif callable(item): | |
|
192 | kind = "func" | |
|
193 | ||
|
194 | doc = inspect.getdoc(item) | |
|
195 | if doc is not None: | |
|
196 | cache[name] = (doc, kind, index) | |
|
197 | ||
|
198 | return cache | |
|
199 | ||
|
200 | #------------------------------------------------------------------------------ | |
|
201 | # IPython connectivity | |
|
202 | #------------------------------------------------------------------------------ | |
|
203 | ||
|
204 | import IPython.ipapi | |
|
205 | ip = IPython.ipapi.get() | |
|
206 | ||
|
207 | _lookfor_modules = ['numpy', 'scipy'] | |
|
208 | ||
|
209 | def lookfor_f(self, arg=''): | |
|
210 | r""" | |
|
211 | Search for objects whose documentation contains all given words. | |
|
212 | Shows a summary of matching objects, sorted roughly by relevance. | |
|
213 | ||
|
214 | Usage | |
|
215 | ----- | |
|
216 | %lookfor +numpy some words | |
|
217 | Search module 'numpy' | |
|
218 | ||
|
219 | %lookfor_modules numpy scipy | |
|
220 | Set default modules whose docstrings to search | |
|
221 | ||
|
222 | """ | |
|
223 | lookfor(arg, modules=_lookfor_modules) | |
|
224 | ||
|
225 | def lookfor_modules_f(self, arg=''): | |
|
226 | global _lookfor_modules | |
|
227 | if not arg: | |
|
228 | print "Modules included in %lookfor search:", _lookfor_modules | |
|
229 | else: | |
|
230 | _lookfor_modules = arg.split() | |
|
231 | ||
|
232 | ip.expose_magic('lookfor', lookfor_f) | |
|
233 | ip.expose_magic('lookfor_modules', lookfor_modules_f) | |
|
234 |
@@ -0,0 +1,6 b'' | |||
|
1 | completion=IPYTHON | |
|
2 | background_color=BLACK | |
|
3 | filter_empty=True | |
|
4 | filter_magic=True | |
|
5 | filter_doc=True | |
|
6 | filter_cmd=True |
@@ -0,0 +1,1 b'' | |||
|
1 | doc/ipython.el usr/share/emacs/site-lisp |
@@ -0,0 +1,52 b'' | |||
|
1 | .TH IRUNNER 1 "April 24, 2007" "" "" | |
|
2 | .SH NAME | |
|
3 | \fBirunner \- interactive runner interface | |
|
4 | .SH SYNOPSIS | |
|
5 | .nf | |
|
6 | .fam C | |
|
7 | \fBirunner\fP [\fIoptions\fP] \fIfile_to_run\fP | |
|
8 | .fam T | |
|
9 | .fi | |
|
10 | .SH DESCRIPTION | |
|
11 | irunner is an interface to the various interactive runners | |
|
12 | available in IPython's \fBirunner\fP module. | |
|
13 | .PP | |
|
14 | The already implemented runners are listed below; adding | |
|
15 | one for a new program is a trivial task, see the source | |
|
16 | for examples. | |
|
17 | .SH OPTIONS | |
|
18 | .TP | |
|
19 | .B | |
|
20 | \-h, \-\-help | |
|
21 | show this help message and exit | |
|
22 | .TP | |
|
23 | .B | |
|
24 | \-\-ipython | |
|
25 | IPython interactive runner (default). | |
|
26 | .TP | |
|
27 | .B | |
|
28 | \-\-python | |
|
29 | Python interactive runner. | |
|
30 | .TP | |
|
31 | .B | |
|
32 | \-\-sage | |
|
33 | SAGE interactive runner. | |
|
34 | .SH EXAMPLE | |
|
35 | irunner.py \-\-python \-\- \-\-help | |
|
36 | will pass \-\-help to the python runner. | |
|
37 | Similarly, | |
|
38 | irunner.py \-\-ipython \-\- \-\-interact script.ipy | |
|
39 | .SH SEE ALSO | |
|
40 | .BR ipython(1) | |
|
41 | .br | |
|
42 | .SH BUGS | |
|
43 | The SAGE runner only works if you manually configure your SAGE | |
|
44 | copy to use 'colors NoColor' in the ipythonrc config file, since | |
|
45 | currently the prompt matching regexp does not identify color sequences. | |
|
46 | .SH AUTHOR | |
|
47 | \fBirunner\fP is an extension of Ken Schutte <kschutte-AT-csail.mit.edu>'s | |
|
48 | script contributed on the ipython-user list: | |
|
49 | http://scipy.net/pipermail/ipython-user/2006-May/001705.html | |
|
50 | .PP | |
|
51 | This manual page was written by Bernd Zeimetz <bernd@bzed.de>, | |
|
52 | for the Debian project (but may be used by others). |
@@ -0,0 +1,1 b'' | |||
|
1 | debian/irunner.1 |
@@ -0,0 +1,1 b'' | |||
|
1 | 2 |
@@ -1,365 +1,364 b'' | |||
|
1 | #!/usr/bin/env python | |
|
2 | 1 |
|
|
3 | 2 | """ Implementations for various useful completers |
|
4 | 3 | |
|
5 | 4 | See Extensions/ipy_stock_completers.py on examples of how to enable a completer, |
|
6 | 5 | but the basic idea is to do: |
|
7 | 6 | |
|
8 | 7 | ip.set_hook('complete_command', svn_completer, str_key = 'svn') |
|
9 | 8 | |
|
10 | 9 | """ |
|
11 | 10 | import IPython.ipapi |
|
12 | 11 | import glob,os,shlex,sys |
|
13 | 12 | import inspect |
|
14 | 13 | from time import time |
|
15 | 14 | from zipimport import zipimporter |
|
16 | 15 | ip = IPython.ipapi.get() |
|
17 | 16 | |
|
18 | 17 | try: |
|
19 | 18 | set |
|
20 | 19 | except: |
|
21 | 20 | from sets import Set as set |
|
22 | 21 | |
|
23 | 22 | TIMEOUT_STORAGE = 3 #Time in seconds after which the rootmodules will be stored |
|
24 | 23 | TIMEOUT_GIVEUP = 20 #Time in seconds after which we give up |
|
25 | 24 | |
|
26 | 25 | def quick_completer(cmd, completions): |
|
27 | 26 | """ Easily create a trivial completer for a command. |
|
28 | 27 | |
|
29 | 28 | Takes either a list of completions, or all completions in string |
|
30 | 29 | (that will be split on whitespace) |
|
31 | 30 | |
|
32 | 31 | Example:: |
|
33 | 32 | |
|
34 | 33 | [d:\ipython]|1> import ipy_completers |
|
35 | 34 | [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz']) |
|
36 | 35 | [d:\ipython]|3> foo b<TAB> |
|
37 | 36 | bar baz |
|
38 | 37 | [d:\ipython]|3> foo ba |
|
39 | 38 | """ |
|
40 | 39 | if isinstance(completions, basestring): |
|
41 | 40 | |
|
42 | 41 | completions = completions.split() |
|
43 | 42 | def do_complete(self,event): |
|
44 | 43 | return completions |
|
45 | 44 | |
|
46 | 45 | ip.set_hook('complete_command',do_complete, str_key = cmd) |
|
47 | 46 | |
|
48 | 47 | def getRootModules(): |
|
49 | 48 | """ |
|
50 | 49 | Returns a list containing the names of all the modules available in the |
|
51 | 50 | folders of the pythonpath. |
|
52 | 51 | """ |
|
53 | 52 | modules = [] |
|
54 | 53 | if ip.db.has_key('rootmodules'): |
|
55 | 54 | return ip.db['rootmodules'] |
|
56 | 55 | t = time() |
|
57 | 56 | store = False |
|
58 | 57 | for path in sys.path: |
|
59 | 58 | modules += moduleList(path) |
|
60 | 59 | if time() - t >= TIMEOUT_STORAGE and not store: |
|
61 | 60 | store = True |
|
62 | 61 | print "\nCaching the list of root modules, please wait!" |
|
63 | 62 | print "(This will only be done once - type '%rehashx' to " + \ |
|
64 | 63 | "reset cache!)" |
|
65 | 64 | |
|
66 | 65 | if time() - t > TIMEOUT_GIVEUP: |
|
67 | 66 | print "This is taking too long, we give up." |
|
68 | 67 | |
|
69 | 68 | ip.db['rootmodules'] = [] |
|
70 | 69 | return [] |
|
71 | 70 | |
|
72 | 71 | modules += sys.builtin_module_names |
|
73 | 72 | |
|
74 | 73 | modules = list(set(modules)) |
|
75 | 74 | if '__init__' in modules: |
|
76 | 75 | modules.remove('__init__') |
|
77 | 76 | modules = list(set(modules)) |
|
78 | 77 | if store: |
|
79 | 78 | ip.db['rootmodules'] = modules |
|
80 | 79 | return modules |
|
81 | 80 | |
|
82 | 81 | def moduleList(path): |
|
83 | 82 | """ |
|
84 | 83 | Return the list containing the names of the modules available in the given |
|
85 | 84 | folder. |
|
86 | 85 | """ |
|
87 | 86 | |
|
88 | 87 | if os.path.isdir(path): |
|
89 | 88 | folder_list = os.listdir(path) |
|
90 | 89 | elif path.endswith('.egg'): |
|
91 | 90 | try: |
|
92 | 91 | folder_list = [f for f in zipimporter(path)._files] |
|
93 | 92 | except: |
|
94 | 93 | folder_list = [] |
|
95 | 94 | else: |
|
96 | 95 | folder_list = [] |
|
97 | 96 | #folder_list = glob.glob(os.path.join(path,'*')) |
|
98 | 97 | folder_list = [p for p in folder_list \ |
|
99 | 98 | if os.path.exists(os.path.join(path, p,'__init__.py'))\ |
|
100 | 99 | or p[-3:] in ('.py','.so')\ |
|
101 | 100 | or p[-4:] in ('.pyc','.pyo','.pyd')] |
|
102 | 101 | |
|
103 | 102 | folder_list = [os.path.basename(p).split('.')[0] for p in folder_list] |
|
104 | 103 | return folder_list |
|
105 | 104 | |
|
106 | 105 | def moduleCompletion(line): |
|
107 | 106 | """ |
|
108 | 107 | Returns a list containing the completion possibilities for an import line. |
|
109 | 108 | The line looks like this : |
|
110 | 109 | 'import xml.d' |
|
111 | 110 | 'from xml.dom import' |
|
112 | 111 | """ |
|
113 | 112 | def tryImport(mod, only_modules=False): |
|
114 | 113 | def isImportable(module, attr): |
|
115 | 114 | if only_modules: |
|
116 | 115 | return inspect.ismodule(getattr(module, attr)) |
|
117 | 116 | else: |
|
118 | 117 | return not(attr[:2] == '__' and attr[-2:] == '__') |
|
119 | 118 | try: |
|
120 | 119 | m = __import__(mod) |
|
121 | 120 | except: |
|
122 | 121 | return [] |
|
123 | 122 | mods = mod.split('.') |
|
124 | 123 | for module in mods[1:]: |
|
125 | 124 | m = getattr(m,module) |
|
126 | 125 | if (not hasattr(m, '__file__')) or (not only_modules) or\ |
|
127 | 126 | (hasattr(m, '__file__') and '__init__' in m.__file__): |
|
128 | 127 | completion_list = [attr for attr in dir(m) if isImportable(m, attr)] |
|
129 | 128 | completion_list.extend(getattr(m,'__all__',[])) |
|
130 | 129 | if hasattr(m, '__file__') and '__init__' in m.__file__: |
|
131 | 130 | completion_list.extend(moduleList(os.path.dirname(m.__file__))) |
|
132 | 131 | completion_list = list(set(completion_list)) |
|
133 | 132 | if '__init__' in completion_list: |
|
134 | 133 | completion_list.remove('__init__') |
|
135 | 134 | return completion_list |
|
136 | 135 | |
|
137 | 136 | words = line.split(' ') |
|
138 | 137 | if len(words) == 3 and words[0] == 'from': |
|
139 | 138 | return ['import '] |
|
140 | 139 | if len(words) < 3 and (words[0] in ['import','from']) : |
|
141 | 140 | if len(words) == 1: |
|
142 | 141 | return getRootModules() |
|
143 | 142 | mod = words[1].split('.') |
|
144 | 143 | if len(mod) < 2: |
|
145 | 144 | return getRootModules() |
|
146 | 145 | completion_list = tryImport('.'.join(mod[:-1]), True) |
|
147 | 146 | completion_list = ['.'.join(mod[:-1] + [el]) for el in completion_list] |
|
148 | 147 | return completion_list |
|
149 | 148 | if len(words) >= 3 and words[0] == 'from': |
|
150 | 149 | mod = words[1] |
|
151 | 150 | return tryImport(mod) |
|
152 | 151 | |
|
153 | 152 | def vcs_completer(commands, event): |
|
154 | 153 | """ utility to make writing typical version control app completers easier |
|
155 | 154 | |
|
156 | 155 | VCS command line apps typically have the format: |
|
157 | 156 | |
|
158 | 157 | [sudo ]PROGNAME [help] [command] file file... |
|
159 | 158 | |
|
160 | 159 | """ |
|
161 | 160 | |
|
162 | 161 | |
|
163 | 162 | cmd_param = event.line.split() |
|
164 | 163 | if event.line.endswith(' '): |
|
165 | 164 | cmd_param.append('') |
|
166 | 165 | |
|
167 | 166 | if cmd_param[0] == 'sudo': |
|
168 | 167 | cmd_param = cmd_param[1:] |
|
169 | 168 | |
|
170 | 169 | if len(cmd_param) == 2 or 'help' in cmd_param: |
|
171 | 170 | return commands.split() |
|
172 | 171 | |
|
173 | 172 | return ip.IP.Completer.file_matches(event.symbol) |
|
174 | 173 | |
|
175 | 174 | |
|
176 | 175 | pkg_cache = None |
|
177 | 176 | |
|
178 | 177 | def module_completer(self,event): |
|
179 | 178 | """ Give completions after user has typed 'import ...' or 'from ...'""" |
|
180 | 179 | |
|
181 | 180 | # This works in all versions of python. While 2.5 has |
|
182 | 181 | # pkgutil.walk_packages(), that particular routine is fairly dangerous, |
|
183 | 182 | # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full |
|
184 | 183 | # of possibly problematic side effects. |
|
185 | 184 | # This search the folders in the sys.path for available modules. |
|
186 | 185 | |
|
187 | 186 | return moduleCompletion(event.line) |
|
188 | 187 | |
|
189 | 188 | |
|
190 | 189 | svn_commands = """\ |
|
191 | 190 | add blame praise annotate ann cat checkout co cleanup commit ci copy |
|
192 | 191 | cp delete del remove rm diff di export help ? h import info list ls |
|
193 | 192 | lock log merge mkdir move mv rename ren propdel pdel pd propedit pedit |
|
194 | 193 | pe propget pget pg proplist plist pl propset pset ps resolved revert |
|
195 | 194 | status stat st switch sw unlock update |
|
196 | 195 | """ |
|
197 | 196 | |
|
198 | 197 | def svn_completer(self,event): |
|
199 | 198 | return vcs_completer(svn_commands, event) |
|
200 | 199 | |
|
201 | 200 | |
|
202 | 201 | hg_commands = """ |
|
203 | 202 | add addremove annotate archive backout branch branches bundle cat |
|
204 | 203 | clone commit copy diff export grep heads help identify import incoming |
|
205 | 204 | init locate log manifest merge outgoing parents paths pull push |
|
206 | 205 | qapplied qclone qcommit qdelete qdiff qfold qguard qheader qimport |
|
207 | 206 | qinit qnew qnext qpop qprev qpush qrefresh qrename qrestore qsave |
|
208 | 207 | qselect qseries qtop qunapplied recover remove rename revert rollback |
|
209 | 208 | root serve showconfig status strip tag tags tip unbundle update verify |
|
210 | 209 | version |
|
211 | 210 | """ |
|
212 | 211 | |
|
213 | 212 | def hg_completer(self,event): |
|
214 | 213 | """ Completer for mercurial commands """ |
|
215 | 214 | |
|
216 | 215 | return vcs_completer(hg_commands, event) |
|
217 | 216 | |
|
218 | 217 | |
|
219 | 218 | |
|
220 | 219 | __bzr_commands = None |
|
221 | 220 | |
|
222 | 221 | def bzr_commands(): |
|
223 | 222 | global __bzr_commands |
|
224 | 223 | if __bzr_commands is not None: |
|
225 | 224 | return __bzr_commands |
|
226 | 225 | out = os.popen('bzr help commands') |
|
227 | 226 | __bzr_commands = [l.split()[0] for l in out] |
|
228 | 227 | return __bzr_commands |
|
229 | 228 | |
|
230 | 229 | def bzr_completer(self,event): |
|
231 | 230 | """ Completer for bazaar commands """ |
|
232 | 231 | cmd_param = event.line.split() |
|
233 | 232 | if event.line.endswith(' '): |
|
234 | 233 | cmd_param.append('') |
|
235 | 234 | |
|
236 | 235 | if len(cmd_param) > 2: |
|
237 | 236 | cmd = cmd_param[1] |
|
238 | 237 | param = cmd_param[-1] |
|
239 | 238 | output_file = (param == '--output=') |
|
240 | 239 | if cmd == 'help': |
|
241 | 240 | return bzr_commands() |
|
242 | 241 | elif cmd in ['bundle-revisions','conflicts', |
|
243 | 242 | 'deleted','nick','register-branch', |
|
244 | 243 | 'serve','unbind','upgrade','version', |
|
245 | 244 | 'whoami'] and not output_file: |
|
246 | 245 | return [] |
|
247 | 246 | else: |
|
248 | 247 | # the rest are probably file names |
|
249 | 248 | return ip.IP.Completer.file_matches(event.symbol) |
|
250 | 249 | |
|
251 | 250 | return bzr_commands() |
|
252 | 251 | |
|
253 | 252 | |
|
254 | 253 | def shlex_split(x): |
|
255 | 254 | """Helper function to split lines into segments.""" |
|
256 | 255 | #shlex.split raise exception if syntax error in sh syntax |
|
257 | 256 | #for example if no closing " is found. This function keeps dropping |
|
258 | 257 | #the last character of the line until shlex.split does not raise |
|
259 | 258 | #exception. Adds end of the line to the result of shlex.split |
|
260 | 259 | #example: %run "c:/python -> ['%run','"c:/python'] |
|
261 | 260 | endofline=[] |
|
262 | 261 | while x!="": |
|
263 | 262 | try: |
|
264 | 263 | comps=shlex.split(x) |
|
265 | 264 | if len(endofline)>=1: |
|
266 | 265 | comps.append("".join(endofline)) |
|
267 | 266 | return comps |
|
268 | 267 | except ValueError: |
|
269 | 268 | endofline=[x[-1:]]+endofline |
|
270 | 269 | x=x[:-1] |
|
271 | 270 | return ["".join(endofline)] |
|
272 | 271 | |
|
273 | 272 | def runlistpy(self, event): |
|
274 | 273 | comps = shlex_split(event.line) |
|
275 | 274 | relpath = (len(comps) > 1 and comps[-1] or '').strip("'\"") |
|
276 | 275 | |
|
277 | 276 | #print "\nev=",event # dbg |
|
278 | 277 | #print "rp=",relpath # dbg |
|
279 | 278 | #print 'comps=',comps # dbg |
|
280 | 279 | |
|
281 | 280 | lglob = glob.glob |
|
282 | 281 | isdir = os.path.isdir |
|
283 | 282 | if relpath.startswith('~'): |
|
284 | 283 | relpath = os.path.expanduser(relpath) |
|
285 | 284 | dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*') |
|
286 | 285 | if isdir(f)] |
|
287 | 286 | |
|
288 | 287 | # Find if the user has already typed the first filename, after which we |
|
289 | 288 | # should complete on all files, since after the first one other files may |
|
290 | 289 | # be arguments to the input script. |
|
291 | 290 | #filter( |
|
292 | 291 | if filter(lambda f: f.endswith('.py') or f.endswith('.ipy') or |
|
293 | 292 | f.endswith('.pyw'),comps): |
|
294 | 293 | pys = [f.replace('\\','/') for f in lglob('*')] |
|
295 | 294 | else: |
|
296 | 295 | pys = [f.replace('\\','/') |
|
297 | 296 | for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') + |
|
298 | 297 | lglob(relpath + '*.pyw')] |
|
299 | 298 | return dirs + pys |
|
300 | 299 | |
|
301 | 300 | |
|
302 | 301 | def cd_completer(self, event): |
|
303 | 302 | relpath = event.symbol |
|
304 | 303 | #print event # dbg |
|
305 | 304 | if '-b' in event.line: |
|
306 | 305 | # return only bookmark completions |
|
307 | 306 | bkms = self.db.get('bookmarks',{}) |
|
308 | 307 | return bkms.keys() |
|
309 | 308 | |
|
310 | 309 | |
|
311 | 310 | if event.symbol == '-': |
|
312 | 311 | width_dh = str(len(str(len(ip.user_ns['_dh']) + 1))) |
|
313 | 312 | # jump in directory history by number |
|
314 | 313 | fmt = '-%0' + width_dh +'d [%s]' |
|
315 | 314 | ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['_dh'])] |
|
316 | 315 | if len(ents) > 1: |
|
317 | 316 | return ents |
|
318 | 317 | return [] |
|
319 | 318 | |
|
320 | 319 | if relpath.startswith('~'): |
|
321 | 320 | relpath = os.path.expanduser(relpath).replace('\\','/') |
|
322 | 321 | found = [] |
|
323 | 322 | for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*') |
|
324 | 323 | if os.path.isdir(f)]: |
|
325 | 324 | if ' ' in d: |
|
326 | 325 | # we don't want to deal with any of that, complex code |
|
327 | 326 | # for this is elsewhere |
|
328 | 327 | raise IPython.ipapi.TryNext |
|
329 | 328 | found.append( d ) |
|
330 | 329 | |
|
331 | 330 | if not found: |
|
332 | 331 | if os.path.isdir(relpath): |
|
333 | 332 | return [relpath] |
|
334 | 333 | raise IPython.ipapi.TryNext |
|
335 | 334 | return found |
|
336 | 335 | |
|
337 | 336 | def apt_get_packages(prefix): |
|
338 | 337 | out = os.popen('apt-cache pkgnames') |
|
339 | 338 | for p in out: |
|
340 | 339 | if p.startswith(prefix): |
|
341 | 340 | yield p.rstrip() |
|
342 | 341 | |
|
343 | 342 | |
|
344 | 343 | apt_commands = """\ |
|
345 | 344 | update upgrade install remove purge source build-dep dist-upgrade |
|
346 | 345 | dselect-upgrade clean autoclean check""" |
|
347 | 346 | |
|
348 | 347 | def apt_completer(self, event): |
|
349 | 348 | """ Completer for apt-get (uses apt-cache internally) |
|
350 | 349 | |
|
351 | 350 | """ |
|
352 | 351 | |
|
353 | 352 | |
|
354 | 353 | cmd_param = event.line.split() |
|
355 | 354 | if event.line.endswith(' '): |
|
356 | 355 | cmd_param.append('') |
|
357 | 356 | |
|
358 | 357 | if cmd_param[0] == 'sudo': |
|
359 | 358 | cmd_param = cmd_param[1:] |
|
360 | 359 | |
|
361 | 360 | if len(cmd_param) == 2 or 'help' in cmd_param: |
|
362 | 361 | return apt_commands.split() |
|
363 | 362 | |
|
364 | 363 | return list(apt_get_packages(event.symbol)) |
|
365 | 364 |
@@ -1,585 +1,592 b'' | |||
|
1 | 1 | """ ILeo - Leo plugin for IPython |
|
2 | 2 | |
|
3 | 3 | |
|
4 | 4 | """ |
|
5 | 5 | import IPython.ipapi |
|
6 | 6 | import IPython.genutils |
|
7 | 7 | import IPython.generics |
|
8 | 8 | from IPython.hooks import CommandChainDispatcher |
|
9 | 9 | import re |
|
10 | 10 | import UserDict |
|
11 | 11 | from IPython.ipapi import TryNext |
|
12 | 12 | import IPython.macro |
|
13 | 13 | import IPython.Shell |
|
14 | 14 | |
|
15 | 15 | def init_ipython(ipy): |
|
16 | 16 | """ This will be run by _ip.load('ipy_leo') |
|
17 | 17 | |
|
18 | 18 | Leo still needs to run update_commander() after this. |
|
19 | 19 | |
|
20 | 20 | """ |
|
21 | 21 | global ip |
|
22 | 22 | ip = ipy |
|
23 | 23 | IPython.Shell.hijack_tk() |
|
24 | 24 | ip.set_hook('complete_command', mb_completer, str_key = '%mb') |
|
25 | 25 | ip.expose_magic('mb',mb_f) |
|
26 | 26 | ip.expose_magic('lee',lee_f) |
|
27 | 27 | ip.expose_magic('leoref',leoref_f) |
|
28 | 28 | expose_ileo_push(push_cl_node,100) |
|
29 | 29 | # this should be the LAST one that will be executed, and it will never raise TryNext |
|
30 | 30 | expose_ileo_push(push_ipython_script, 1000) |
|
31 | 31 | expose_ileo_push(push_plain_python, 100) |
|
32 | 32 | expose_ileo_push(push_ev_node, 100) |
|
33 | 33 | global wb |
|
34 | 34 | wb = LeoWorkbook() |
|
35 | 35 | ip.user_ns['wb'] = wb |
|
36 | 36 | |
|
37 | 37 | show_welcome() |
|
38 | 38 | |
|
39 | 39 | |
|
40 | 40 | def update_commander(new_leox): |
|
41 | 41 | """ Set the Leo commander to use |
|
42 | 42 | |
|
43 | 43 | This will be run every time Leo does ipython-launch; basically, |
|
44 | 44 | when the user switches the document he is focusing on, he should do |
|
45 | 45 | ipython-launch to tell ILeo what document the commands apply to. |
|
46 | 46 | |
|
47 | 47 | """ |
|
48 | 48 | |
|
49 | 49 | global c,g |
|
50 | 50 | c,g = new_leox.c, new_leox.g |
|
51 | 51 | print "Set Leo Commander:",c.frame.getTitle() |
|
52 | 52 | |
|
53 | 53 | # will probably be overwritten by user, but handy for experimentation early on |
|
54 | 54 | ip.user_ns['c'] = c |
|
55 | 55 | ip.user_ns['g'] = g |
|
56 | 56 | ip.user_ns['_leo'] = new_leox |
|
57 | 57 | |
|
58 | 58 | new_leox.push = push_position_from_leo |
|
59 | 59 | run_leo_startup_node() |
|
60 | 60 | |
|
61 | 61 | from IPython.external.simplegeneric import generic |
|
62 | 62 | import pprint |
|
63 | 63 | |
|
64 | 64 | def es(s): |
|
65 | 65 | g.es(s, tabName = 'IPython') |
|
66 | 66 | pass |
|
67 | 67 | |
|
68 | 68 | @generic |
|
69 | 69 | def format_for_leo(obj): |
|
70 | 70 | """ Convert obj to string representiation (for editing in Leo)""" |
|
71 | 71 | return pprint.pformat(obj) |
|
72 | 72 | |
|
73 | 73 | @format_for_leo.when_type(list) |
|
74 | 74 | def format_list(obj): |
|
75 | 75 | return "\n".join(str(s) for s in obj) |
|
76 | 76 | |
|
77 | 77 | |
|
78 | 78 | attribute_re = re.compile('^[a-zA-Z_][a-zA-Z0-9_]*$') |
|
79 | 79 | def valid_attribute(s): |
|
80 | 80 | return attribute_re.match(s) |
|
81 | 81 | |
|
82 | 82 | _rootnode = None |
|
83 | 83 | def rootnode(): |
|
84 | 84 | """ Get ileo root node (@ipy-root) |
|
85 | 85 | |
|
86 | 86 | if node has become invalid or has not been set, return None |
|
87 | 87 | |
|
88 | 88 | Note that the root is the *first* @ipy-root item found |
|
89 | 89 | """ |
|
90 | 90 | global _rootnode |
|
91 | 91 | if _rootnode is None: |
|
92 | 92 | return None |
|
93 | 93 | if c.positionExists(_rootnode.p): |
|
94 | 94 | return _rootnode |
|
95 | 95 | _rootnode = None |
|
96 | 96 | return None |
|
97 | 97 | |
|
98 | 98 | def all_cells(): |
|
99 | 99 | global _rootnode |
|
100 | 100 | d = {} |
|
101 | 101 | r = rootnode() |
|
102 | 102 | if r is not None: |
|
103 | 103 | nodes = r.p.children_iter() |
|
104 | 104 | else: |
|
105 | 105 | nodes = c.allNodes_iter() |
|
106 | 106 | |
|
107 | 107 | for p in nodes: |
|
108 | 108 | h = p.headString() |
|
109 | 109 | if h.strip() == '@ipy-root': |
|
110 | 110 | # update root node (found it for the first time) |
|
111 | 111 | _rootnode = LeoNode(p) |
|
112 | 112 | # the next recursive call will use the children of new root |
|
113 | 113 | return all_cells() |
|
114 | 114 | |
|
115 | 115 | if h.startswith('@a '): |
|
116 | 116 | d[h.lstrip('@a ').strip()] = p.parent().copy() |
|
117 | 117 | elif not valid_attribute(h): |
|
118 | 118 | continue |
|
119 | 119 | d[h] = p.copy() |
|
120 | 120 | return d |
|
121 | 121 | |
|
122 | 122 | def eval_node(n): |
|
123 | 123 | body = n.b |
|
124 | 124 | if not body.startswith('@cl'): |
|
125 | 125 | # plain python repr node, just eval it |
|
126 | 126 | return ip.ev(n.b) |
|
127 | 127 | # @cl nodes deserve special treatment - first eval the first line (minus cl), then use it to call the rest of body |
|
128 | 128 | first, rest = body.split('\n',1) |
|
129 | 129 | tup = first.split(None, 1) |
|
130 | 130 | # @cl alone SPECIAL USE-> dump var to user_ns |
|
131 | 131 | if len(tup) == 1: |
|
132 | 132 | val = ip.ev(rest) |
|
133 | 133 | ip.user_ns[n.h] = val |
|
134 | 134 | es("%s = %s" % (n.h, repr(val)[:20] )) |
|
135 | 135 | return val |
|
136 | 136 | |
|
137 | 137 | cl, hd = tup |
|
138 | 138 | |
|
139 | 139 | xformer = ip.ev(hd.strip()) |
|
140 | 140 | es('Transform w/ %s' % repr(xformer)) |
|
141 | 141 | return xformer(rest, n) |
|
142 | 142 | |
|
143 | 143 | class LeoNode(object, UserDict.DictMixin): |
|
144 | 144 | """ Node in Leo outline |
|
145 | 145 | |
|
146 | 146 | Most important attributes (getters/setters available: |
|
147 | 147 | .v - evaluate node, can also be alligned |
|
148 | 148 | .b, .h - body string, headline string |
|
149 | 149 | .l - value as string list |
|
150 | 150 | |
|
151 | 151 | Also supports iteration, |
|
152 | 152 | |
|
153 | 153 | setitem / getitem (indexing): |
|
154 | 154 | wb.foo['key'] = 12 |
|
155 | 155 | assert wb.foo['key'].v == 12 |
|
156 | 156 | |
|
157 | 157 | Note the asymmetry on setitem and getitem! Also other |
|
158 | 158 | dict methods are available. |
|
159 | 159 | |
|
160 | 160 | .ipush() - run push-to-ipython |
|
161 | 161 | |
|
162 | 162 | Minibuffer command access (tab completion works): |
|
163 | 163 | |
|
164 | 164 | mb save-to-file |
|
165 | 165 | |
|
166 | 166 | """ |
|
167 | 167 | def __init__(self,p): |
|
168 | 168 | self.p = p.copy() |
|
169 | 169 | |
|
170 | 170 | def __str__(self): |
|
171 | 171 | return "<LeoNode %s>" % str(self.p) |
|
172 | 172 | |
|
173 | 173 | __repr__ = __str__ |
|
174 | 174 | |
|
175 | 175 | def __get_h(self): return self.p.headString() |
|
176 | 176 | def __set_h(self,val): |
|
177 | 177 | print "set head",val |
|
178 | 178 | c.beginUpdate() |
|
179 | 179 | try: |
|
180 | 180 | c.setHeadString(self.p,val) |
|
181 | 181 | finally: |
|
182 | 182 | c.endUpdate() |
|
183 | 183 | |
|
184 | 184 | h = property( __get_h, __set_h, doc = "Node headline string") |
|
185 | 185 | |
|
186 | 186 | def __get_b(self): return self.p.bodyString() |
|
187 | 187 | def __set_b(self,val): |
|
188 | 188 | print "set body",val |
|
189 | 189 | c.beginUpdate() |
|
190 | 190 | try: |
|
191 | 191 | c.setBodyString(self.p, val) |
|
192 | 192 | finally: |
|
193 | 193 | c.endUpdate() |
|
194 | 194 | |
|
195 | 195 | b = property(__get_b, __set_b, doc = "Nody body string") |
|
196 | 196 | |
|
197 | 197 | def __set_val(self, val): |
|
198 | 198 | self.b = format_for_leo(val) |
|
199 | 199 | |
|
200 | 200 | v = property(lambda self: eval_node(self), __set_val, doc = "Node evaluated value") |
|
201 | 201 | |
|
202 | 202 | def __set_l(self,val): |
|
203 | 203 | self.b = '\n'.join(val ) |
|
204 | 204 | l = property(lambda self : IPython.genutils.SList(self.b.splitlines()), |
|
205 | 205 | __set_l, doc = "Node value as string list") |
|
206 | 206 | |
|
207 | 207 | def __iter__(self): |
|
208 | 208 | """ Iterate through nodes direct children """ |
|
209 | 209 | |
|
210 | 210 | return (LeoNode(p) for p in self.p.children_iter()) |
|
211 | 211 | |
|
212 | 212 | def __children(self): |
|
213 | 213 | d = {} |
|
214 | 214 | for child in self: |
|
215 | 215 | head = child.h |
|
216 | 216 | tup = head.split(None,1) |
|
217 | 217 | if len(tup) > 1 and tup[0] == '@k': |
|
218 | 218 | d[tup[1]] = child |
|
219 | 219 | continue |
|
220 | 220 | |
|
221 | 221 | if not valid_attribute(head): |
|
222 | 222 | d[head] = child |
|
223 | 223 | continue |
|
224 | 224 | return d |
|
225 | 225 | def keys(self): |
|
226 | 226 | d = self.__children() |
|
227 | 227 | return d.keys() |
|
228 | 228 | def __getitem__(self, key): |
|
229 | 229 | """ wb.foo['Some stuff'] Return a child node with headline 'Some stuff' |
|
230 | 230 | |
|
231 | 231 | If key is a valid python name (e.g. 'foo'), look for headline '@k foo' as well |
|
232 | 232 | """ |
|
233 | 233 | key = str(key) |
|
234 | 234 | d = self.__children() |
|
235 | 235 | return d[key] |
|
236 | 236 | def __setitem__(self, key, val): |
|
237 | 237 | """ You can do wb.foo['My Stuff'] = 12 to create children |
|
238 | 238 | |
|
239 | 239 | This will create 'My Stuff' as a child of foo (if it does not exist), and |
|
240 | 240 | do .v = 12 assignment. |
|
241 | 241 | |
|
242 | 242 | Exception: |
|
243 | 243 | |
|
244 | 244 | wb.foo['bar'] = 12 |
|
245 | 245 | |
|
246 | 246 | will create a child with headline '@k bar', because bar is a valid python name |
|
247 | 247 | and we don't want to crowd the WorkBook namespace with (possibly numerous) entries |
|
248 | 248 | """ |
|
249 | 249 | key = str(key) |
|
250 | 250 | d = self.__children() |
|
251 | 251 | if key in d: |
|
252 | 252 | d[key].v = val |
|
253 | 253 | return |
|
254 | 254 | |
|
255 | 255 | if not valid_attribute(key): |
|
256 | 256 | head = key |
|
257 | 257 | else: |
|
258 | 258 | head = '@k ' + key |
|
259 | 259 | p = c.createLastChildNode(self.p, head, '') |
|
260 | 260 | LeoNode(p).v = val |
|
261 | 261 | |
|
262 | 262 | def ipush(self): |
|
263 | 263 | """ Does push-to-ipython on the node """ |
|
264 | 264 | push_from_leo(self) |
|
265 | 265 | |
|
266 | 266 | def go(self): |
|
267 | 267 | """ Set node as current node (to quickly see it in Outline) """ |
|
268 | 268 | c.beginUpdate() |
|
269 | 269 | try: |
|
270 | 270 | c.setCurrentPosition(self.p) |
|
271 | 271 | finally: |
|
272 | 272 | c.endUpdate() |
|
273 | 273 | |
|
274 | 274 | def script(self): |
|
275 | 275 | """ Method to get the 'tangled' contents of the node |
|
276 | 276 | |
|
277 | 277 | (parse @others, << section >> references etc.) |
|
278 | 278 | """ |
|
279 | 279 | return g.getScript(c,self.p,useSelectedText=False,useSentinels=False) |
|
280 | 280 | |
|
281 | 281 | def __get_uA(self): |
|
282 | 282 | p = self.p |
|
283 | 283 | # Create the uA if necessary. |
|
284 | 284 | if not hasattr(p.v.t,'unknownAttributes'): |
|
285 | 285 | p.v.t.unknownAttributes = {} |
|
286 | 286 | |
|
287 | 287 | d = p.v.t.unknownAttributes.setdefault('ipython', {}) |
|
288 | 288 | return d |
|
289 | 289 | |
|
290 | 290 | uA = property(__get_uA, doc = "Access persistent unknownAttributes of node") |
|
291 | 291 | |
|
292 | 292 | |
|
293 | 293 | class LeoWorkbook: |
|
294 | 294 | """ class for 'advanced' node access |
|
295 | 295 | |
|
296 | 296 | Has attributes for all "discoverable" nodes. Node is discoverable if it |
|
297 | 297 | either |
|
298 | 298 | |
|
299 | 299 | - has a valid python name (Foo, bar_12) |
|
300 | 300 | - is a parent of an anchor node (if it has a child '@a foo', it is visible as foo) |
|
301 | 301 | |
|
302 | 302 | """ |
|
303 | 303 | def __getattr__(self, key): |
|
304 | 304 | if key.startswith('_') or key == 'trait_names' or not valid_attribute(key): |
|
305 | 305 | raise AttributeError |
|
306 | 306 | cells = all_cells() |
|
307 | 307 | p = cells.get(key, None) |
|
308 | 308 | if p is None: |
|
309 | 309 | return add_var(key) |
|
310 | 310 | |
|
311 | 311 | return LeoNode(p) |
|
312 | 312 | |
|
313 | 313 | def __str__(self): |
|
314 | 314 | return "<LeoWorkbook>" |
|
315 | 315 | def __setattr__(self,key, val): |
|
316 | 316 | raise AttributeError("Direct assignment to workbook denied, try wb.%s.v = %s" % (key,val)) |
|
317 | 317 | |
|
318 | 318 | __repr__ = __str__ |
|
319 | 319 | |
|
320 | 320 | def __iter__(self): |
|
321 | 321 | """ Iterate all (even non-exposed) nodes """ |
|
322 | 322 | cells = all_cells() |
|
323 | 323 | return (LeoNode(p) for p in c.allNodes_iter()) |
|
324 | 324 | |
|
325 | 325 | current = property(lambda self: LeoNode(c.currentPosition()), doc = "Currently selected node") |
|
326 | 326 | |
|
327 | 327 | def match_h(self, regex): |
|
328 | 328 | cmp = re.compile(regex) |
|
329 | 329 | for node in self: |
|
330 | 330 | if re.match(cmp, node.h, re.IGNORECASE): |
|
331 | 331 | yield node |
|
332 | 332 | return |
|
333 | 333 | |
|
334 | 334 | @IPython.generics.complete_object.when_type(LeoWorkbook) |
|
335 | 335 | def workbook_complete(obj, prev): |
|
336 | 336 | return all_cells().keys() + [s for s in prev if not s.startswith('_')] |
|
337 | 337 | |
|
338 | 338 | |
|
339 | 339 | def add_var(varname): |
|
340 | 340 | c.beginUpdate() |
|
341 | 341 | r = rootnode() |
|
342 | 342 | try: |
|
343 | 343 | if r is None: |
|
344 | 344 | p2 = g.findNodeAnywhere(c,varname) |
|
345 | 345 | else: |
|
346 | 346 | p2 = g.findNodeInChildren(c, r.p, varname) |
|
347 | 347 | if p2: |
|
348 | 348 | return LeoNode(p2) |
|
349 | 349 | |
|
350 | 350 | if r is not None: |
|
351 | 351 | p2 = r.p.insertAsLastChild() |
|
352 | 352 | |
|
353 | 353 | else: |
|
354 | 354 | p2 = c.currentPosition().insertAfter() |
|
355 | 355 | |
|
356 | 356 | c.setHeadString(p2,varname) |
|
357 | 357 | return LeoNode(p2) |
|
358 | 358 | finally: |
|
359 | 359 | c.endUpdate() |
|
360 | 360 | |
|
361 | 361 | def add_file(self,fname): |
|
362 | 362 | p2 = c.currentPosition().insertAfter() |
|
363 | 363 | |
|
364 | 364 | push_from_leo = CommandChainDispatcher() |
|
365 | 365 | |
|
366 | 366 | def expose_ileo_push(f, prio = 0): |
|
367 | 367 | push_from_leo.add(f, prio) |
|
368 | 368 | |
|
369 | 369 | def push_ipython_script(node): |
|
370 | 370 | """ Execute the node body in IPython, as if it was entered in interactive prompt """ |
|
371 | 371 | c.beginUpdate() |
|
372 | 372 | try: |
|
373 | 373 | ohist = ip.IP.output_hist |
|
374 | 374 | hstart = len(ip.IP.input_hist) |
|
375 | 375 | script = node.script() |
|
376 | 376 | |
|
377 | 377 | ip.user_ns['_p'] = node |
|
378 | 378 | ip.runlines(script) |
|
379 | 379 | ip.user_ns.pop('_p',None) |
|
380 | 380 | |
|
381 | 381 | has_output = False |
|
382 | 382 | for idx in range(hstart,len(ip.IP.input_hist)): |
|
383 | 383 | val = ohist.get(idx,None) |
|
384 | 384 | if val is None: |
|
385 | 385 | continue |
|
386 | 386 | has_output = True |
|
387 | 387 | inp = ip.IP.input_hist[idx] |
|
388 | 388 | if inp.strip(): |
|
389 | 389 | es('In: %s' % (inp[:40], )) |
|
390 | 390 | |
|
391 | 391 | es('<%d> %s' % (idx, pprint.pformat(ohist[idx],width = 40))) |
|
392 | 392 | |
|
393 | 393 | if not has_output: |
|
394 | 394 | es('ipy run: %s (%d LL)' %( node.h,len(script))) |
|
395 | 395 | finally: |
|
396 | 396 | c.endUpdate() |
|
397 | 397 | |
|
398 | 398 | |
|
399 | 399 | def eval_body(body): |
|
400 | 400 | try: |
|
401 | 401 | val = ip.ev(body) |
|
402 | 402 | except: |
|
403 | 403 | # just use stringlist if it's not completely legal python expression |
|
404 | 404 | val = IPython.genutils.SList(body.splitlines()) |
|
405 | 405 | return val |
|
406 | 406 | |
|
407 | 407 | def push_plain_python(node): |
|
408 | 408 | if not node.h.endswith('P'): |
|
409 | 409 | raise TryNext |
|
410 | 410 | script = node.script() |
|
411 | 411 | lines = script.count('\n') |
|
412 | 412 | try: |
|
413 | 413 | exec script in ip.user_ns |
|
414 | 414 | except: |
|
415 | 415 | print " -- Exception in script:\n"+script + "\n --" |
|
416 | 416 | raise |
|
417 | 417 | es('ipy plain: %s (%d LL)' % (node.h,lines)) |
|
418 | 418 | |
|
419 | 419 | |
|
420 | 420 | def push_cl_node(node): |
|
421 | 421 | """ If node starts with @cl, eval it |
|
422 | 422 | |
|
423 | 423 | The result is put as last child of @ipy-results node, if it exists |
|
424 | 424 | """ |
|
425 | 425 | if not node.b.startswith('@cl'): |
|
426 | 426 | raise TryNext |
|
427 | 427 | |
|
428 | 428 | p2 = g.findNodeAnywhere(c,'@ipy-results') |
|
429 | 429 | val = node.v |
|
430 | 430 | if p2: |
|
431 | 431 | es("=> @ipy-results") |
|
432 | 432 | LeoNode(p2).v = val |
|
433 | 433 | es(val) |
|
434 | 434 | |
|
435 | 435 | def push_ev_node(node): |
|
436 | 436 | """ If headline starts with @ev, eval it and put result in body """ |
|
437 | 437 | if not node.h.startswith('@ev '): |
|
438 | 438 | raise TryNext |
|
439 | 439 | expr = node.h.lstrip('@ev ') |
|
440 | 440 | es('ipy eval ' + expr) |
|
441 | 441 | res = ip.ev(expr) |
|
442 | 442 | node.v = res |
|
443 | 443 | |
|
444 | 444 | |
|
445 | 445 | def push_position_from_leo(p): |
|
446 | push_from_leo(LeoNode(p)) | |
|
446 | try: | |
|
447 | push_from_leo(LeoNode(p)) | |
|
448 | except AttributeError,e: | |
|
449 | if e.args == ("Commands instance has no attribute 'frame'",): | |
|
450 | es("Error: ILeo not associated with .leo document") | |
|
451 | es("Press alt+shift+I to fix!") | |
|
452 | else: | |
|
453 | raise | |
|
447 | 454 | |
|
448 | 455 | @generic |
|
449 | 456 | def edit_object_in_leo(obj, varname): |
|
450 | 457 | """ Make it @cl node so it can be pushed back directly by alt+I """ |
|
451 | 458 | node = add_var(varname) |
|
452 | 459 | formatted = format_for_leo(obj) |
|
453 | 460 | if not formatted.startswith('@cl'): |
|
454 | 461 | formatted = '@cl\n' + formatted |
|
455 | 462 | node.b = formatted |
|
456 | 463 | node.go() |
|
457 | 464 | |
|
458 | 465 | @edit_object_in_leo.when_type(IPython.macro.Macro) |
|
459 | 466 | def edit_macro(obj,varname): |
|
460 | 467 | bod = '_ip.defmacro("""\\\n' + obj.value + '""")' |
|
461 | 468 | node = add_var('Macro_' + varname) |
|
462 | 469 | node.b = bod |
|
463 | 470 | node.go() |
|
464 | 471 | |
|
465 | 472 | def get_history(hstart = 0): |
|
466 | 473 | res = [] |
|
467 | 474 | ohist = ip.IP.output_hist |
|
468 | 475 | |
|
469 | 476 | for idx in range(hstart, len(ip.IP.input_hist)): |
|
470 | 477 | val = ohist.get(idx,None) |
|
471 | 478 | has_output = True |
|
472 | 479 | inp = ip.IP.input_hist_raw[idx] |
|
473 | 480 | if inp.strip(): |
|
474 | 481 | res.append('In [%d]: %s' % (idx, inp)) |
|
475 | 482 | if val: |
|
476 | 483 | res.append(pprint.pformat(val)) |
|
477 | 484 | res.append('\n') |
|
478 | 485 | return ''.join(res) |
|
479 | 486 | |
|
480 | 487 | |
|
481 | 488 | def lee_f(self,s): |
|
482 | 489 | """ Open file(s)/objects in Leo |
|
483 | 490 | |
|
484 | 491 | - %lee hist -> open full session history in leo |
|
485 | 492 | - Takes an object. l = [1,2,"hello"]; %lee l. Alt+I in leo pushes the object back |
|
486 | 493 | - Takes an mglob pattern, e.g. '%lee *.cpp' or %lee 'rec:*.cpp' |
|
487 | 494 | - Takes input history indices: %lee 4 6-8 10 12-47 |
|
488 | 495 | """ |
|
489 | 496 | import os |
|
490 | 497 | |
|
491 | 498 | c.beginUpdate() |
|
492 | 499 | try: |
|
493 | 500 | if s == 'hist': |
|
494 | 501 | wb.ipython_history.b = get_history() |
|
495 | 502 | wb.ipython_history.go() |
|
496 | 503 | return |
|
497 | 504 | |
|
498 | 505 | |
|
499 | 506 | if s and s[0].isdigit(): |
|
500 | 507 | # numbers; push input slices to leo |
|
501 | 508 | lines = self.extract_input_slices(s.strip().split(), True) |
|
502 | 509 | v = add_var('stored_ipython_input') |
|
503 | 510 | v.b = '\n'.join(lines) |
|
504 | 511 | return |
|
505 | 512 | |
|
506 | 513 | |
|
507 | 514 | # try editing the object directly |
|
508 | 515 | obj = ip.user_ns.get(s, None) |
|
509 | 516 | if obj is not None: |
|
510 | 517 | edit_object_in_leo(obj,s) |
|
511 | 518 | return |
|
512 | 519 | |
|
513 | 520 | |
|
514 | 521 | # if it's not object, it's a file name / mglob pattern |
|
515 | 522 | from IPython.external import mglob |
|
516 | 523 | |
|
517 | 524 | files = (os.path.abspath(f) for f in mglob.expand(s)) |
|
518 | 525 | for fname in files: |
|
519 | 526 | p = g.findNodeAnywhere(c,'@auto ' + fname) |
|
520 | 527 | if not p: |
|
521 | 528 | p = c.currentPosition().insertAfter() |
|
522 | 529 | |
|
523 | 530 | p.setHeadString('@auto ' + fname) |
|
524 | 531 | if os.path.isfile(fname): |
|
525 | 532 | c.setBodyString(p,open(fname).read()) |
|
526 | 533 | c.selectPosition(p) |
|
527 | 534 | print "Editing file(s), press ctrl+shift+w in Leo to write @auto nodes" |
|
528 | 535 | finally: |
|
529 | 536 | c.endUpdate() |
|
530 | 537 | |
|
531 | 538 | |
|
532 | 539 | |
|
533 | 540 | def leoref_f(self,s): |
|
534 | 541 | """ Quick reference for ILeo """ |
|
535 | 542 | import textwrap |
|
536 | 543 | print textwrap.dedent("""\ |
|
537 | 544 | %leoe file/object - open file / object in leo |
|
538 | 545 | wb.foo.v - eval node foo (i.e. headstring is 'foo' or '@ipy foo') |
|
539 | 546 | wb.foo.v = 12 - assign to body of node foo |
|
540 | 547 | wb.foo.b - read or write the body of node foo |
|
541 | 548 | wb.foo.l - body of node foo as string list |
|
542 | 549 | |
|
543 | 550 | for el in wb.foo: |
|
544 | 551 | print el.v |
|
545 | 552 | |
|
546 | 553 | """ |
|
547 | 554 | ) |
|
548 | 555 | |
|
549 | 556 | |
|
550 | 557 | |
|
551 | 558 | def mb_f(self, arg): |
|
552 | 559 | """ Execute leo minibuffer commands |
|
553 | 560 | |
|
554 | 561 | Example: |
|
555 | 562 | mb save-to-file |
|
556 | 563 | """ |
|
557 | 564 | c.executeMinibufferCommand(arg) |
|
558 | 565 | |
|
559 | 566 | def mb_completer(self,event): |
|
560 | 567 | """ Custom completer for minibuffer """ |
|
561 | 568 | cmd_param = event.line.split() |
|
562 | 569 | if event.line.endswith(' '): |
|
563 | 570 | cmd_param.append('') |
|
564 | 571 | if len(cmd_param) > 2: |
|
565 | 572 | return ip.IP.Completer.file_matches(event.symbol) |
|
566 | 573 | cmds = c.commandsDict.keys() |
|
567 | 574 | cmds.sort() |
|
568 | 575 | return cmds |
|
569 | 576 | |
|
570 | 577 | def show_welcome(): |
|
571 | 578 | print "------------------" |
|
572 | 579 | print "Welcome to Leo-enabled IPython session!" |
|
573 | 580 | print "Try %leoref for quick reference." |
|
574 | 581 | import IPython.platutils |
|
575 | 582 | IPython.platutils.set_term_title('ILeo') |
|
576 | 583 | IPython.platutils.freeze_term_title() |
|
577 | 584 | |
|
578 | 585 | def run_leo_startup_node(): |
|
579 | 586 | p = g.findNodeAnywhere(c,'@ipy-startup') |
|
580 | 587 | if p: |
|
581 | 588 | print "Running @ipy-startup nodes" |
|
582 | 589 | for n in LeoNode(p): |
|
583 | 590 | push_from_leo(n) |
|
584 | 591 | |
|
585 | 592 |
@@ -1,3311 +1,3311 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Magic functions for InteractiveShell. |
|
3 | 3 | |
|
4 | 4 | $Id: Magic.py 2996 2008-01-30 06:31:39Z fperez $""" |
|
5 | 5 | |
|
6 | 6 | #***************************************************************************** |
|
7 | 7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
8 | 8 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> |
|
9 | 9 | # |
|
10 | 10 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | 11 | # the file COPYING, distributed as part of this software. |
|
12 | 12 | #***************************************************************************** |
|
13 | 13 | |
|
14 | 14 | #**************************************************************************** |
|
15 | 15 | # Modules and globals |
|
16 | 16 | |
|
17 | 17 | from IPython import Release |
|
18 | 18 | __author__ = '%s <%s>\n%s <%s>' % \ |
|
19 | 19 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) |
|
20 | 20 | __license__ = Release.license |
|
21 | 21 | |
|
22 | 22 | # Python standard modules |
|
23 | 23 | import __builtin__ |
|
24 | 24 | import bdb |
|
25 | 25 | import inspect |
|
26 | 26 | import os |
|
27 | 27 | import pdb |
|
28 | 28 | import pydoc |
|
29 | 29 | import sys |
|
30 | 30 | import re |
|
31 | 31 | import tempfile |
|
32 | 32 | import time |
|
33 | 33 | import cPickle as pickle |
|
34 | 34 | import textwrap |
|
35 | 35 | from cStringIO import StringIO |
|
36 | 36 | from getopt import getopt,GetoptError |
|
37 | 37 | from pprint import pprint, pformat |
|
38 | 38 | from sets import Set |
|
39 | 39 | |
|
40 | 40 | # cProfile was added in Python2.5 |
|
41 | 41 | try: |
|
42 | 42 | import cProfile as profile |
|
43 | 43 | import pstats |
|
44 | 44 | except ImportError: |
|
45 | 45 | # profile isn't bundled by default in Debian for license reasons |
|
46 | 46 | try: |
|
47 | 47 | import profile,pstats |
|
48 | 48 | except ImportError: |
|
49 | 49 | profile = pstats = None |
|
50 | 50 | |
|
51 | 51 | # Homebrewed |
|
52 | 52 | import IPython |
|
53 | 53 | from IPython import Debugger, OInspect, wildcard |
|
54 | 54 | from IPython.FakeModule import FakeModule |
|
55 | 55 | from IPython.Itpl import Itpl, itpl, printpl,itplns |
|
56 | 56 | from IPython.PyColorize import Parser |
|
57 | 57 | from IPython.ipstruct import Struct |
|
58 | 58 | from IPython.macro import Macro |
|
59 | 59 | from IPython.genutils import * |
|
60 | 60 | from IPython import platutils |
|
61 | 61 | import IPython.generics |
|
62 | 62 | import IPython.ipapi |
|
63 | 63 | from IPython.ipapi import UsageError |
|
64 | 64 | #*************************************************************************** |
|
65 | 65 | # Utility functions |
|
66 | 66 | def on_off(tag): |
|
67 | 67 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
68 | 68 | return ['OFF','ON'][tag] |
|
69 | 69 | |
|
70 | 70 | class Bunch: pass |
|
71 | 71 | |
|
72 | 72 | def compress_dhist(dh): |
|
73 | 73 | head, tail = dh[:-10], dh[-10:] |
|
74 | 74 | |
|
75 | 75 | newhead = [] |
|
76 | 76 | done = Set() |
|
77 | 77 | for h in head: |
|
78 | 78 | if h in done: |
|
79 | 79 | continue |
|
80 | 80 | newhead.append(h) |
|
81 | 81 | done.add(h) |
|
82 | 82 | |
|
83 | 83 | return newhead + tail |
|
84 | 84 | |
|
85 | 85 | |
|
86 | 86 | #*************************************************************************** |
|
87 | 87 | # Main class implementing Magic functionality |
|
88 | 88 | class Magic: |
|
89 | 89 | """Magic functions for InteractiveShell. |
|
90 | 90 | |
|
91 | 91 | Shell functions which can be reached as %function_name. All magic |
|
92 | 92 | functions should accept a string, which they can parse for their own |
|
93 | 93 | needs. This can make some functions easier to type, eg `%cd ../` |
|
94 | 94 | vs. `%cd("../")` |
|
95 | 95 | |
|
96 | 96 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
97 | 97 | at the command line, but it is is needed in the definition. """ |
|
98 | 98 | |
|
99 | 99 | # class globals |
|
100 | 100 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
101 | 101 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
102 | 102 | |
|
103 | 103 | #...................................................................... |
|
104 | 104 | # some utility functions |
|
105 | 105 | |
|
106 | 106 | def __init__(self,shell): |
|
107 | 107 | |
|
108 | 108 | self.options_table = {} |
|
109 | 109 | if profile is None: |
|
110 | 110 | self.magic_prun = self.profile_missing_notice |
|
111 | 111 | self.shell = shell |
|
112 | 112 | |
|
113 | 113 | # namespace for holding state we may need |
|
114 | 114 | self._magic_state = Bunch() |
|
115 | 115 | |
|
116 | 116 | def profile_missing_notice(self, *args, **kwargs): |
|
117 | 117 | error("""\ |
|
118 |
The profile module could not be found. |
|
|
119 | it has been removed from the standard Debian package because of its non-free | |
|
120 | license. To use profiling, please install"python2.3-profiler" from non-free.""") | |
|
118 | The profile module could not be found. It has been removed from the standard | |
|
119 | python packages because of its non-free license. To use profiling, install the | |
|
120 | python-profiler package from non-free.""") | |
|
121 | 121 | |
|
122 | 122 | def default_option(self,fn,optstr): |
|
123 | 123 | """Make an entry in the options_table for fn, with value optstr""" |
|
124 | 124 | |
|
125 | 125 | if fn not in self.lsmagic(): |
|
126 | 126 | error("%s is not a magic function" % fn) |
|
127 | 127 | self.options_table[fn] = optstr |
|
128 | 128 | |
|
129 | 129 | def lsmagic(self): |
|
130 | 130 | """Return a list of currently available magic functions. |
|
131 | 131 | |
|
132 | 132 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
133 | 133 | ['magic_ls','magic_cd',...]""" |
|
134 | 134 | |
|
135 | 135 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
136 | 136 | |
|
137 | 137 | # magics in class definition |
|
138 | 138 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
139 | 139 | callable(Magic.__dict__[fn]) |
|
140 | 140 | # in instance namespace (run-time user additions) |
|
141 | 141 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
142 | 142 | callable(self.__dict__[fn]) |
|
143 | 143 | # and bound magics by user (so they can access self): |
|
144 | 144 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
145 | 145 | callable(self.__class__.__dict__[fn]) |
|
146 | 146 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
147 | 147 | filter(inst_magic,self.__dict__.keys()) + \ |
|
148 | 148 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
149 | 149 | out = [] |
|
150 | 150 | for fn in Set(magics): |
|
151 | 151 | out.append(fn.replace('magic_','',1)) |
|
152 | 152 | out.sort() |
|
153 | 153 | return out |
|
154 | 154 | |
|
155 | 155 | def extract_input_slices(self,slices,raw=False): |
|
156 | 156 | """Return as a string a set of input history slices. |
|
157 | 157 | |
|
158 | 158 | Inputs: |
|
159 | 159 | |
|
160 | 160 | - slices: the set of slices is given as a list of strings (like |
|
161 | 161 | ['1','4:8','9'], since this function is for use by magic functions |
|
162 | 162 | which get their arguments as strings. |
|
163 | 163 | |
|
164 | 164 | Optional inputs: |
|
165 | 165 | |
|
166 | 166 | - raw(False): by default, the processed input is used. If this is |
|
167 | 167 | true, the raw input history is used instead. |
|
168 | 168 | |
|
169 | 169 | Note that slices can be called with two notations: |
|
170 | 170 | |
|
171 | 171 | N:M -> standard python form, means including items N...(M-1). |
|
172 | 172 | |
|
173 | 173 | N-M -> include items N..M (closed endpoint).""" |
|
174 | 174 | |
|
175 | 175 | if raw: |
|
176 | 176 | hist = self.shell.input_hist_raw |
|
177 | 177 | else: |
|
178 | 178 | hist = self.shell.input_hist |
|
179 | 179 | |
|
180 | 180 | cmds = [] |
|
181 | 181 | for chunk in slices: |
|
182 | 182 | if ':' in chunk: |
|
183 | 183 | ini,fin = map(int,chunk.split(':')) |
|
184 | 184 | elif '-' in chunk: |
|
185 | 185 | ini,fin = map(int,chunk.split('-')) |
|
186 | 186 | fin += 1 |
|
187 | 187 | else: |
|
188 | 188 | ini = int(chunk) |
|
189 | 189 | fin = ini+1 |
|
190 | 190 | cmds.append(hist[ini:fin]) |
|
191 | 191 | return cmds |
|
192 | 192 | |
|
193 | 193 | def _ofind(self, oname, namespaces=None): |
|
194 | 194 | """Find an object in the available namespaces. |
|
195 | 195 | |
|
196 | 196 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
197 | 197 | |
|
198 | 198 | Has special code to detect magic functions. |
|
199 | 199 | """ |
|
200 | 200 | |
|
201 | 201 | oname = oname.strip() |
|
202 | 202 | |
|
203 | 203 | alias_ns = None |
|
204 | 204 | if namespaces is None: |
|
205 | 205 | # Namespaces to search in: |
|
206 | 206 | # Put them in a list. The order is important so that we |
|
207 | 207 | # find things in the same order that Python finds them. |
|
208 | 208 | namespaces = [ ('Interactive', self.shell.user_ns), |
|
209 | 209 | ('IPython internal', self.shell.internal_ns), |
|
210 | 210 | ('Python builtin', __builtin__.__dict__), |
|
211 | 211 | ('Alias', self.shell.alias_table), |
|
212 | 212 | ] |
|
213 | 213 | alias_ns = self.shell.alias_table |
|
214 | 214 | |
|
215 | 215 | # initialize results to 'null' |
|
216 | 216 | found = 0; obj = None; ospace = None; ds = None; |
|
217 | 217 | ismagic = 0; isalias = 0; parent = None |
|
218 | 218 | |
|
219 | 219 | # Look for the given name by splitting it in parts. If the head is |
|
220 | 220 | # found, then we look for all the remaining parts as members, and only |
|
221 | 221 | # declare success if we can find them all. |
|
222 | 222 | oname_parts = oname.split('.') |
|
223 | 223 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
224 | 224 | for nsname,ns in namespaces: |
|
225 | 225 | try: |
|
226 | 226 | obj = ns[oname_head] |
|
227 | 227 | except KeyError: |
|
228 | 228 | continue |
|
229 | 229 | else: |
|
230 | 230 | #print 'oname_rest:', oname_rest # dbg |
|
231 | 231 | for part in oname_rest: |
|
232 | 232 | try: |
|
233 | 233 | parent = obj |
|
234 | 234 | obj = getattr(obj,part) |
|
235 | 235 | except: |
|
236 | 236 | # Blanket except b/c some badly implemented objects |
|
237 | 237 | # allow __getattr__ to raise exceptions other than |
|
238 | 238 | # AttributeError, which then crashes IPython. |
|
239 | 239 | break |
|
240 | 240 | else: |
|
241 | 241 | # If we finish the for loop (no break), we got all members |
|
242 | 242 | found = 1 |
|
243 | 243 | ospace = nsname |
|
244 | 244 | if ns == alias_ns: |
|
245 | 245 | isalias = 1 |
|
246 | 246 | break # namespace loop |
|
247 | 247 | |
|
248 | 248 | # Try to see if it's magic |
|
249 | 249 | if not found: |
|
250 | 250 | if oname.startswith(self.shell.ESC_MAGIC): |
|
251 | 251 | oname = oname[1:] |
|
252 | 252 | obj = getattr(self,'magic_'+oname,None) |
|
253 | 253 | if obj is not None: |
|
254 | 254 | found = 1 |
|
255 | 255 | ospace = 'IPython internal' |
|
256 | 256 | ismagic = 1 |
|
257 | 257 | |
|
258 | 258 | # Last try: special-case some literals like '', [], {}, etc: |
|
259 | 259 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
260 | 260 | obj = eval(oname_head) |
|
261 | 261 | found = 1 |
|
262 | 262 | ospace = 'Interactive' |
|
263 | 263 | |
|
264 | 264 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
265 | 265 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
266 | 266 | |
|
267 | 267 | def arg_err(self,func): |
|
268 | 268 | """Print docstring if incorrect arguments were passed""" |
|
269 | 269 | print 'Error in arguments:' |
|
270 | 270 | print OInspect.getdoc(func) |
|
271 | 271 | |
|
272 | 272 | def format_latex(self,strng): |
|
273 | 273 | """Format a string for latex inclusion.""" |
|
274 | 274 | |
|
275 | 275 | # Characters that need to be escaped for latex: |
|
276 | 276 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
277 | 277 | # Magic command names as headers: |
|
278 | 278 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, |
|
279 | 279 | re.MULTILINE) |
|
280 | 280 | # Magic commands |
|
281 | 281 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, |
|
282 | 282 | re.MULTILINE) |
|
283 | 283 | # Paragraph continue |
|
284 | 284 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
285 | 285 | |
|
286 | 286 | # The "\n" symbol |
|
287 | 287 | newline_re = re.compile(r'\\n') |
|
288 | 288 | |
|
289 | 289 | # Now build the string for output: |
|
290 | 290 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
291 | 291 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
292 | 292 | strng) |
|
293 | 293 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
294 | 294 | strng = par_re.sub(r'\\\\',strng) |
|
295 | 295 | strng = escape_re.sub(r'\\\1',strng) |
|
296 | 296 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
297 | 297 | return strng |
|
298 | 298 | |
|
299 | 299 | def format_screen(self,strng): |
|
300 | 300 | """Format a string for screen printing. |
|
301 | 301 | |
|
302 | 302 | This removes some latex-type format codes.""" |
|
303 | 303 | # Paragraph continue |
|
304 | 304 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
305 | 305 | strng = par_re.sub('',strng) |
|
306 | 306 | return strng |
|
307 | 307 | |
|
308 | 308 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
309 | 309 | """Parse options passed to an argument string. |
|
310 | 310 | |
|
311 | 311 | The interface is similar to that of getopt(), but it returns back a |
|
312 | 312 | Struct with the options as keys and the stripped argument string still |
|
313 | 313 | as a string. |
|
314 | 314 | |
|
315 | 315 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
316 | 316 | This allows us to easily expand variables, glob files, quote |
|
317 | 317 | arguments, etc. |
|
318 | 318 | |
|
319 | 319 | Options: |
|
320 | 320 | -mode: default 'string'. If given as 'list', the argument string is |
|
321 | 321 | returned as a list (split on whitespace) instead of a string. |
|
322 | 322 | |
|
323 | 323 | -list_all: put all option values in lists. Normally only options |
|
324 | 324 | appearing more than once are put in a list. |
|
325 | 325 | |
|
326 | 326 | -posix (True): whether to split the input line in POSIX mode or not, |
|
327 | 327 | as per the conventions outlined in the shlex module from the |
|
328 | 328 | standard library.""" |
|
329 | 329 | |
|
330 | 330 | # inject default options at the beginning of the input line |
|
331 | 331 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
332 | 332 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
333 | 333 | |
|
334 | 334 | mode = kw.get('mode','string') |
|
335 | 335 | if mode not in ['string','list']: |
|
336 | 336 | raise ValueError,'incorrect mode given: %s' % mode |
|
337 | 337 | # Get options |
|
338 | 338 | list_all = kw.get('list_all',0) |
|
339 | 339 | posix = kw.get('posix',True) |
|
340 | 340 | |
|
341 | 341 | # Check if we have more than one argument to warrant extra processing: |
|
342 | 342 | odict = {} # Dictionary with options |
|
343 | 343 | args = arg_str.split() |
|
344 | 344 | if len(args) >= 1: |
|
345 | 345 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
346 | 346 | # need to look for options |
|
347 | 347 | argv = arg_split(arg_str,posix) |
|
348 | 348 | # Do regular option processing |
|
349 | 349 | try: |
|
350 | 350 | opts,args = getopt(argv,opt_str,*long_opts) |
|
351 | 351 | except GetoptError,e: |
|
352 | 352 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
353 | 353 | " ".join(long_opts))) |
|
354 | 354 | for o,a in opts: |
|
355 | 355 | if o.startswith('--'): |
|
356 | 356 | o = o[2:] |
|
357 | 357 | else: |
|
358 | 358 | o = o[1:] |
|
359 | 359 | try: |
|
360 | 360 | odict[o].append(a) |
|
361 | 361 | except AttributeError: |
|
362 | 362 | odict[o] = [odict[o],a] |
|
363 | 363 | except KeyError: |
|
364 | 364 | if list_all: |
|
365 | 365 | odict[o] = [a] |
|
366 | 366 | else: |
|
367 | 367 | odict[o] = a |
|
368 | 368 | |
|
369 | 369 | # Prepare opts,args for return |
|
370 | 370 | opts = Struct(odict) |
|
371 | 371 | if mode == 'string': |
|
372 | 372 | args = ' '.join(args) |
|
373 | 373 | |
|
374 | 374 | return opts,args |
|
375 | 375 | |
|
376 | 376 | #...................................................................... |
|
377 | 377 | # And now the actual magic functions |
|
378 | 378 | |
|
379 | 379 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
380 | 380 | def magic_lsmagic(self, parameter_s = ''): |
|
381 | 381 | """List currently available magic functions.""" |
|
382 | 382 | mesc = self.shell.ESC_MAGIC |
|
383 | 383 | print 'Available magic functions:\n'+mesc+\ |
|
384 | 384 | (' '+mesc).join(self.lsmagic()) |
|
385 | 385 | print '\n' + Magic.auto_status[self.shell.rc.automagic] |
|
386 | 386 | return None |
|
387 | 387 | |
|
388 | 388 | def magic_magic(self, parameter_s = ''): |
|
389 | 389 | """Print information about the magic function system. |
|
390 | 390 | |
|
391 | 391 | Supported formats: -latex, -brief, -rest |
|
392 | 392 | """ |
|
393 | 393 | |
|
394 | 394 | mode = '' |
|
395 | 395 | try: |
|
396 | 396 | if parameter_s.split()[0] == '-latex': |
|
397 | 397 | mode = 'latex' |
|
398 | 398 | if parameter_s.split()[0] == '-brief': |
|
399 | 399 | mode = 'brief' |
|
400 | 400 | if parameter_s.split()[0] == '-rest': |
|
401 | 401 | mode = 'rest' |
|
402 | 402 | rest_docs = [] |
|
403 | 403 | except: |
|
404 | 404 | pass |
|
405 | 405 | |
|
406 | 406 | magic_docs = [] |
|
407 | 407 | for fname in self.lsmagic(): |
|
408 | 408 | mname = 'magic_' + fname |
|
409 | 409 | for space in (Magic,self,self.__class__): |
|
410 | 410 | try: |
|
411 | 411 | fn = space.__dict__[mname] |
|
412 | 412 | except KeyError: |
|
413 | 413 | pass |
|
414 | 414 | else: |
|
415 | 415 | break |
|
416 | 416 | if mode == 'brief': |
|
417 | 417 | # only first line |
|
418 | 418 | if fn.__doc__: |
|
419 | 419 | fndoc = fn.__doc__.split('\n',1)[0] |
|
420 | 420 | else: |
|
421 | 421 | fndoc = 'No documentation' |
|
422 | 422 | else: |
|
423 | 423 | fndoc = fn.__doc__.rstrip() |
|
424 | 424 | |
|
425 | 425 | if mode == 'rest': |
|
426 | 426 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC, |
|
427 | 427 | fname,fndoc)) |
|
428 | 428 | |
|
429 | 429 | else: |
|
430 | 430 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, |
|
431 | 431 | fname,fndoc)) |
|
432 | 432 | |
|
433 | 433 | magic_docs = ''.join(magic_docs) |
|
434 | 434 | |
|
435 | 435 | if mode == 'rest': |
|
436 | 436 | return "".join(rest_docs) |
|
437 | 437 | |
|
438 | 438 | if mode == 'latex': |
|
439 | 439 | print self.format_latex(magic_docs) |
|
440 | 440 | return |
|
441 | 441 | else: |
|
442 | 442 | magic_docs = self.format_screen(magic_docs) |
|
443 | 443 | if mode == 'brief': |
|
444 | 444 | return magic_docs |
|
445 | 445 | |
|
446 | 446 | outmsg = """ |
|
447 | 447 | IPython's 'magic' functions |
|
448 | 448 | =========================== |
|
449 | 449 | |
|
450 | 450 | The magic function system provides a series of functions which allow you to |
|
451 | 451 | control the behavior of IPython itself, plus a lot of system-type |
|
452 | 452 | features. All these functions are prefixed with a % character, but parameters |
|
453 | 453 | are given without parentheses or quotes. |
|
454 | 454 | |
|
455 | 455 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
456 | 456 | %automagic function), you don't need to type in the % explicitly. By default, |
|
457 | 457 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
458 | 458 | |
|
459 | 459 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
460 | 460 | to 'mydir', if it exists. |
|
461 | 461 | |
|
462 | 462 | You can define your own magic functions to extend the system. See the supplied |
|
463 | 463 | ipythonrc and example-magic.py files for details (in your ipython |
|
464 | 464 | configuration directory, typically $HOME/.ipython/). |
|
465 | 465 | |
|
466 | 466 | You can also define your own aliased names for magic functions. In your |
|
467 | 467 | ipythonrc file, placing a line like: |
|
468 | 468 | |
|
469 | 469 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
470 | 470 | |
|
471 | 471 | will define %pf as a new name for %profile. |
|
472 | 472 | |
|
473 | 473 | You can also call magics in code using the ipmagic() function, which IPython |
|
474 | 474 | automatically adds to the builtin namespace. Type 'ipmagic?' for details. |
|
475 | 475 | |
|
476 | 476 | For a list of the available magic functions, use %lsmagic. For a description |
|
477 | 477 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
478 | 478 | |
|
479 | 479 | Currently the magic system has the following functions:\n""" |
|
480 | 480 | |
|
481 | 481 | mesc = self.shell.ESC_MAGIC |
|
482 | 482 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
483 | 483 | "\n\n%s%s\n\n%s" % (outmsg, |
|
484 | 484 | magic_docs,mesc,mesc, |
|
485 | 485 | (' '+mesc).join(self.lsmagic()), |
|
486 | 486 | Magic.auto_status[self.shell.rc.automagic] ) ) |
|
487 | 487 | |
|
488 | 488 | page(outmsg,screen_lines=self.shell.rc.screen_length) |
|
489 | 489 | |
|
490 | 490 | |
|
491 | 491 | def magic_autoindent(self, parameter_s = ''): |
|
492 | 492 | """Toggle autoindent on/off (if available).""" |
|
493 | 493 | |
|
494 | 494 | self.shell.set_autoindent() |
|
495 | 495 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
496 | 496 | |
|
497 | 497 | |
|
498 | 498 | def magic_automagic(self, parameter_s = ''): |
|
499 | 499 | """Make magic functions callable without having to type the initial %. |
|
500 | 500 | |
|
501 | 501 | Without argumentsl toggles on/off (when off, you must call it as |
|
502 | 502 | %automagic, of course). With arguments it sets the value, and you can |
|
503 | 503 | use any of (case insensitive): |
|
504 | 504 | |
|
505 | 505 | - on,1,True: to activate |
|
506 | 506 | |
|
507 | 507 | - off,0,False: to deactivate. |
|
508 | 508 | |
|
509 | 509 | Note that magic functions have lowest priority, so if there's a |
|
510 | 510 | variable whose name collides with that of a magic fn, automagic won't |
|
511 | 511 | work for that function (you get the variable instead). However, if you |
|
512 | 512 | delete the variable (del var), the previously shadowed magic function |
|
513 | 513 | becomes visible to automagic again.""" |
|
514 | 514 | |
|
515 | 515 | rc = self.shell.rc |
|
516 | 516 | arg = parameter_s.lower() |
|
517 | 517 | if parameter_s in ('on','1','true'): |
|
518 | 518 | rc.automagic = True |
|
519 | 519 | elif parameter_s in ('off','0','false'): |
|
520 | 520 | rc.automagic = False |
|
521 | 521 | else: |
|
522 | 522 | rc.automagic = not rc.automagic |
|
523 | 523 | print '\n' + Magic.auto_status[rc.automagic] |
|
524 | 524 | |
|
525 | 525 | |
|
526 | 526 | def magic_autocall(self, parameter_s = ''): |
|
527 | 527 | """Make functions callable without having to type parentheses. |
|
528 | 528 | |
|
529 | 529 | Usage: |
|
530 | 530 | |
|
531 | 531 | %autocall [mode] |
|
532 | 532 | |
|
533 | 533 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
534 | 534 | value is toggled on and off (remembering the previous state). |
|
535 | 535 | |
|
536 | 536 | In more detail, these values mean: |
|
537 | 537 | |
|
538 | 538 | 0 -> fully disabled |
|
539 | 539 | |
|
540 | 540 | 1 -> active, but do not apply if there are no arguments on the line. |
|
541 | 541 | |
|
542 | 542 | In this mode, you get: |
|
543 | 543 | |
|
544 | 544 | In [1]: callable |
|
545 | 545 | Out[1]: <built-in function callable> |
|
546 | 546 | |
|
547 | 547 | In [2]: callable 'hello' |
|
548 | 548 | ------> callable('hello') |
|
549 | 549 | Out[2]: False |
|
550 | 550 | |
|
551 | 551 | 2 -> Active always. Even if no arguments are present, the callable |
|
552 | 552 | object is called: |
|
553 | 553 | |
|
554 | 554 | In [4]: callable |
|
555 | 555 | ------> callable() |
|
556 | 556 | |
|
557 | 557 | Note that even with autocall off, you can still use '/' at the start of |
|
558 | 558 | a line to treat the first argument on the command line as a function |
|
559 | 559 | and add parentheses to it: |
|
560 | 560 | |
|
561 | 561 | In [8]: /str 43 |
|
562 | 562 | ------> str(43) |
|
563 | 563 | Out[8]: '43' |
|
564 | 564 | """ |
|
565 | 565 | |
|
566 | 566 | rc = self.shell.rc |
|
567 | 567 | |
|
568 | 568 | if parameter_s: |
|
569 | 569 | arg = int(parameter_s) |
|
570 | 570 | else: |
|
571 | 571 | arg = 'toggle' |
|
572 | 572 | |
|
573 | 573 | if not arg in (0,1,2,'toggle'): |
|
574 | 574 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
575 | 575 | return |
|
576 | 576 | |
|
577 | 577 | if arg in (0,1,2): |
|
578 | 578 | rc.autocall = arg |
|
579 | 579 | else: # toggle |
|
580 | 580 | if rc.autocall: |
|
581 | 581 | self._magic_state.autocall_save = rc.autocall |
|
582 | 582 | rc.autocall = 0 |
|
583 | 583 | else: |
|
584 | 584 | try: |
|
585 | 585 | rc.autocall = self._magic_state.autocall_save |
|
586 | 586 | except AttributeError: |
|
587 | 587 | rc.autocall = self._magic_state.autocall_save = 1 |
|
588 | 588 | |
|
589 | 589 | print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall] |
|
590 | 590 | |
|
591 | 591 | def magic_system_verbose(self, parameter_s = ''): |
|
592 | 592 | """Set verbose printing of system calls. |
|
593 | 593 | |
|
594 | 594 | If called without an argument, act as a toggle""" |
|
595 | 595 | |
|
596 | 596 | if parameter_s: |
|
597 | 597 | val = bool(eval(parameter_s)) |
|
598 | 598 | else: |
|
599 | 599 | val = None |
|
600 | 600 | |
|
601 | 601 | self.shell.rc_set_toggle('system_verbose',val) |
|
602 | 602 | print "System verbose printing is:",\ |
|
603 | 603 | ['OFF','ON'][self.shell.rc.system_verbose] |
|
604 | 604 | |
|
605 | 605 | |
|
606 | 606 | def magic_page(self, parameter_s=''): |
|
607 | 607 | """Pretty print the object and display it through a pager. |
|
608 | 608 | |
|
609 | 609 | %page [options] OBJECT |
|
610 | 610 | |
|
611 | 611 | If no object is given, use _ (last output). |
|
612 | 612 | |
|
613 | 613 | Options: |
|
614 | 614 | |
|
615 | 615 | -r: page str(object), don't pretty-print it.""" |
|
616 | 616 | |
|
617 | 617 | # After a function contributed by Olivier Aubert, slightly modified. |
|
618 | 618 | |
|
619 | 619 | # Process options/args |
|
620 | 620 | opts,args = self.parse_options(parameter_s,'r') |
|
621 | 621 | raw = 'r' in opts |
|
622 | 622 | |
|
623 | 623 | oname = args and args or '_' |
|
624 | 624 | info = self._ofind(oname) |
|
625 | 625 | if info['found']: |
|
626 | 626 | txt = (raw and str or pformat)( info['obj'] ) |
|
627 | 627 | page(txt) |
|
628 | 628 | else: |
|
629 | 629 | print 'Object `%s` not found' % oname |
|
630 | 630 | |
|
631 | 631 | def magic_profile(self, parameter_s=''): |
|
632 | 632 | """Print your currently active IPyhton profile.""" |
|
633 | 633 | if self.shell.rc.profile: |
|
634 | 634 | printpl('Current IPython profile: $self.shell.rc.profile.') |
|
635 | 635 | else: |
|
636 | 636 | print 'No profile active.' |
|
637 | 637 | |
|
638 | 638 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
639 | 639 | """Provide detailed information about an object. |
|
640 | 640 | |
|
641 | 641 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
642 | 642 | |
|
643 | 643 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
644 | 644 | |
|
645 | 645 | |
|
646 | 646 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
647 | 647 | detail_level = 0 |
|
648 | 648 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
649 | 649 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
650 | 650 | pinfo,qmark1,oname,qmark2 = \ |
|
651 | 651 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
652 | 652 | if pinfo or qmark1 or qmark2: |
|
653 | 653 | detail_level = 1 |
|
654 | 654 | if "*" in oname: |
|
655 | 655 | self.magic_psearch(oname) |
|
656 | 656 | else: |
|
657 | 657 | self._inspect('pinfo', oname, detail_level=detail_level, |
|
658 | 658 | namespaces=namespaces) |
|
659 | 659 | |
|
660 | 660 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
661 | 661 | """Print the definition header for any callable object. |
|
662 | 662 | |
|
663 | 663 | If the object is a class, print the constructor information.""" |
|
664 | 664 | self._inspect('pdef',parameter_s, namespaces) |
|
665 | 665 | |
|
666 | 666 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
667 | 667 | """Print the docstring for an object. |
|
668 | 668 | |
|
669 | 669 | If the given object is a class, it will print both the class and the |
|
670 | 670 | constructor docstrings.""" |
|
671 | 671 | self._inspect('pdoc',parameter_s, namespaces) |
|
672 | 672 | |
|
673 | 673 | def magic_psource(self, parameter_s='', namespaces=None): |
|
674 | 674 | """Print (or run through pager) the source code for an object.""" |
|
675 | 675 | self._inspect('psource',parameter_s, namespaces) |
|
676 | 676 | |
|
677 | 677 | def magic_pfile(self, parameter_s=''): |
|
678 | 678 | """Print (or run through pager) the file where an object is defined. |
|
679 | 679 | |
|
680 | 680 | The file opens at the line where the object definition begins. IPython |
|
681 | 681 | will honor the environment variable PAGER if set, and otherwise will |
|
682 | 682 | do its best to print the file in a convenient form. |
|
683 | 683 | |
|
684 | 684 | If the given argument is not an object currently defined, IPython will |
|
685 | 685 | try to interpret it as a filename (automatically adding a .py extension |
|
686 | 686 | if needed). You can thus use %pfile as a syntax highlighting code |
|
687 | 687 | viewer.""" |
|
688 | 688 | |
|
689 | 689 | # first interpret argument as an object name |
|
690 | 690 | out = self._inspect('pfile',parameter_s) |
|
691 | 691 | # if not, try the input as a filename |
|
692 | 692 | if out == 'not found': |
|
693 | 693 | try: |
|
694 | 694 | filename = get_py_filename(parameter_s) |
|
695 | 695 | except IOError,msg: |
|
696 | 696 | print msg |
|
697 | 697 | return |
|
698 | 698 | page(self.shell.inspector.format(file(filename).read())) |
|
699 | 699 | |
|
700 | 700 | def _inspect(self,meth,oname,namespaces=None,**kw): |
|
701 | 701 | """Generic interface to the inspector system. |
|
702 | 702 | |
|
703 | 703 | This function is meant to be called by pdef, pdoc & friends.""" |
|
704 | 704 | |
|
705 | 705 | #oname = oname.strip() |
|
706 | 706 | #print '1- oname: <%r>' % oname # dbg |
|
707 | 707 | try: |
|
708 | 708 | oname = oname.strip().encode('ascii') |
|
709 | 709 | #print '2- oname: <%r>' % oname # dbg |
|
710 | 710 | except UnicodeEncodeError: |
|
711 | 711 | print 'Python identifiers can only contain ascii characters.' |
|
712 | 712 | return 'not found' |
|
713 | 713 | |
|
714 | 714 | info = Struct(self._ofind(oname, namespaces)) |
|
715 | 715 | |
|
716 | 716 | if info.found: |
|
717 | 717 | try: |
|
718 | 718 | IPython.generics.inspect_object(info.obj) |
|
719 | 719 | return |
|
720 | 720 | except IPython.ipapi.TryNext: |
|
721 | 721 | pass |
|
722 | 722 | # Get the docstring of the class property if it exists. |
|
723 | 723 | path = oname.split('.') |
|
724 | 724 | root = '.'.join(path[:-1]) |
|
725 | 725 | if info.parent is not None: |
|
726 | 726 | try: |
|
727 | 727 | target = getattr(info.parent, '__class__') |
|
728 | 728 | # The object belongs to a class instance. |
|
729 | 729 | try: |
|
730 | 730 | target = getattr(target, path[-1]) |
|
731 | 731 | # The class defines the object. |
|
732 | 732 | if isinstance(target, property): |
|
733 | 733 | oname = root + '.__class__.' + path[-1] |
|
734 | 734 | info = Struct(self._ofind(oname)) |
|
735 | 735 | except AttributeError: pass |
|
736 | 736 | except AttributeError: pass |
|
737 | 737 | |
|
738 | 738 | pmethod = getattr(self.shell.inspector,meth) |
|
739 | 739 | formatter = info.ismagic and self.format_screen or None |
|
740 | 740 | if meth == 'pdoc': |
|
741 | 741 | pmethod(info.obj,oname,formatter) |
|
742 | 742 | elif meth == 'pinfo': |
|
743 | 743 | pmethod(info.obj,oname,formatter,info,**kw) |
|
744 | 744 | else: |
|
745 | 745 | pmethod(info.obj,oname) |
|
746 | 746 | else: |
|
747 | 747 | print 'Object `%s` not found.' % oname |
|
748 | 748 | return 'not found' # so callers can take other action |
|
749 | 749 | |
|
750 | 750 | def magic_psearch(self, parameter_s=''): |
|
751 | 751 | """Search for object in namespaces by wildcard. |
|
752 | 752 | |
|
753 | 753 | %psearch [options] PATTERN [OBJECT TYPE] |
|
754 | 754 | |
|
755 | 755 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
756 | 756 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
757 | 757 | rest of the command line must be unchanged (options come first), so |
|
758 | 758 | for example the following forms are equivalent |
|
759 | 759 | |
|
760 | 760 | %psearch -i a* function |
|
761 | 761 | -i a* function? |
|
762 | 762 | ?-i a* function |
|
763 | 763 | |
|
764 | 764 | Arguments: |
|
765 | 765 | |
|
766 | 766 | PATTERN |
|
767 | 767 | |
|
768 | 768 | where PATTERN is a string containing * as a wildcard similar to its |
|
769 | 769 | use in a shell. The pattern is matched in all namespaces on the |
|
770 | 770 | search path. By default objects starting with a single _ are not |
|
771 | 771 | matched, many IPython generated objects have a single |
|
772 | 772 | underscore. The default is case insensitive matching. Matching is |
|
773 | 773 | also done on the attributes of objects and not only on the objects |
|
774 | 774 | in a module. |
|
775 | 775 | |
|
776 | 776 | [OBJECT TYPE] |
|
777 | 777 | |
|
778 | 778 | Is the name of a python type from the types module. The name is |
|
779 | 779 | given in lowercase without the ending type, ex. StringType is |
|
780 | 780 | written string. By adding a type here only objects matching the |
|
781 | 781 | given type are matched. Using all here makes the pattern match all |
|
782 | 782 | types (this is the default). |
|
783 | 783 | |
|
784 | 784 | Options: |
|
785 | 785 | |
|
786 | 786 | -a: makes the pattern match even objects whose names start with a |
|
787 | 787 | single underscore. These names are normally ommitted from the |
|
788 | 788 | search. |
|
789 | 789 | |
|
790 | 790 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
791 | 791 | these options is given, the default is read from your ipythonrc |
|
792 | 792 | file. The option name which sets this value is |
|
793 | 793 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
794 | 794 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
795 | 795 | search. |
|
796 | 796 | |
|
797 | 797 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
798 | 798 | specifiy can be searched in any of the following namespaces: |
|
799 | 799 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
800 | 800 | 'builtin' and 'user' are the search defaults. Note that you should |
|
801 | 801 | not use quotes when specifying namespaces. |
|
802 | 802 | |
|
803 | 803 | 'Builtin' contains the python module builtin, 'user' contains all |
|
804 | 804 | user data, 'alias' only contain the shell aliases and no python |
|
805 | 805 | objects, 'internal' contains objects used by IPython. The |
|
806 | 806 | 'user_global' namespace is only used by embedded IPython instances, |
|
807 | 807 | and it contains module-level globals. You can add namespaces to the |
|
808 | 808 | search with -s or exclude them with -e (these options can be given |
|
809 | 809 | more than once). |
|
810 | 810 | |
|
811 | 811 | Examples: |
|
812 | 812 | |
|
813 | 813 | %psearch a* -> objects beginning with an a |
|
814 | 814 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
815 | 815 | %psearch a* function -> all functions beginning with an a |
|
816 | 816 | %psearch re.e* -> objects beginning with an e in module re |
|
817 | 817 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
818 | 818 | %psearch r*.* string -> all strings in modules beginning with r |
|
819 | 819 | |
|
820 | 820 | Case sensitve search: |
|
821 | 821 | |
|
822 | 822 | %psearch -c a* list all object beginning with lower case a |
|
823 | 823 | |
|
824 | 824 | Show objects beginning with a single _: |
|
825 | 825 | |
|
826 | 826 | %psearch -a _* list objects beginning with a single underscore""" |
|
827 | 827 | try: |
|
828 | 828 | parameter_s = parameter_s.encode('ascii') |
|
829 | 829 | except UnicodeEncodeError: |
|
830 | 830 | print 'Python identifiers can only contain ascii characters.' |
|
831 | 831 | return |
|
832 | 832 | |
|
833 | 833 | # default namespaces to be searched |
|
834 | 834 | def_search = ['user','builtin'] |
|
835 | 835 | |
|
836 | 836 | # Process options/args |
|
837 | 837 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
838 | 838 | opt = opts.get |
|
839 | 839 | shell = self.shell |
|
840 | 840 | psearch = shell.inspector.psearch |
|
841 | 841 | |
|
842 | 842 | # select case options |
|
843 | 843 | if opts.has_key('i'): |
|
844 | 844 | ignore_case = True |
|
845 | 845 | elif opts.has_key('c'): |
|
846 | 846 | ignore_case = False |
|
847 | 847 | else: |
|
848 | 848 | ignore_case = not shell.rc.wildcards_case_sensitive |
|
849 | 849 | |
|
850 | 850 | # Build list of namespaces to search from user options |
|
851 | 851 | def_search.extend(opt('s',[])) |
|
852 | 852 | ns_exclude = ns_exclude=opt('e',[]) |
|
853 | 853 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
854 | 854 | |
|
855 | 855 | # Call the actual search |
|
856 | 856 | try: |
|
857 | 857 | psearch(args,shell.ns_table,ns_search, |
|
858 | 858 | show_all=opt('a'),ignore_case=ignore_case) |
|
859 | 859 | except: |
|
860 | 860 | shell.showtraceback() |
|
861 | 861 | |
|
862 | 862 | def magic_who_ls(self, parameter_s=''): |
|
863 | 863 | """Return a sorted list of all interactive variables. |
|
864 | 864 | |
|
865 | 865 | If arguments are given, only variables of types matching these |
|
866 | 866 | arguments are returned.""" |
|
867 | 867 | |
|
868 | 868 | user_ns = self.shell.user_ns |
|
869 | 869 | internal_ns = self.shell.internal_ns |
|
870 | 870 | user_config_ns = self.shell.user_config_ns |
|
871 | 871 | out = [] |
|
872 | 872 | typelist = parameter_s.split() |
|
873 | 873 | |
|
874 | 874 | for i in user_ns: |
|
875 | 875 | if not (i.startswith('_') or i.startswith('_i')) \ |
|
876 | 876 | and not (i in internal_ns or i in user_config_ns): |
|
877 | 877 | if typelist: |
|
878 | 878 | if type(user_ns[i]).__name__ in typelist: |
|
879 | 879 | out.append(i) |
|
880 | 880 | else: |
|
881 | 881 | out.append(i) |
|
882 | 882 | out.sort() |
|
883 | 883 | return out |
|
884 | 884 | |
|
885 | 885 | def magic_who(self, parameter_s=''): |
|
886 | 886 | """Print all interactive variables, with some minimal formatting. |
|
887 | 887 | |
|
888 | 888 | If any arguments are given, only variables whose type matches one of |
|
889 | 889 | these are printed. For example: |
|
890 | 890 | |
|
891 | 891 | %who function str |
|
892 | 892 | |
|
893 | 893 | will only list functions and strings, excluding all other types of |
|
894 | 894 | variables. To find the proper type names, simply use type(var) at a |
|
895 | 895 | command line to see how python prints type names. For example: |
|
896 | 896 | |
|
897 | 897 | In [1]: type('hello')\\ |
|
898 | 898 | Out[1]: <type 'str'> |
|
899 | 899 | |
|
900 | 900 | indicates that the type name for strings is 'str'. |
|
901 | 901 | |
|
902 | 902 | %who always excludes executed names loaded through your configuration |
|
903 | 903 | file and things which are internal to IPython. |
|
904 | 904 | |
|
905 | 905 | This is deliberate, as typically you may load many modules and the |
|
906 | 906 | purpose of %who is to show you only what you've manually defined.""" |
|
907 | 907 | |
|
908 | 908 | varlist = self.magic_who_ls(parameter_s) |
|
909 | 909 | if not varlist: |
|
910 | 910 | if parameter_s: |
|
911 | 911 | print 'No variables match your requested type.' |
|
912 | 912 | else: |
|
913 | 913 | print 'Interactive namespace is empty.' |
|
914 | 914 | return |
|
915 | 915 | |
|
916 | 916 | # if we have variables, move on... |
|
917 | 917 | count = 0 |
|
918 | 918 | for i in varlist: |
|
919 | 919 | print i+'\t', |
|
920 | 920 | count += 1 |
|
921 | 921 | if count > 8: |
|
922 | 922 | count = 0 |
|
923 | 923 | |
|
924 | 924 | |
|
925 | 925 | |
|
926 | 926 | def magic_whos(self, parameter_s=''): |
|
927 | 927 | """Like %who, but gives some extra information about each variable. |
|
928 | 928 | |
|
929 | 929 | The same type filtering of %who can be applied here. |
|
930 | 930 | |
|
931 | 931 | For all variables, the type is printed. Additionally it prints: |
|
932 | 932 | |
|
933 | 933 | - For {},[],(): their length. |
|
934 | 934 | |
|
935 | 935 | - For numpy and Numeric arrays, a summary with shape, number of |
|
936 | 936 | elements, typecode and size in memory. |
|
937 | 937 | |
|
938 | 938 | - Everything else: a string representation, snipping their middle if |
|
939 | 939 | too long.""" |
|
940 | 940 | |
|
941 | 941 | varnames = self.magic_who_ls(parameter_s) |
|
942 | 942 | if not varnames: |
|
943 | 943 | if parameter_s: |
|
944 | 944 | print 'No variables match your requested type.' |
|
945 | 945 | else: |
|
946 | 946 | print 'Interactive namespace is empty.' |
|
947 | 947 | return |
|
948 | 948 | |
|
949 | 949 | # if we have variables, move on... |
|
950 | 950 | |
|
951 | 951 | # for these types, show len() instead of data: |
|
952 | 952 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
953 | 953 | |
|
954 | 954 | # for numpy/Numeric arrays, display summary info |
|
955 | 955 | try: |
|
956 | 956 | import numpy |
|
957 | 957 | except ImportError: |
|
958 | 958 | ndarray_type = None |
|
959 | 959 | else: |
|
960 | 960 | ndarray_type = numpy.ndarray.__name__ |
|
961 | 961 | try: |
|
962 | 962 | import Numeric |
|
963 | 963 | except ImportError: |
|
964 | 964 | array_type = None |
|
965 | 965 | else: |
|
966 | 966 | array_type = Numeric.ArrayType.__name__ |
|
967 | 967 | |
|
968 | 968 | # Find all variable names and types so we can figure out column sizes |
|
969 | 969 | def get_vars(i): |
|
970 | 970 | return self.shell.user_ns[i] |
|
971 | 971 | |
|
972 | 972 | # some types are well known and can be shorter |
|
973 | 973 | abbrevs = {'IPython.macro.Macro' : 'Macro'} |
|
974 | 974 | def type_name(v): |
|
975 | 975 | tn = type(v).__name__ |
|
976 | 976 | return abbrevs.get(tn,tn) |
|
977 | 977 | |
|
978 | 978 | varlist = map(get_vars,varnames) |
|
979 | 979 | |
|
980 | 980 | typelist = [] |
|
981 | 981 | for vv in varlist: |
|
982 | 982 | tt = type_name(vv) |
|
983 | 983 | |
|
984 | 984 | if tt=='instance': |
|
985 | 985 | typelist.append( abbrevs.get(str(vv.__class__), |
|
986 | 986 | str(vv.__class__))) |
|
987 | 987 | else: |
|
988 | 988 | typelist.append(tt) |
|
989 | 989 | |
|
990 | 990 | # column labels and # of spaces as separator |
|
991 | 991 | varlabel = 'Variable' |
|
992 | 992 | typelabel = 'Type' |
|
993 | 993 | datalabel = 'Data/Info' |
|
994 | 994 | colsep = 3 |
|
995 | 995 | # variable format strings |
|
996 | 996 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
997 | 997 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
998 | 998 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
999 | 999 | # find the size of the columns to format the output nicely |
|
1000 | 1000 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
1001 | 1001 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
1002 | 1002 | # table header |
|
1003 | 1003 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
1004 | 1004 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
1005 | 1005 | # and the table itself |
|
1006 | 1006 | kb = 1024 |
|
1007 | 1007 | Mb = 1048576 # kb**2 |
|
1008 | 1008 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
1009 | 1009 | print itpl(vformat), |
|
1010 | 1010 | if vtype in seq_types: |
|
1011 | 1011 | print len(var) |
|
1012 | 1012 | elif vtype in [array_type,ndarray_type]: |
|
1013 | 1013 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
1014 | 1014 | if vtype==ndarray_type: |
|
1015 | 1015 | # numpy |
|
1016 | 1016 | vsize = var.size |
|
1017 | 1017 | vbytes = vsize*var.itemsize |
|
1018 | 1018 | vdtype = var.dtype |
|
1019 | 1019 | else: |
|
1020 | 1020 | # Numeric |
|
1021 | 1021 | vsize = Numeric.size(var) |
|
1022 | 1022 | vbytes = vsize*var.itemsize() |
|
1023 | 1023 | vdtype = var.typecode() |
|
1024 | 1024 | |
|
1025 | 1025 | if vbytes < 100000: |
|
1026 | 1026 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
1027 | 1027 | else: |
|
1028 | 1028 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
1029 | 1029 | if vbytes < Mb: |
|
1030 | 1030 | print '(%s kb)' % (vbytes/kb,) |
|
1031 | 1031 | else: |
|
1032 | 1032 | print '(%s Mb)' % (vbytes/Mb,) |
|
1033 | 1033 | else: |
|
1034 | 1034 | try: |
|
1035 | 1035 | vstr = str(var) |
|
1036 | 1036 | except UnicodeEncodeError: |
|
1037 | 1037 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
1038 | 1038 | 'backslashreplace') |
|
1039 | 1039 | vstr = vstr.replace('\n','\\n') |
|
1040 | 1040 | if len(vstr) < 50: |
|
1041 | 1041 | print vstr |
|
1042 | 1042 | else: |
|
1043 | 1043 | printpl(vfmt_short) |
|
1044 | 1044 | |
|
1045 | 1045 | def magic_reset(self, parameter_s=''): |
|
1046 | 1046 | """Resets the namespace by removing all names defined by the user. |
|
1047 | 1047 | |
|
1048 | 1048 | Input/Output history are left around in case you need them.""" |
|
1049 | 1049 | |
|
1050 | 1050 | ans = self.shell.ask_yes_no( |
|
1051 | 1051 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1052 | 1052 | if not ans: |
|
1053 | 1053 | print 'Nothing done.' |
|
1054 | 1054 | return |
|
1055 | 1055 | user_ns = self.shell.user_ns |
|
1056 | 1056 | for i in self.magic_who_ls(): |
|
1057 | 1057 | del(user_ns[i]) |
|
1058 | 1058 | |
|
1059 | 1059 | # Also flush the private list of module references kept for script |
|
1060 | 1060 | # execution protection |
|
1061 | 1061 | self.shell._user_main_modules[:] = [] |
|
1062 | 1062 | |
|
1063 | 1063 | def magic_logstart(self,parameter_s=''): |
|
1064 | 1064 | """Start logging anywhere in a session. |
|
1065 | 1065 | |
|
1066 | 1066 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1067 | 1067 | |
|
1068 | 1068 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1069 | 1069 | current directory, in 'rotate' mode (see below). |
|
1070 | 1070 | |
|
1071 | 1071 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1072 | 1072 | history up to that point and then continues logging. |
|
1073 | 1073 | |
|
1074 | 1074 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1075 | 1075 | of (note that the modes are given unquoted):\\ |
|
1076 | 1076 | append: well, that says it.\\ |
|
1077 | 1077 | backup: rename (if exists) to name~ and start name.\\ |
|
1078 | 1078 | global: single logfile in your home dir, appended to.\\ |
|
1079 | 1079 | over : overwrite existing log.\\ |
|
1080 | 1080 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1081 | 1081 | |
|
1082 | 1082 | Options: |
|
1083 | 1083 | |
|
1084 | 1084 | -o: log also IPython's output. In this mode, all commands which |
|
1085 | 1085 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1086 | 1086 | their corresponding input line. The output lines are always |
|
1087 | 1087 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1088 | 1088 | Python code. |
|
1089 | 1089 | |
|
1090 | 1090 | Since this marker is always the same, filtering only the output from |
|
1091 | 1091 | a log is very easy, using for example a simple awk call: |
|
1092 | 1092 | |
|
1093 | 1093 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1094 | 1094 | |
|
1095 | 1095 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1096 | 1096 | input, so that user lines are logged in their final form, converted |
|
1097 | 1097 | into valid Python. For example, %Exit is logged as |
|
1098 | 1098 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1099 | 1099 | exactly as typed, with no transformations applied. |
|
1100 | 1100 | |
|
1101 | 1101 | -t: put timestamps before each input line logged (these are put in |
|
1102 | 1102 | comments).""" |
|
1103 | 1103 | |
|
1104 | 1104 | opts,par = self.parse_options(parameter_s,'ort') |
|
1105 | 1105 | log_output = 'o' in opts |
|
1106 | 1106 | log_raw_input = 'r' in opts |
|
1107 | 1107 | timestamp = 't' in opts |
|
1108 | 1108 | |
|
1109 | 1109 | rc = self.shell.rc |
|
1110 | 1110 | logger = self.shell.logger |
|
1111 | 1111 | |
|
1112 | 1112 | # if no args are given, the defaults set in the logger constructor by |
|
1113 | 1113 | # ipytohn remain valid |
|
1114 | 1114 | if par: |
|
1115 | 1115 | try: |
|
1116 | 1116 | logfname,logmode = par.split() |
|
1117 | 1117 | except: |
|
1118 | 1118 | logfname = par |
|
1119 | 1119 | logmode = 'backup' |
|
1120 | 1120 | else: |
|
1121 | 1121 | logfname = logger.logfname |
|
1122 | 1122 | logmode = logger.logmode |
|
1123 | 1123 | # put logfname into rc struct as if it had been called on the command |
|
1124 | 1124 | # line, so it ends up saved in the log header Save it in case we need |
|
1125 | 1125 | # to restore it... |
|
1126 | 1126 | old_logfile = rc.opts.get('logfile','') |
|
1127 | 1127 | if logfname: |
|
1128 | 1128 | logfname = os.path.expanduser(logfname) |
|
1129 | 1129 | rc.opts.logfile = logfname |
|
1130 | 1130 | loghead = self.shell.loghead_tpl % (rc.opts,rc.args) |
|
1131 | 1131 | try: |
|
1132 | 1132 | started = logger.logstart(logfname,loghead,logmode, |
|
1133 | 1133 | log_output,timestamp,log_raw_input) |
|
1134 | 1134 | except: |
|
1135 | 1135 | rc.opts.logfile = old_logfile |
|
1136 | 1136 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1137 | 1137 | else: |
|
1138 | 1138 | # log input history up to this point, optionally interleaving |
|
1139 | 1139 | # output if requested |
|
1140 | 1140 | |
|
1141 | 1141 | if timestamp: |
|
1142 | 1142 | # disable timestamping for the previous history, since we've |
|
1143 | 1143 | # lost those already (no time machine here). |
|
1144 | 1144 | logger.timestamp = False |
|
1145 | 1145 | |
|
1146 | 1146 | if log_raw_input: |
|
1147 | 1147 | input_hist = self.shell.input_hist_raw |
|
1148 | 1148 | else: |
|
1149 | 1149 | input_hist = self.shell.input_hist |
|
1150 | 1150 | |
|
1151 | 1151 | if log_output: |
|
1152 | 1152 | log_write = logger.log_write |
|
1153 | 1153 | output_hist = self.shell.output_hist |
|
1154 | 1154 | for n in range(1,len(input_hist)-1): |
|
1155 | 1155 | log_write(input_hist[n].rstrip()) |
|
1156 | 1156 | if n in output_hist: |
|
1157 | 1157 | log_write(repr(output_hist[n]),'output') |
|
1158 | 1158 | else: |
|
1159 | 1159 | logger.log_write(input_hist[1:]) |
|
1160 | 1160 | if timestamp: |
|
1161 | 1161 | # re-enable timestamping |
|
1162 | 1162 | logger.timestamp = True |
|
1163 | 1163 | |
|
1164 | 1164 | print ('Activating auto-logging. ' |
|
1165 | 1165 | 'Current session state plus future input saved.') |
|
1166 | 1166 | logger.logstate() |
|
1167 | 1167 | |
|
1168 | 1168 | def magic_logstop(self,parameter_s=''): |
|
1169 | 1169 | """Fully stop logging and close log file. |
|
1170 | 1170 | |
|
1171 | 1171 | In order to start logging again, a new %logstart call needs to be made, |
|
1172 | 1172 | possibly (though not necessarily) with a new filename, mode and other |
|
1173 | 1173 | options.""" |
|
1174 | 1174 | self.logger.logstop() |
|
1175 | 1175 | |
|
1176 | 1176 | def magic_logoff(self,parameter_s=''): |
|
1177 | 1177 | """Temporarily stop logging. |
|
1178 | 1178 | |
|
1179 | 1179 | You must have previously started logging.""" |
|
1180 | 1180 | self.shell.logger.switch_log(0) |
|
1181 | 1181 | |
|
1182 | 1182 | def magic_logon(self,parameter_s=''): |
|
1183 | 1183 | """Restart logging. |
|
1184 | 1184 | |
|
1185 | 1185 | This function is for restarting logging which you've temporarily |
|
1186 | 1186 | stopped with %logoff. For starting logging for the first time, you |
|
1187 | 1187 | must use the %logstart function, which allows you to specify an |
|
1188 | 1188 | optional log filename.""" |
|
1189 | 1189 | |
|
1190 | 1190 | self.shell.logger.switch_log(1) |
|
1191 | 1191 | |
|
1192 | 1192 | def magic_logstate(self,parameter_s=''): |
|
1193 | 1193 | """Print the status of the logging system.""" |
|
1194 | 1194 | |
|
1195 | 1195 | self.shell.logger.logstate() |
|
1196 | 1196 | |
|
1197 | 1197 | def magic_pdb(self, parameter_s=''): |
|
1198 | 1198 | """Control the automatic calling of the pdb interactive debugger. |
|
1199 | 1199 | |
|
1200 | 1200 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1201 | 1201 | argument it works as a toggle. |
|
1202 | 1202 | |
|
1203 | 1203 | When an exception is triggered, IPython can optionally call the |
|
1204 | 1204 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1205 | 1205 | this feature on and off. |
|
1206 | 1206 | |
|
1207 | 1207 | The initial state of this feature is set in your ipythonrc |
|
1208 | 1208 | configuration file (the variable is called 'pdb'). |
|
1209 | 1209 | |
|
1210 | 1210 | If you want to just activate the debugger AFTER an exception has fired, |
|
1211 | 1211 | without having to type '%pdb on' and rerunning your code, you can use |
|
1212 | 1212 | the %debug magic.""" |
|
1213 | 1213 | |
|
1214 | 1214 | par = parameter_s.strip().lower() |
|
1215 | 1215 | |
|
1216 | 1216 | if par: |
|
1217 | 1217 | try: |
|
1218 | 1218 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1219 | 1219 | except KeyError: |
|
1220 | 1220 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1221 | 1221 | 'or nothing for a toggle.') |
|
1222 | 1222 | return |
|
1223 | 1223 | else: |
|
1224 | 1224 | # toggle |
|
1225 | 1225 | new_pdb = not self.shell.call_pdb |
|
1226 | 1226 | |
|
1227 | 1227 | # set on the shell |
|
1228 | 1228 | self.shell.call_pdb = new_pdb |
|
1229 | 1229 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1230 | 1230 | |
|
1231 | 1231 | def magic_debug(self, parameter_s=''): |
|
1232 | 1232 | """Activate the interactive debugger in post-mortem mode. |
|
1233 | 1233 | |
|
1234 | 1234 | If an exception has just occurred, this lets you inspect its stack |
|
1235 | 1235 | frames interactively. Note that this will always work only on the last |
|
1236 | 1236 | traceback that occurred, so you must call this quickly after an |
|
1237 | 1237 | exception that you wish to inspect has fired, because if another one |
|
1238 | 1238 | occurs, it clobbers the previous one. |
|
1239 | 1239 | |
|
1240 | 1240 | If you want IPython to automatically do this on every exception, see |
|
1241 | 1241 | the %pdb magic for more details. |
|
1242 | 1242 | """ |
|
1243 | 1243 | |
|
1244 | 1244 | self.shell.debugger(force=True) |
|
1245 | 1245 | |
|
1246 | 1246 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1247 | 1247 | opts=None,arg_lst=None,prog_ns=None): |
|
1248 | 1248 | |
|
1249 | 1249 | """Run a statement through the python code profiler. |
|
1250 | 1250 | |
|
1251 | 1251 | Usage:\\ |
|
1252 | 1252 | %prun [options] statement |
|
1253 | 1253 | |
|
1254 | 1254 | The given statement (which doesn't require quote marks) is run via the |
|
1255 | 1255 | python profiler in a manner similar to the profile.run() function. |
|
1256 | 1256 | Namespaces are internally managed to work correctly; profile.run |
|
1257 | 1257 | cannot be used in IPython because it makes certain assumptions about |
|
1258 | 1258 | namespaces which do not hold under IPython. |
|
1259 | 1259 | |
|
1260 | 1260 | Options: |
|
1261 | 1261 | |
|
1262 | 1262 | -l <limit>: you can place restrictions on what or how much of the |
|
1263 | 1263 | profile gets printed. The limit value can be: |
|
1264 | 1264 | |
|
1265 | 1265 | * A string: only information for function names containing this string |
|
1266 | 1266 | is printed. |
|
1267 | 1267 | |
|
1268 | 1268 | * An integer: only these many lines are printed. |
|
1269 | 1269 | |
|
1270 | 1270 | * A float (between 0 and 1): this fraction of the report is printed |
|
1271 | 1271 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1272 | 1272 | |
|
1273 | 1273 | You can combine several limits with repeated use of the option. For |
|
1274 | 1274 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1275 | 1275 | information about class constructors. |
|
1276 | 1276 | |
|
1277 | 1277 | -r: return the pstats.Stats object generated by the profiling. This |
|
1278 | 1278 | object has all the information about the profile in it, and you can |
|
1279 | 1279 | later use it for further analysis or in other functions. |
|
1280 | 1280 | |
|
1281 | 1281 | -s <key>: sort profile by given key. You can provide more than one key |
|
1282 | 1282 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1283 | 1283 | default sorting key is 'time'. |
|
1284 | 1284 | |
|
1285 | 1285 | The following is copied verbatim from the profile documentation |
|
1286 | 1286 | referenced below: |
|
1287 | 1287 | |
|
1288 | 1288 | When more than one key is provided, additional keys are used as |
|
1289 | 1289 | secondary criteria when the there is equality in all keys selected |
|
1290 | 1290 | before them. |
|
1291 | 1291 | |
|
1292 | 1292 | Abbreviations can be used for any key names, as long as the |
|
1293 | 1293 | abbreviation is unambiguous. The following are the keys currently |
|
1294 | 1294 | defined: |
|
1295 | 1295 | |
|
1296 | 1296 | Valid Arg Meaning\\ |
|
1297 | 1297 | "calls" call count\\ |
|
1298 | 1298 | "cumulative" cumulative time\\ |
|
1299 | 1299 | "file" file name\\ |
|
1300 | 1300 | "module" file name\\ |
|
1301 | 1301 | "pcalls" primitive call count\\ |
|
1302 | 1302 | "line" line number\\ |
|
1303 | 1303 | "name" function name\\ |
|
1304 | 1304 | "nfl" name/file/line\\ |
|
1305 | 1305 | "stdname" standard name\\ |
|
1306 | 1306 | "time" internal time |
|
1307 | 1307 | |
|
1308 | 1308 | Note that all sorts on statistics are in descending order (placing |
|
1309 | 1309 | most time consuming items first), where as name, file, and line number |
|
1310 | 1310 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1311 | 1311 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1312 | 1312 | sort of the name as printed, which means that the embedded line |
|
1313 | 1313 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1314 | 1314 | would (if the file names were the same) appear in the string order |
|
1315 | 1315 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1316 | 1316 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1317 | 1317 | sort_stats("name", "file", "line"). |
|
1318 | 1318 | |
|
1319 | 1319 | -T <filename>: save profile results as shown on screen to a text |
|
1320 | 1320 | file. The profile is still shown on screen. |
|
1321 | 1321 | |
|
1322 | 1322 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1323 | 1323 | filename. This data is in a format understod by the pstats module, and |
|
1324 | 1324 | is generated by a call to the dump_stats() method of profile |
|
1325 | 1325 | objects. The profile is still shown on screen. |
|
1326 | 1326 | |
|
1327 | 1327 | If you want to run complete programs under the profiler's control, use |
|
1328 | 1328 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1329 | 1329 | contains profiler specific options as described here. |
|
1330 | 1330 | |
|
1331 | 1331 | You can read the complete documentation for the profile module with:\\ |
|
1332 | 1332 | In [1]: import profile; profile.help() """ |
|
1333 | 1333 | |
|
1334 | 1334 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1335 | 1335 | # protect user quote marks |
|
1336 | 1336 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1337 | 1337 | |
|
1338 | 1338 | if user_mode: # regular user call |
|
1339 | 1339 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1340 | 1340 | list_all=1) |
|
1341 | 1341 | namespace = self.shell.user_ns |
|
1342 | 1342 | else: # called to run a program by %run -p |
|
1343 | 1343 | try: |
|
1344 | 1344 | filename = get_py_filename(arg_lst[0]) |
|
1345 | 1345 | except IOError,msg: |
|
1346 | 1346 | error(msg) |
|
1347 | 1347 | return |
|
1348 | 1348 | |
|
1349 | 1349 | arg_str = 'execfile(filename,prog_ns)' |
|
1350 | 1350 | namespace = locals() |
|
1351 | 1351 | |
|
1352 | 1352 | opts.merge(opts_def) |
|
1353 | 1353 | |
|
1354 | 1354 | prof = profile.Profile() |
|
1355 | 1355 | try: |
|
1356 | 1356 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1357 | 1357 | sys_exit = '' |
|
1358 | 1358 | except SystemExit: |
|
1359 | 1359 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1360 | 1360 | |
|
1361 | 1361 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1362 | 1362 | |
|
1363 | 1363 | lims = opts.l |
|
1364 | 1364 | if lims: |
|
1365 | 1365 | lims = [] # rebuild lims with ints/floats/strings |
|
1366 | 1366 | for lim in opts.l: |
|
1367 | 1367 | try: |
|
1368 | 1368 | lims.append(int(lim)) |
|
1369 | 1369 | except ValueError: |
|
1370 | 1370 | try: |
|
1371 | 1371 | lims.append(float(lim)) |
|
1372 | 1372 | except ValueError: |
|
1373 | 1373 | lims.append(lim) |
|
1374 | 1374 | |
|
1375 | 1375 | # Trap output. |
|
1376 | 1376 | stdout_trap = StringIO() |
|
1377 | 1377 | |
|
1378 | 1378 | if hasattr(stats,'stream'): |
|
1379 | 1379 | # In newer versions of python, the stats object has a 'stream' |
|
1380 | 1380 | # attribute to write into. |
|
1381 | 1381 | stats.stream = stdout_trap |
|
1382 | 1382 | stats.print_stats(*lims) |
|
1383 | 1383 | else: |
|
1384 | 1384 | # For older versions, we manually redirect stdout during printing |
|
1385 | 1385 | sys_stdout = sys.stdout |
|
1386 | 1386 | try: |
|
1387 | 1387 | sys.stdout = stdout_trap |
|
1388 | 1388 | stats.print_stats(*lims) |
|
1389 | 1389 | finally: |
|
1390 | 1390 | sys.stdout = sys_stdout |
|
1391 | 1391 | |
|
1392 | 1392 | output = stdout_trap.getvalue() |
|
1393 | 1393 | output = output.rstrip() |
|
1394 | 1394 | |
|
1395 | 1395 | page(output,screen_lines=self.shell.rc.screen_length) |
|
1396 | 1396 | print sys_exit, |
|
1397 | 1397 | |
|
1398 | 1398 | dump_file = opts.D[0] |
|
1399 | 1399 | text_file = opts.T[0] |
|
1400 | 1400 | if dump_file: |
|
1401 | 1401 | prof.dump_stats(dump_file) |
|
1402 | 1402 | print '\n*** Profile stats marshalled to file',\ |
|
1403 | 1403 | `dump_file`+'.',sys_exit |
|
1404 | 1404 | if text_file: |
|
1405 | 1405 | pfile = file(text_file,'w') |
|
1406 | 1406 | pfile.write(output) |
|
1407 | 1407 | pfile.close() |
|
1408 | 1408 | print '\n*** Profile printout saved to text file',\ |
|
1409 | 1409 | `text_file`+'.',sys_exit |
|
1410 | 1410 | |
|
1411 | 1411 | if opts.has_key('r'): |
|
1412 | 1412 | return stats |
|
1413 | 1413 | else: |
|
1414 | 1414 | return None |
|
1415 | 1415 | |
|
1416 | 1416 | def magic_run(self, parameter_s ='',runner=None): |
|
1417 | 1417 | """Run the named file inside IPython as a program. |
|
1418 | 1418 | |
|
1419 | 1419 | Usage:\\ |
|
1420 | 1420 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1421 | 1421 | |
|
1422 | 1422 | Parameters after the filename are passed as command-line arguments to |
|
1423 | 1423 | the program (put in sys.argv). Then, control returns to IPython's |
|
1424 | 1424 | prompt. |
|
1425 | 1425 | |
|
1426 | 1426 | This is similar to running at a system prompt:\\ |
|
1427 | 1427 | $ python file args\\ |
|
1428 | 1428 | but with the advantage of giving you IPython's tracebacks, and of |
|
1429 | 1429 | loading all variables into your interactive namespace for further use |
|
1430 | 1430 | (unless -p is used, see below). |
|
1431 | 1431 | |
|
1432 | 1432 | The file is executed in a namespace initially consisting only of |
|
1433 | 1433 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1434 | 1434 | sees its environment as if it were being run as a stand-alone program |
|
1435 | 1435 | (except for sharing global objects such as previously imported |
|
1436 | 1436 | modules). But after execution, the IPython interactive namespace gets |
|
1437 | 1437 | updated with all variables defined in the program (except for __name__ |
|
1438 | 1438 | and sys.argv). This allows for very convenient loading of code for |
|
1439 | 1439 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1440 | 1440 | |
|
1441 | 1441 | Options: |
|
1442 | 1442 | |
|
1443 | 1443 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1444 | 1444 | without extension (as python does under import). This allows running |
|
1445 | 1445 | scripts and reloading the definitions in them without calling code |
|
1446 | 1446 | protected by an ' if __name__ == "__main__" ' clause. |
|
1447 | 1447 | |
|
1448 | 1448 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1449 | 1449 | is useful if you are experimenting with code written in a text editor |
|
1450 | 1450 | which depends on variables defined interactively. |
|
1451 | 1451 | |
|
1452 | 1452 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1453 | 1453 | being run. This is particularly useful if IPython is being used to |
|
1454 | 1454 | run unittests, which always exit with a sys.exit() call. In such |
|
1455 | 1455 | cases you are interested in the output of the test results, not in |
|
1456 | 1456 | seeing a traceback of the unittest module. |
|
1457 | 1457 | |
|
1458 | 1458 | -t: print timing information at the end of the run. IPython will give |
|
1459 | 1459 | you an estimated CPU time consumption for your script, which under |
|
1460 | 1460 | Unix uses the resource module to avoid the wraparound problems of |
|
1461 | 1461 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1462 | 1462 | is also given (for Windows platforms this is reported as 0.0). |
|
1463 | 1463 | |
|
1464 | 1464 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1465 | 1465 | must be an integer indicating how many times you want the script to |
|
1466 | 1466 | run. The final timing report will include total and per run results. |
|
1467 | 1467 | |
|
1468 | 1468 | For example (testing the script uniq_stable.py): |
|
1469 | 1469 | |
|
1470 | 1470 | In [1]: run -t uniq_stable |
|
1471 | 1471 | |
|
1472 | 1472 | IPython CPU timings (estimated):\\ |
|
1473 | 1473 | User : 0.19597 s.\\ |
|
1474 | 1474 | System: 0.0 s.\\ |
|
1475 | 1475 | |
|
1476 | 1476 | In [2]: run -t -N5 uniq_stable |
|
1477 | 1477 | |
|
1478 | 1478 | IPython CPU timings (estimated):\\ |
|
1479 | 1479 | Total runs performed: 5\\ |
|
1480 | 1480 | Times : Total Per run\\ |
|
1481 | 1481 | User : 0.910862 s, 0.1821724 s.\\ |
|
1482 | 1482 | System: 0.0 s, 0.0 s. |
|
1483 | 1483 | |
|
1484 | 1484 | -d: run your program under the control of pdb, the Python debugger. |
|
1485 | 1485 | This allows you to execute your program step by step, watch variables, |
|
1486 | 1486 | etc. Internally, what IPython does is similar to calling: |
|
1487 | 1487 | |
|
1488 | 1488 | pdb.run('execfile("YOURFILENAME")') |
|
1489 | 1489 | |
|
1490 | 1490 | with a breakpoint set on line 1 of your file. You can change the line |
|
1491 | 1491 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1492 | 1492 | (where N must be an integer). For example: |
|
1493 | 1493 | |
|
1494 | 1494 | %run -d -b40 myscript |
|
1495 | 1495 | |
|
1496 | 1496 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1497 | 1497 | the first breakpoint must be set on a line which actually does |
|
1498 | 1498 | something (not a comment or docstring) for it to stop execution. |
|
1499 | 1499 | |
|
1500 | 1500 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1501 | 1501 | first enter 'c' (without qoutes) to start execution up to the first |
|
1502 | 1502 | breakpoint. |
|
1503 | 1503 | |
|
1504 | 1504 | Entering 'help' gives information about the use of the debugger. You |
|
1505 | 1505 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1506 | 1506 | at a prompt. |
|
1507 | 1507 | |
|
1508 | 1508 | -p: run program under the control of the Python profiler module (which |
|
1509 | 1509 | prints a detailed report of execution times, function calls, etc). |
|
1510 | 1510 | |
|
1511 | 1511 | You can pass other options after -p which affect the behavior of the |
|
1512 | 1512 | profiler itself. See the docs for %prun for details. |
|
1513 | 1513 | |
|
1514 | 1514 | In this mode, the program's variables do NOT propagate back to the |
|
1515 | 1515 | IPython interactive namespace (because they remain in the namespace |
|
1516 | 1516 | where the profiler executes them). |
|
1517 | 1517 | |
|
1518 | 1518 | Internally this triggers a call to %prun, see its documentation for |
|
1519 | 1519 | details on the options available specifically for profiling. |
|
1520 | 1520 | |
|
1521 | 1521 | There is one special usage for which the text above doesn't apply: |
|
1522 | 1522 | if the filename ends with .ipy, the file is run as ipython script, |
|
1523 | 1523 | just as if the commands were written on IPython prompt. |
|
1524 | 1524 | """ |
|
1525 | 1525 | |
|
1526 | 1526 | # get arguments and set sys.argv for program to be run. |
|
1527 | 1527 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1528 | 1528 | mode='list',list_all=1) |
|
1529 | 1529 | |
|
1530 | 1530 | try: |
|
1531 | 1531 | filename = get_py_filename(arg_lst[0]) |
|
1532 | 1532 | except IndexError: |
|
1533 | 1533 | warn('you must provide at least a filename.') |
|
1534 | 1534 | print '\n%run:\n',OInspect.getdoc(self.magic_run) |
|
1535 | 1535 | return |
|
1536 | 1536 | except IOError,msg: |
|
1537 | 1537 | error(msg) |
|
1538 | 1538 | return |
|
1539 | 1539 | |
|
1540 | 1540 | if filename.lower().endswith('.ipy'): |
|
1541 | 1541 | self.api.runlines(open(filename).read()) |
|
1542 | 1542 | return |
|
1543 | 1543 | |
|
1544 | 1544 | # Control the response to exit() calls made by the script being run |
|
1545 | 1545 | exit_ignore = opts.has_key('e') |
|
1546 | 1546 | |
|
1547 | 1547 | # Make sure that the running script gets a proper sys.argv as if it |
|
1548 | 1548 | # were run from a system shell. |
|
1549 | 1549 | save_argv = sys.argv # save it for later restoring |
|
1550 | 1550 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1551 | 1551 | |
|
1552 | 1552 | if opts.has_key('i'): |
|
1553 | 1553 | # Run in user's interactive namespace |
|
1554 | 1554 | prog_ns = self.shell.user_ns |
|
1555 | 1555 | __name__save = self.shell.user_ns['__name__'] |
|
1556 | 1556 | prog_ns['__name__'] = '__main__' |
|
1557 | 1557 | main_mod = FakeModule(prog_ns) |
|
1558 | 1558 | else: |
|
1559 | 1559 | # Run in a fresh, empty namespace |
|
1560 | 1560 | if opts.has_key('n'): |
|
1561 | 1561 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1562 | 1562 | else: |
|
1563 | 1563 | name = '__main__' |
|
1564 | 1564 | main_mod = FakeModule() |
|
1565 | 1565 | prog_ns = main_mod.__dict__ |
|
1566 | 1566 | prog_ns['__name__'] = name |
|
1567 | 1567 | # The shell MUST hold a reference to main_mod so after %run exits, |
|
1568 | 1568 | # the python deletion mechanism doesn't zero it out (leaving |
|
1569 | 1569 | # dangling references) |
|
1570 | 1570 | self.shell._user_main_modules.append(main_mod) |
|
1571 | 1571 | |
|
1572 | 1572 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1573 | 1573 | # set the __file__ global in the script's namespace |
|
1574 | 1574 | prog_ns['__file__'] = filename |
|
1575 | 1575 | |
|
1576 | 1576 | # pickle fix. See iplib for an explanation. But we need to make sure |
|
1577 | 1577 | # that, if we overwrite __main__, we replace it at the end |
|
1578 | 1578 | if prog_ns['__name__'] == '__main__': |
|
1579 | 1579 | restore_main = sys.modules['__main__'] |
|
1580 | 1580 | else: |
|
1581 | 1581 | restore_main = False |
|
1582 | 1582 | |
|
1583 | 1583 | sys.modules[prog_ns['__name__']] = main_mod |
|
1584 | 1584 | |
|
1585 | 1585 | stats = None |
|
1586 | 1586 | try: |
|
1587 | 1587 | self.shell.savehist() |
|
1588 | 1588 | |
|
1589 | 1589 | if opts.has_key('p'): |
|
1590 | 1590 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1591 | 1591 | else: |
|
1592 | 1592 | if opts.has_key('d'): |
|
1593 | 1593 | deb = Debugger.Pdb(self.shell.rc.colors) |
|
1594 | 1594 | # reset Breakpoint state, which is moronically kept |
|
1595 | 1595 | # in a class |
|
1596 | 1596 | bdb.Breakpoint.next = 1 |
|
1597 | 1597 | bdb.Breakpoint.bplist = {} |
|
1598 | 1598 | bdb.Breakpoint.bpbynumber = [None] |
|
1599 | 1599 | # Set an initial breakpoint to stop execution |
|
1600 | 1600 | maxtries = 10 |
|
1601 | 1601 | bp = int(opts.get('b',[1])[0]) |
|
1602 | 1602 | checkline = deb.checkline(filename,bp) |
|
1603 | 1603 | if not checkline: |
|
1604 | 1604 | for bp in range(bp+1,bp+maxtries+1): |
|
1605 | 1605 | if deb.checkline(filename,bp): |
|
1606 | 1606 | break |
|
1607 | 1607 | else: |
|
1608 | 1608 | msg = ("\nI failed to find a valid line to set " |
|
1609 | 1609 | "a breakpoint\n" |
|
1610 | 1610 | "after trying up to line: %s.\n" |
|
1611 | 1611 | "Please set a valid breakpoint manually " |
|
1612 | 1612 | "with the -b option." % bp) |
|
1613 | 1613 | error(msg) |
|
1614 | 1614 | return |
|
1615 | 1615 | # if we find a good linenumber, set the breakpoint |
|
1616 | 1616 | deb.do_break('%s:%s' % (filename,bp)) |
|
1617 | 1617 | # Start file run |
|
1618 | 1618 | print "NOTE: Enter 'c' at the", |
|
1619 | 1619 | print "%s prompt to start your script." % deb.prompt |
|
1620 | 1620 | try: |
|
1621 | 1621 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1622 | 1622 | |
|
1623 | 1623 | except: |
|
1624 | 1624 | etype, value, tb = sys.exc_info() |
|
1625 | 1625 | # Skip three frames in the traceback: the %run one, |
|
1626 | 1626 | # one inside bdb.py, and the command-line typed by the |
|
1627 | 1627 | # user (run by exec in pdb itself). |
|
1628 | 1628 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1629 | 1629 | else: |
|
1630 | 1630 | if runner is None: |
|
1631 | 1631 | runner = self.shell.safe_execfile |
|
1632 | 1632 | if opts.has_key('t'): |
|
1633 | 1633 | # timed execution |
|
1634 | 1634 | try: |
|
1635 | 1635 | nruns = int(opts['N'][0]) |
|
1636 | 1636 | if nruns < 1: |
|
1637 | 1637 | error('Number of runs must be >=1') |
|
1638 | 1638 | return |
|
1639 | 1639 | except (KeyError): |
|
1640 | 1640 | nruns = 1 |
|
1641 | 1641 | if nruns == 1: |
|
1642 | 1642 | t0 = clock2() |
|
1643 | 1643 | runner(filename,prog_ns,prog_ns, |
|
1644 | 1644 | exit_ignore=exit_ignore) |
|
1645 | 1645 | t1 = clock2() |
|
1646 | 1646 | t_usr = t1[0]-t0[0] |
|
1647 | 1647 | t_sys = t1[1]-t1[1] |
|
1648 | 1648 | print "\nIPython CPU timings (estimated):" |
|
1649 | 1649 | print " User : %10s s." % t_usr |
|
1650 | 1650 | print " System: %10s s." % t_sys |
|
1651 | 1651 | else: |
|
1652 | 1652 | runs = range(nruns) |
|
1653 | 1653 | t0 = clock2() |
|
1654 | 1654 | for nr in runs: |
|
1655 | 1655 | runner(filename,prog_ns,prog_ns, |
|
1656 | 1656 | exit_ignore=exit_ignore) |
|
1657 | 1657 | t1 = clock2() |
|
1658 | 1658 | t_usr = t1[0]-t0[0] |
|
1659 | 1659 | t_sys = t1[1]-t1[1] |
|
1660 | 1660 | print "\nIPython CPU timings (estimated):" |
|
1661 | 1661 | print "Total runs performed:",nruns |
|
1662 | 1662 | print " Times : %10s %10s" % ('Total','Per run') |
|
1663 | 1663 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1664 | 1664 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1665 | 1665 | |
|
1666 | 1666 | else: |
|
1667 | 1667 | # regular execution |
|
1668 | 1668 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1669 | 1669 | if opts.has_key('i'): |
|
1670 | 1670 | self.shell.user_ns['__name__'] = __name__save |
|
1671 | 1671 | else: |
|
1672 | 1672 | # update IPython interactive namespace |
|
1673 | 1673 | del prog_ns['__name__'] |
|
1674 | 1674 | self.shell.user_ns.update(prog_ns) |
|
1675 | 1675 | finally: |
|
1676 | 1676 | sys.argv = save_argv |
|
1677 | 1677 | if restore_main: |
|
1678 | 1678 | sys.modules['__main__'] = restore_main |
|
1679 | 1679 | self.shell.reloadhist() |
|
1680 | 1680 | |
|
1681 | 1681 | return stats |
|
1682 | 1682 | |
|
1683 | 1683 | def magic_runlog(self, parameter_s =''): |
|
1684 | 1684 | """Run files as logs. |
|
1685 | 1685 | |
|
1686 | 1686 | Usage:\\ |
|
1687 | 1687 | %runlog file1 file2 ... |
|
1688 | 1688 | |
|
1689 | 1689 | Run the named files (treating them as log files) in sequence inside |
|
1690 | 1690 | the interpreter, and return to the prompt. This is much slower than |
|
1691 | 1691 | %run because each line is executed in a try/except block, but it |
|
1692 | 1692 | allows running files with syntax errors in them. |
|
1693 | 1693 | |
|
1694 | 1694 | Normally IPython will guess when a file is one of its own logfiles, so |
|
1695 | 1695 | you can typically use %run even for logs. This shorthand allows you to |
|
1696 | 1696 | force any file to be treated as a log file.""" |
|
1697 | 1697 | |
|
1698 | 1698 | for f in parameter_s.split(): |
|
1699 | 1699 | self.shell.safe_execfile(f,self.shell.user_ns, |
|
1700 | 1700 | self.shell.user_ns,islog=1) |
|
1701 | 1701 | |
|
1702 | 1702 | def magic_timeit(self, parameter_s =''): |
|
1703 | 1703 | """Time execution of a Python statement or expression |
|
1704 | 1704 | |
|
1705 | 1705 | Usage:\\ |
|
1706 | 1706 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1707 | 1707 | |
|
1708 | 1708 | Time execution of a Python statement or expression using the timeit |
|
1709 | 1709 | module. |
|
1710 | 1710 | |
|
1711 | 1711 | Options: |
|
1712 | 1712 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1713 | 1713 | is not given, a fitting value is chosen. |
|
1714 | 1714 | |
|
1715 | 1715 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1716 | 1716 | Default: 3 |
|
1717 | 1717 | |
|
1718 | 1718 | -t: use time.time to measure the time, which is the default on Unix. |
|
1719 | 1719 | This function measures wall time. |
|
1720 | 1720 | |
|
1721 | 1721 | -c: use time.clock to measure the time, which is the default on |
|
1722 | 1722 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1723 | 1723 | instead and returns the CPU user time. |
|
1724 | 1724 | |
|
1725 | 1725 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1726 | 1726 | Default: 3 |
|
1727 | 1727 | |
|
1728 | 1728 | |
|
1729 | 1729 | Examples:\\ |
|
1730 | 1730 | In [1]: %timeit pass |
|
1731 | 1731 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1732 | 1732 | |
|
1733 | 1733 | In [2]: u = None |
|
1734 | 1734 | |
|
1735 | 1735 | In [3]: %timeit u is None |
|
1736 | 1736 | 10000000 loops, best of 3: 184 ns per loop |
|
1737 | 1737 | |
|
1738 | 1738 | In [4]: %timeit -r 4 u == None |
|
1739 | 1739 | 1000000 loops, best of 4: 242 ns per loop |
|
1740 | 1740 | |
|
1741 | 1741 | In [5]: import time |
|
1742 | 1742 | |
|
1743 | 1743 | In [6]: %timeit -n1 time.sleep(2) |
|
1744 | 1744 | 1 loops, best of 3: 2 s per loop |
|
1745 | 1745 | |
|
1746 | 1746 | |
|
1747 | 1747 | The times reported by %timeit will be slightly higher than those |
|
1748 | 1748 | reported by the timeit.py script when variables are accessed. This is |
|
1749 | 1749 | due to the fact that %timeit executes the statement in the namespace |
|
1750 | 1750 | of the shell, compared with timeit.py, which uses a single setup |
|
1751 | 1751 | statement to import function or create variables. Generally, the bias |
|
1752 | 1752 | does not matter as long as results from timeit.py are not mixed with |
|
1753 | 1753 | those from %timeit.""" |
|
1754 | 1754 | |
|
1755 | 1755 | import timeit |
|
1756 | 1756 | import math |
|
1757 | 1757 | |
|
1758 | 1758 | units = ["s", "ms", "\xc2\xb5s", "ns"] |
|
1759 | 1759 | scaling = [1, 1e3, 1e6, 1e9] |
|
1760 | 1760 | |
|
1761 | 1761 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1762 | 1762 | posix=False) |
|
1763 | 1763 | if stmt == "": |
|
1764 | 1764 | return |
|
1765 | 1765 | timefunc = timeit.default_timer |
|
1766 | 1766 | number = int(getattr(opts, "n", 0)) |
|
1767 | 1767 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1768 | 1768 | precision = int(getattr(opts, "p", 3)) |
|
1769 | 1769 | if hasattr(opts, "t"): |
|
1770 | 1770 | timefunc = time.time |
|
1771 | 1771 | if hasattr(opts, "c"): |
|
1772 | 1772 | timefunc = clock |
|
1773 | 1773 | |
|
1774 | 1774 | timer = timeit.Timer(timer=timefunc) |
|
1775 | 1775 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1776 | 1776 | # but is there a better way to achieve that the code stmt has access |
|
1777 | 1777 | # to the shell namespace? |
|
1778 | 1778 | |
|
1779 | 1779 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1780 | 1780 | 'setup': "pass"} |
|
1781 | 1781 | # Track compilation time so it can be reported if too long |
|
1782 | 1782 | # Minimum time above which compilation time will be reported |
|
1783 | 1783 | tc_min = 0.1 |
|
1784 | 1784 | |
|
1785 | 1785 | t0 = clock() |
|
1786 | 1786 | code = compile(src, "<magic-timeit>", "exec") |
|
1787 | 1787 | tc = clock()-t0 |
|
1788 | 1788 | |
|
1789 | 1789 | ns = {} |
|
1790 | 1790 | exec code in self.shell.user_ns, ns |
|
1791 | 1791 | timer.inner = ns["inner"] |
|
1792 | 1792 | |
|
1793 | 1793 | if number == 0: |
|
1794 | 1794 | # determine number so that 0.2 <= total time < 2.0 |
|
1795 | 1795 | number = 1 |
|
1796 | 1796 | for i in range(1, 10): |
|
1797 | 1797 | number *= 10 |
|
1798 | 1798 | if timer.timeit(number) >= 0.2: |
|
1799 | 1799 | break |
|
1800 | 1800 | |
|
1801 | 1801 | best = min(timer.repeat(repeat, number)) / number |
|
1802 | 1802 | |
|
1803 | 1803 | if best > 0.0: |
|
1804 | 1804 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1805 | 1805 | else: |
|
1806 | 1806 | order = 3 |
|
1807 | 1807 | print "%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1808 | 1808 | precision, |
|
1809 | 1809 | best * scaling[order], |
|
1810 | 1810 | units[order]) |
|
1811 | 1811 | if tc > tc_min: |
|
1812 | 1812 | print "Compiler time: %.2f s" % tc |
|
1813 | 1813 | |
|
1814 | 1814 | def magic_time(self,parameter_s = ''): |
|
1815 | 1815 | """Time execution of a Python statement or expression. |
|
1816 | 1816 | |
|
1817 | 1817 | The CPU and wall clock times are printed, and the value of the |
|
1818 | 1818 | expression (if any) is returned. Note that under Win32, system time |
|
1819 | 1819 | is always reported as 0, since it can not be measured. |
|
1820 | 1820 | |
|
1821 | 1821 | This function provides very basic timing functionality. In Python |
|
1822 | 1822 | 2.3, the timeit module offers more control and sophistication, so this |
|
1823 | 1823 | could be rewritten to use it (patches welcome). |
|
1824 | 1824 | |
|
1825 | 1825 | Some examples: |
|
1826 | 1826 | |
|
1827 | 1827 | In [1]: time 2**128 |
|
1828 | 1828 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1829 | 1829 | Wall time: 0.00 |
|
1830 | 1830 | Out[1]: 340282366920938463463374607431768211456L |
|
1831 | 1831 | |
|
1832 | 1832 | In [2]: n = 1000000 |
|
1833 | 1833 | |
|
1834 | 1834 | In [3]: time sum(range(n)) |
|
1835 | 1835 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1836 | 1836 | Wall time: 1.37 |
|
1837 | 1837 | Out[3]: 499999500000L |
|
1838 | 1838 | |
|
1839 | 1839 | In [4]: time print 'hello world' |
|
1840 | 1840 | hello world |
|
1841 | 1841 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1842 | 1842 | Wall time: 0.00 |
|
1843 | 1843 | |
|
1844 | 1844 | Note that the time needed by Python to compile the given expression |
|
1845 | 1845 | will be reported if it is more than 0.1s. In this example, the |
|
1846 | 1846 | actual exponentiation is done by Python at compilation time, so while |
|
1847 | 1847 | the expression can take a noticeable amount of time to compute, that |
|
1848 | 1848 | time is purely due to the compilation: |
|
1849 | 1849 | |
|
1850 | 1850 | In [5]: time 3**9999; |
|
1851 | 1851 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1852 | 1852 | Wall time: 0.00 s |
|
1853 | 1853 | |
|
1854 | 1854 | In [6]: time 3**999999; |
|
1855 | 1855 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1856 | 1856 | Wall time: 0.00 s |
|
1857 | 1857 | Compiler : 0.78 s |
|
1858 | 1858 | """ |
|
1859 | 1859 | |
|
1860 | 1860 | # fail immediately if the given expression can't be compiled |
|
1861 | 1861 | |
|
1862 | 1862 | expr = self.shell.prefilter(parameter_s,False) |
|
1863 | 1863 | |
|
1864 | 1864 | # Minimum time above which compilation time will be reported |
|
1865 | 1865 | tc_min = 0.1 |
|
1866 | 1866 | |
|
1867 | 1867 | try: |
|
1868 | 1868 | mode = 'eval' |
|
1869 | 1869 | t0 = clock() |
|
1870 | 1870 | code = compile(expr,'<timed eval>',mode) |
|
1871 | 1871 | tc = clock()-t0 |
|
1872 | 1872 | except SyntaxError: |
|
1873 | 1873 | mode = 'exec' |
|
1874 | 1874 | t0 = clock() |
|
1875 | 1875 | code = compile(expr,'<timed exec>',mode) |
|
1876 | 1876 | tc = clock()-t0 |
|
1877 | 1877 | # skew measurement as little as possible |
|
1878 | 1878 | glob = self.shell.user_ns |
|
1879 | 1879 | clk = clock2 |
|
1880 | 1880 | wtime = time.time |
|
1881 | 1881 | # time execution |
|
1882 | 1882 | wall_st = wtime() |
|
1883 | 1883 | if mode=='eval': |
|
1884 | 1884 | st = clk() |
|
1885 | 1885 | out = eval(code,glob) |
|
1886 | 1886 | end = clk() |
|
1887 | 1887 | else: |
|
1888 | 1888 | st = clk() |
|
1889 | 1889 | exec code in glob |
|
1890 | 1890 | end = clk() |
|
1891 | 1891 | out = None |
|
1892 | 1892 | wall_end = wtime() |
|
1893 | 1893 | # Compute actual times and report |
|
1894 | 1894 | wall_time = wall_end-wall_st |
|
1895 | 1895 | cpu_user = end[0]-st[0] |
|
1896 | 1896 | cpu_sys = end[1]-st[1] |
|
1897 | 1897 | cpu_tot = cpu_user+cpu_sys |
|
1898 | 1898 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1899 | 1899 | (cpu_user,cpu_sys,cpu_tot) |
|
1900 | 1900 | print "Wall time: %.2f s" % wall_time |
|
1901 | 1901 | if tc > tc_min: |
|
1902 | 1902 | print "Compiler : %.2f s" % tc |
|
1903 | 1903 | return out |
|
1904 | 1904 | |
|
1905 | 1905 | def magic_macro(self,parameter_s = ''): |
|
1906 | 1906 | """Define a set of input lines as a macro for future re-execution. |
|
1907 | 1907 | |
|
1908 | 1908 | Usage:\\ |
|
1909 | 1909 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1910 | 1910 | |
|
1911 | 1911 | Options: |
|
1912 | 1912 | |
|
1913 | 1913 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1914 | 1914 | so that magics are loaded in their transformed version to valid |
|
1915 | 1915 | Python. If this option is given, the raw input as typed as the |
|
1916 | 1916 | command line is used instead. |
|
1917 | 1917 | |
|
1918 | 1918 | This will define a global variable called `name` which is a string |
|
1919 | 1919 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1920 | 1920 | above) from your input history into a single string. This variable |
|
1921 | 1921 | acts like an automatic function which re-executes those lines as if |
|
1922 | 1922 | you had typed them. You just type 'name' at the prompt and the code |
|
1923 | 1923 | executes. |
|
1924 | 1924 | |
|
1925 | 1925 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
1926 | 1926 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
1927 | 1927 | using the lines numbered 5,6 and 7. |
|
1928 | 1928 | |
|
1929 | 1929 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1930 | 1930 | notation, where N:M means numbers N through M-1. |
|
1931 | 1931 | |
|
1932 | 1932 | For example, if your history contains (%hist prints it): |
|
1933 | 1933 | |
|
1934 | 1934 | 44: x=1\\ |
|
1935 | 1935 | 45: y=3\\ |
|
1936 | 1936 | 46: z=x+y\\ |
|
1937 | 1937 | 47: print x\\ |
|
1938 | 1938 | 48: a=5\\ |
|
1939 | 1939 | 49: print 'x',x,'y',y\\ |
|
1940 | 1940 | |
|
1941 | 1941 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1942 | 1942 | called my_macro with: |
|
1943 | 1943 | |
|
1944 | 1944 | In [51]: %macro my_macro 44-47 49 |
|
1945 | 1945 | |
|
1946 | 1946 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1947 | 1947 | in one pass. |
|
1948 | 1948 | |
|
1949 | 1949 | You don't need to give the line-numbers in order, and any given line |
|
1950 | 1950 | number can appear multiple times. You can assemble macros with any |
|
1951 | 1951 | lines from your input history in any order. |
|
1952 | 1952 | |
|
1953 | 1953 | The macro is a simple object which holds its value in an attribute, |
|
1954 | 1954 | but IPython's display system checks for macros and executes them as |
|
1955 | 1955 | code instead of printing them when you type their name. |
|
1956 | 1956 | |
|
1957 | 1957 | You can view a macro's contents by explicitly printing it with: |
|
1958 | 1958 | |
|
1959 | 1959 | 'print macro_name'. |
|
1960 | 1960 | |
|
1961 | 1961 | For one-off cases which DON'T contain magic function calls in them you |
|
1962 | 1962 | can obtain similar results by explicitly executing slices from your |
|
1963 | 1963 | input history with: |
|
1964 | 1964 | |
|
1965 | 1965 | In [60]: exec In[44:48]+In[49]""" |
|
1966 | 1966 | |
|
1967 | 1967 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
1968 | 1968 | if not args: |
|
1969 | 1969 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] |
|
1970 | 1970 | macs.sort() |
|
1971 | 1971 | return macs |
|
1972 | 1972 | if len(args) == 1: |
|
1973 | 1973 | raise UsageError( |
|
1974 | 1974 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
1975 | 1975 | name,ranges = args[0], args[1:] |
|
1976 | 1976 | |
|
1977 | 1977 | #print 'rng',ranges # dbg |
|
1978 | 1978 | lines = self.extract_input_slices(ranges,opts.has_key('r')) |
|
1979 | 1979 | macro = Macro(lines) |
|
1980 | 1980 | self.shell.user_ns.update({name:macro}) |
|
1981 | 1981 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
1982 | 1982 | print 'Macro contents:' |
|
1983 | 1983 | print macro, |
|
1984 | 1984 | |
|
1985 | 1985 | def magic_save(self,parameter_s = ''): |
|
1986 | 1986 | """Save a set of lines to a given filename. |
|
1987 | 1987 | |
|
1988 | 1988 | Usage:\\ |
|
1989 | 1989 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
1990 | 1990 | |
|
1991 | 1991 | Options: |
|
1992 | 1992 | |
|
1993 | 1993 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1994 | 1994 | so that magics are loaded in their transformed version to valid |
|
1995 | 1995 | Python. If this option is given, the raw input as typed as the |
|
1996 | 1996 | command line is used instead. |
|
1997 | 1997 | |
|
1998 | 1998 | This function uses the same syntax as %macro for line extraction, but |
|
1999 | 1999 | instead of creating a macro it saves the resulting string to the |
|
2000 | 2000 | filename you specify. |
|
2001 | 2001 | |
|
2002 | 2002 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2003 | 2003 | it asks for confirmation before overwriting existing files.""" |
|
2004 | 2004 | |
|
2005 | 2005 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2006 | 2006 | fname,ranges = args[0], args[1:] |
|
2007 | 2007 | if not fname.endswith('.py'): |
|
2008 | 2008 | fname += '.py' |
|
2009 | 2009 | if os.path.isfile(fname): |
|
2010 | 2010 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2011 | 2011 | if ans.lower() not in ['y','yes']: |
|
2012 | 2012 | print 'Operation cancelled.' |
|
2013 | 2013 | return |
|
2014 | 2014 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) |
|
2015 | 2015 | f = file(fname,'w') |
|
2016 | 2016 | f.write(cmds) |
|
2017 | 2017 | f.close() |
|
2018 | 2018 | print 'The following commands were written to file `%s`:' % fname |
|
2019 | 2019 | print cmds |
|
2020 | 2020 | |
|
2021 | 2021 | def _edit_macro(self,mname,macro): |
|
2022 | 2022 | """open an editor with the macro data in a file""" |
|
2023 | 2023 | filename = self.shell.mktempfile(macro.value) |
|
2024 | 2024 | self.shell.hooks.editor(filename) |
|
2025 | 2025 | |
|
2026 | 2026 | # and make a new macro object, to replace the old one |
|
2027 | 2027 | mfile = open(filename) |
|
2028 | 2028 | mvalue = mfile.read() |
|
2029 | 2029 | mfile.close() |
|
2030 | 2030 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2031 | 2031 | |
|
2032 | 2032 | def magic_ed(self,parameter_s=''): |
|
2033 | 2033 | """Alias to %edit.""" |
|
2034 | 2034 | return self.magic_edit(parameter_s) |
|
2035 | 2035 | |
|
2036 | 2036 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2037 | 2037 | """Bring up an editor and execute the resulting code. |
|
2038 | 2038 | |
|
2039 | 2039 | Usage: |
|
2040 | 2040 | %edit [options] [args] |
|
2041 | 2041 | |
|
2042 | 2042 | %edit runs IPython's editor hook. The default version of this hook is |
|
2043 | 2043 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
2044 | 2044 | environment variable $EDITOR. If this isn't found, it will default to |
|
2045 | 2045 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
2046 | 2046 | docstring for how to change the editor hook. |
|
2047 | 2047 | |
|
2048 | 2048 | You can also set the value of this editor via the command line option |
|
2049 | 2049 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
2050 | 2050 | specifically for IPython an editor different from your typical default |
|
2051 | 2051 | (and for Windows users who typically don't set environment variables). |
|
2052 | 2052 | |
|
2053 | 2053 | This command allows you to conveniently edit multi-line code right in |
|
2054 | 2054 | your IPython session. |
|
2055 | 2055 | |
|
2056 | 2056 | If called without arguments, %edit opens up an empty editor with a |
|
2057 | 2057 | temporary file and will execute the contents of this file when you |
|
2058 | 2058 | close it (don't forget to save it!). |
|
2059 | 2059 | |
|
2060 | 2060 | |
|
2061 | 2061 | Options: |
|
2062 | 2062 | |
|
2063 | 2063 | -n <number>: open the editor at a specified line number. By default, |
|
2064 | 2064 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2065 | 2065 | you can configure this by providing your own modified hook if your |
|
2066 | 2066 | favorite editor supports line-number specifications with a different |
|
2067 | 2067 | syntax. |
|
2068 | 2068 | |
|
2069 | 2069 | -p: this will call the editor with the same data as the previous time |
|
2070 | 2070 | it was used, regardless of how long ago (in your current session) it |
|
2071 | 2071 | was. |
|
2072 | 2072 | |
|
2073 | 2073 | -r: use 'raw' input. This option only applies to input taken from the |
|
2074 | 2074 | user's history. By default, the 'processed' history is used, so that |
|
2075 | 2075 | magics are loaded in their transformed version to valid Python. If |
|
2076 | 2076 | this option is given, the raw input as typed as the command line is |
|
2077 | 2077 | used instead. When you exit the editor, it will be executed by |
|
2078 | 2078 | IPython's own processor. |
|
2079 | 2079 | |
|
2080 | 2080 | -x: do not execute the edited code immediately upon exit. This is |
|
2081 | 2081 | mainly useful if you are editing programs which need to be called with |
|
2082 | 2082 | command line arguments, which you can then do using %run. |
|
2083 | 2083 | |
|
2084 | 2084 | |
|
2085 | 2085 | Arguments: |
|
2086 | 2086 | |
|
2087 | 2087 | If arguments are given, the following possibilites exist: |
|
2088 | 2088 | |
|
2089 | 2089 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
2090 | 2090 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
2091 | 2091 | loaded into the editor. The syntax is the same of the %macro command. |
|
2092 | 2092 | |
|
2093 | 2093 | - If the argument doesn't start with a number, it is evaluated as a |
|
2094 | 2094 | variable and its contents loaded into the editor. You can thus edit |
|
2095 | 2095 | any string which contains python code (including the result of |
|
2096 | 2096 | previous edits). |
|
2097 | 2097 | |
|
2098 | 2098 | - If the argument is the name of an object (other than a string), |
|
2099 | 2099 | IPython will try to locate the file where it was defined and open the |
|
2100 | 2100 | editor at the point where it is defined. You can use `%edit function` |
|
2101 | 2101 | to load an editor exactly at the point where 'function' is defined, |
|
2102 | 2102 | edit it and have the file be executed automatically. |
|
2103 | 2103 | |
|
2104 | 2104 | If the object is a macro (see %macro for details), this opens up your |
|
2105 | 2105 | specified editor with a temporary file containing the macro's data. |
|
2106 | 2106 | Upon exit, the macro is reloaded with the contents of the file. |
|
2107 | 2107 | |
|
2108 | 2108 | Note: opening at an exact line is only supported under Unix, and some |
|
2109 | 2109 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2110 | 2110 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2111 | 2111 | (X)Emacs, vi, jed, pico and joe all do. |
|
2112 | 2112 | |
|
2113 | 2113 | - If the argument is not found as a variable, IPython will look for a |
|
2114 | 2114 | file with that name (adding .py if necessary) and load it into the |
|
2115 | 2115 | editor. It will execute its contents with execfile() when you exit, |
|
2116 | 2116 | loading any code in the file into your interactive namespace. |
|
2117 | 2117 | |
|
2118 | 2118 | After executing your code, %edit will return as output the code you |
|
2119 | 2119 | typed in the editor (except when it was an existing file). This way |
|
2120 | 2120 | you can reload the code in further invocations of %edit as a variable, |
|
2121 | 2121 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2122 | 2122 | the output. |
|
2123 | 2123 | |
|
2124 | 2124 | Note that %edit is also available through the alias %ed. |
|
2125 | 2125 | |
|
2126 | 2126 | This is an example of creating a simple function inside the editor and |
|
2127 | 2127 | then modifying it. First, start up the editor: |
|
2128 | 2128 | |
|
2129 | 2129 | In [1]: ed\\ |
|
2130 | 2130 | Editing... done. Executing edited code...\\ |
|
2131 | 2131 | Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n' |
|
2132 | 2132 | |
|
2133 | 2133 | We can then call the function foo(): |
|
2134 | 2134 | |
|
2135 | 2135 | In [2]: foo()\\ |
|
2136 | 2136 | foo() was defined in an editing session |
|
2137 | 2137 | |
|
2138 | 2138 | Now we edit foo. IPython automatically loads the editor with the |
|
2139 | 2139 | (temporary) file where foo() was previously defined: |
|
2140 | 2140 | |
|
2141 | 2141 | In [3]: ed foo\\ |
|
2142 | 2142 | Editing... done. Executing edited code... |
|
2143 | 2143 | |
|
2144 | 2144 | And if we call foo() again we get the modified version: |
|
2145 | 2145 | |
|
2146 | 2146 | In [4]: foo()\\ |
|
2147 | 2147 | foo() has now been changed! |
|
2148 | 2148 | |
|
2149 | 2149 | Here is an example of how to edit a code snippet successive |
|
2150 | 2150 | times. First we call the editor: |
|
2151 | 2151 | |
|
2152 | 2152 | In [8]: ed\\ |
|
2153 | 2153 | Editing... done. Executing edited code...\\ |
|
2154 | 2154 | hello\\ |
|
2155 | 2155 | Out[8]: "print 'hello'\\n" |
|
2156 | 2156 | |
|
2157 | 2157 | Now we call it again with the previous output (stored in _): |
|
2158 | 2158 | |
|
2159 | 2159 | In [9]: ed _\\ |
|
2160 | 2160 | Editing... done. Executing edited code...\\ |
|
2161 | 2161 | hello world\\ |
|
2162 | 2162 | Out[9]: "print 'hello world'\\n" |
|
2163 | 2163 | |
|
2164 | 2164 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2165 | 2165 | |
|
2166 | 2166 | In [10]: ed _8\\ |
|
2167 | 2167 | Editing... done. Executing edited code...\\ |
|
2168 | 2168 | hello again\\ |
|
2169 | 2169 | Out[10]: "print 'hello again'\\n" |
|
2170 | 2170 | |
|
2171 | 2171 | |
|
2172 | 2172 | Changing the default editor hook: |
|
2173 | 2173 | |
|
2174 | 2174 | If you wish to write your own editor hook, you can put it in a |
|
2175 | 2175 | configuration file which you load at startup time. The default hook |
|
2176 | 2176 | is defined in the IPython.hooks module, and you can use that as a |
|
2177 | 2177 | starting example for further modifications. That file also has |
|
2178 | 2178 | general instructions on how to set a new hook for use once you've |
|
2179 | 2179 | defined it.""" |
|
2180 | 2180 | |
|
2181 | 2181 | # FIXME: This function has become a convoluted mess. It needs a |
|
2182 | 2182 | # ground-up rewrite with clean, simple logic. |
|
2183 | 2183 | |
|
2184 | 2184 | def make_filename(arg): |
|
2185 | 2185 | "Make a filename from the given args" |
|
2186 | 2186 | try: |
|
2187 | 2187 | filename = get_py_filename(arg) |
|
2188 | 2188 | except IOError: |
|
2189 | 2189 | if args.endswith('.py'): |
|
2190 | 2190 | filename = arg |
|
2191 | 2191 | else: |
|
2192 | 2192 | filename = None |
|
2193 | 2193 | return filename |
|
2194 | 2194 | |
|
2195 | 2195 | # custom exceptions |
|
2196 | 2196 | class DataIsObject(Exception): pass |
|
2197 | 2197 | |
|
2198 | 2198 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2199 | 2199 | # Set a few locals from the options for convenience: |
|
2200 | 2200 | opts_p = opts.has_key('p') |
|
2201 | 2201 | opts_r = opts.has_key('r') |
|
2202 | 2202 | |
|
2203 | 2203 | # Default line number value |
|
2204 | 2204 | lineno = opts.get('n',None) |
|
2205 | 2205 | |
|
2206 | 2206 | if opts_p: |
|
2207 | 2207 | args = '_%s' % last_call[0] |
|
2208 | 2208 | if not self.shell.user_ns.has_key(args): |
|
2209 | 2209 | args = last_call[1] |
|
2210 | 2210 | |
|
2211 | 2211 | # use last_call to remember the state of the previous call, but don't |
|
2212 | 2212 | # let it be clobbered by successive '-p' calls. |
|
2213 | 2213 | try: |
|
2214 | 2214 | last_call[0] = self.shell.outputcache.prompt_count |
|
2215 | 2215 | if not opts_p: |
|
2216 | 2216 | last_call[1] = parameter_s |
|
2217 | 2217 | except: |
|
2218 | 2218 | pass |
|
2219 | 2219 | |
|
2220 | 2220 | # by default this is done with temp files, except when the given |
|
2221 | 2221 | # arg is a filename |
|
2222 | 2222 | use_temp = 1 |
|
2223 | 2223 | |
|
2224 | 2224 | if re.match(r'\d',args): |
|
2225 | 2225 | # Mode where user specifies ranges of lines, like in %macro. |
|
2226 | 2226 | # This means that you can't edit files whose names begin with |
|
2227 | 2227 | # numbers this way. Tough. |
|
2228 | 2228 | ranges = args.split() |
|
2229 | 2229 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
2230 | 2230 | elif args.endswith('.py'): |
|
2231 | 2231 | filename = make_filename(args) |
|
2232 | 2232 | data = '' |
|
2233 | 2233 | use_temp = 0 |
|
2234 | 2234 | elif args: |
|
2235 | 2235 | try: |
|
2236 | 2236 | # Load the parameter given as a variable. If not a string, |
|
2237 | 2237 | # process it as an object instead (below) |
|
2238 | 2238 | |
|
2239 | 2239 | #print '*** args',args,'type',type(args) # dbg |
|
2240 | 2240 | data = eval(args,self.shell.user_ns) |
|
2241 | 2241 | if not type(data) in StringTypes: |
|
2242 | 2242 | raise DataIsObject |
|
2243 | 2243 | |
|
2244 | 2244 | except (NameError,SyntaxError): |
|
2245 | 2245 | # given argument is not a variable, try as a filename |
|
2246 | 2246 | filename = make_filename(args) |
|
2247 | 2247 | if filename is None: |
|
2248 | 2248 | warn("Argument given (%s) can't be found as a variable " |
|
2249 | 2249 | "or as a filename." % args) |
|
2250 | 2250 | return |
|
2251 | 2251 | |
|
2252 | 2252 | data = '' |
|
2253 | 2253 | use_temp = 0 |
|
2254 | 2254 | except DataIsObject: |
|
2255 | 2255 | |
|
2256 | 2256 | # macros have a special edit function |
|
2257 | 2257 | if isinstance(data,Macro): |
|
2258 | 2258 | self._edit_macro(args,data) |
|
2259 | 2259 | return |
|
2260 | 2260 | |
|
2261 | 2261 | # For objects, try to edit the file where they are defined |
|
2262 | 2262 | try: |
|
2263 | 2263 | filename = inspect.getabsfile(data) |
|
2264 | 2264 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2265 | 2265 | # class created by %edit? Try to find source |
|
2266 | 2266 | # by looking for method definitions instead, the |
|
2267 | 2267 | # __module__ in those classes is FakeModule. |
|
2268 | 2268 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2269 | 2269 | for attr in attrs: |
|
2270 | 2270 | if not inspect.ismethod(attr): |
|
2271 | 2271 | continue |
|
2272 | 2272 | filename = inspect.getabsfile(attr) |
|
2273 | 2273 | if filename and 'fakemodule' not in filename.lower(): |
|
2274 | 2274 | # change the attribute to be the edit target instead |
|
2275 | 2275 | data = attr |
|
2276 | 2276 | break |
|
2277 | 2277 | |
|
2278 | 2278 | datafile = 1 |
|
2279 | 2279 | except TypeError: |
|
2280 | 2280 | filename = make_filename(args) |
|
2281 | 2281 | datafile = 1 |
|
2282 | 2282 | warn('Could not find file where `%s` is defined.\n' |
|
2283 | 2283 | 'Opening a file named `%s`' % (args,filename)) |
|
2284 | 2284 | # Now, make sure we can actually read the source (if it was in |
|
2285 | 2285 | # a temp file it's gone by now). |
|
2286 | 2286 | if datafile: |
|
2287 | 2287 | try: |
|
2288 | 2288 | if lineno is None: |
|
2289 | 2289 | lineno = inspect.getsourcelines(data)[1] |
|
2290 | 2290 | except IOError: |
|
2291 | 2291 | filename = make_filename(args) |
|
2292 | 2292 | if filename is None: |
|
2293 | 2293 | warn('The file `%s` where `%s` was defined cannot ' |
|
2294 | 2294 | 'be read.' % (filename,data)) |
|
2295 | 2295 | return |
|
2296 | 2296 | use_temp = 0 |
|
2297 | 2297 | else: |
|
2298 | 2298 | data = '' |
|
2299 | 2299 | |
|
2300 | 2300 | if use_temp: |
|
2301 | 2301 | filename = self.shell.mktempfile(data) |
|
2302 | 2302 | print 'IPython will make a temporary file named:',filename |
|
2303 | 2303 | |
|
2304 | 2304 | # do actual editing here |
|
2305 | 2305 | print 'Editing...', |
|
2306 | 2306 | sys.stdout.flush() |
|
2307 | 2307 | self.shell.hooks.editor(filename,lineno) |
|
2308 | 2308 | if opts.has_key('x'): # -x prevents actual execution |
|
2309 | 2309 | |
|
2310 | 2310 | else: |
|
2311 | 2311 | print 'done. Executing edited code...' |
|
2312 | 2312 | if opts_r: |
|
2313 | 2313 | self.shell.runlines(file_read(filename)) |
|
2314 | 2314 | else: |
|
2315 | 2315 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2316 | 2316 | self.shell.user_ns) |
|
2317 | 2317 | if use_temp: |
|
2318 | 2318 | try: |
|
2319 | 2319 | return open(filename).read() |
|
2320 | 2320 | except IOError,msg: |
|
2321 | 2321 | if msg.filename == filename: |
|
2322 | 2322 | warn('File not found. Did you forget to save?') |
|
2323 | 2323 | return |
|
2324 | 2324 | else: |
|
2325 | 2325 | self.shell.showtraceback() |
|
2326 | 2326 | |
|
2327 | 2327 | def magic_xmode(self,parameter_s = ''): |
|
2328 | 2328 | """Switch modes for the exception handlers. |
|
2329 | 2329 | |
|
2330 | 2330 | Valid modes: Plain, Context and Verbose. |
|
2331 | 2331 | |
|
2332 | 2332 | If called without arguments, acts as a toggle.""" |
|
2333 | 2333 | |
|
2334 | 2334 | def xmode_switch_err(name): |
|
2335 | 2335 | warn('Error changing %s exception modes.\n%s' % |
|
2336 | 2336 | (name,sys.exc_info()[1])) |
|
2337 | 2337 | |
|
2338 | 2338 | shell = self.shell |
|
2339 | 2339 | new_mode = parameter_s.strip().capitalize() |
|
2340 | 2340 | try: |
|
2341 | 2341 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2342 | 2342 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2343 | 2343 | except: |
|
2344 | 2344 | xmode_switch_err('user') |
|
2345 | 2345 | |
|
2346 | 2346 | # threaded shells use a special handler in sys.excepthook |
|
2347 | 2347 | if shell.isthreaded: |
|
2348 | 2348 | try: |
|
2349 | 2349 | shell.sys_excepthook.set_mode(mode=new_mode) |
|
2350 | 2350 | except: |
|
2351 | 2351 | xmode_switch_err('threaded') |
|
2352 | 2352 | |
|
2353 | 2353 | def magic_colors(self,parameter_s = ''): |
|
2354 | 2354 | """Switch color scheme for prompts, info system and exception handlers. |
|
2355 | 2355 | |
|
2356 | 2356 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2357 | 2357 | |
|
2358 | 2358 | Color scheme names are not case-sensitive.""" |
|
2359 | 2359 | |
|
2360 | 2360 | def color_switch_err(name): |
|
2361 | 2361 | warn('Error changing %s color schemes.\n%s' % |
|
2362 | 2362 | (name,sys.exc_info()[1])) |
|
2363 | 2363 | |
|
2364 | 2364 | |
|
2365 | 2365 | new_scheme = parameter_s.strip() |
|
2366 | 2366 | if not new_scheme: |
|
2367 | 2367 | raise UsageError( |
|
2368 | 2368 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2369 | 2369 | return |
|
2370 | 2370 | # local shortcut |
|
2371 | 2371 | shell = self.shell |
|
2372 | 2372 | |
|
2373 | 2373 | import IPython.rlineimpl as readline |
|
2374 | 2374 | |
|
2375 | 2375 | if not readline.have_readline and sys.platform == "win32": |
|
2376 | 2376 | msg = """\ |
|
2377 | 2377 | Proper color support under MS Windows requires the pyreadline library. |
|
2378 | 2378 | You can find it at: |
|
2379 | 2379 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2380 | 2380 | Gary's readline needs the ctypes module, from: |
|
2381 | 2381 | http://starship.python.net/crew/theller/ctypes |
|
2382 | 2382 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2383 | 2383 | |
|
2384 | 2384 | Defaulting color scheme to 'NoColor'""" |
|
2385 | 2385 | new_scheme = 'NoColor' |
|
2386 | 2386 | warn(msg) |
|
2387 | 2387 | |
|
2388 | 2388 | # readline option is 0 |
|
2389 | 2389 | if not shell.has_readline: |
|
2390 | 2390 | new_scheme = 'NoColor' |
|
2391 | 2391 | |
|
2392 | 2392 | # Set prompt colors |
|
2393 | 2393 | try: |
|
2394 | 2394 | shell.outputcache.set_colors(new_scheme) |
|
2395 | 2395 | except: |
|
2396 | 2396 | color_switch_err('prompt') |
|
2397 | 2397 | else: |
|
2398 | 2398 | shell.rc.colors = \ |
|
2399 | 2399 | shell.outputcache.color_table.active_scheme_name |
|
2400 | 2400 | # Set exception colors |
|
2401 | 2401 | try: |
|
2402 | 2402 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2403 | 2403 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2404 | 2404 | except: |
|
2405 | 2405 | color_switch_err('exception') |
|
2406 | 2406 | |
|
2407 | 2407 | # threaded shells use a verbose traceback in sys.excepthook |
|
2408 | 2408 | if shell.isthreaded: |
|
2409 | 2409 | try: |
|
2410 | 2410 | shell.sys_excepthook.set_colors(scheme=new_scheme) |
|
2411 | 2411 | except: |
|
2412 | 2412 | color_switch_err('system exception handler') |
|
2413 | 2413 | |
|
2414 | 2414 | # Set info (for 'object?') colors |
|
2415 | 2415 | if shell.rc.color_info: |
|
2416 | 2416 | try: |
|
2417 | 2417 | shell.inspector.set_active_scheme(new_scheme) |
|
2418 | 2418 | except: |
|
2419 | 2419 | color_switch_err('object inspector') |
|
2420 | 2420 | else: |
|
2421 | 2421 | shell.inspector.set_active_scheme('NoColor') |
|
2422 | 2422 | |
|
2423 | 2423 | def magic_color_info(self,parameter_s = ''): |
|
2424 | 2424 | """Toggle color_info. |
|
2425 | 2425 | |
|
2426 | 2426 | The color_info configuration parameter controls whether colors are |
|
2427 | 2427 | used for displaying object details (by things like %psource, %pfile or |
|
2428 | 2428 | the '?' system). This function toggles this value with each call. |
|
2429 | 2429 | |
|
2430 | 2430 | Note that unless you have a fairly recent pager (less works better |
|
2431 | 2431 | than more) in your system, using colored object information displays |
|
2432 | 2432 | will not work properly. Test it and see.""" |
|
2433 | 2433 | |
|
2434 | 2434 | self.shell.rc.color_info = 1 - self.shell.rc.color_info |
|
2435 | 2435 | self.magic_colors(self.shell.rc.colors) |
|
2436 | 2436 | print 'Object introspection functions have now coloring:', |
|
2437 | 2437 | print ['OFF','ON'][self.shell.rc.color_info] |
|
2438 | 2438 | |
|
2439 | 2439 | def magic_Pprint(self, parameter_s=''): |
|
2440 | 2440 | """Toggle pretty printing on/off.""" |
|
2441 | 2441 | |
|
2442 | 2442 | self.shell.rc.pprint = 1 - self.shell.rc.pprint |
|
2443 | 2443 | print 'Pretty printing has been turned', \ |
|
2444 | 2444 | ['OFF','ON'][self.shell.rc.pprint] |
|
2445 | 2445 | |
|
2446 | 2446 | def magic_exit(self, parameter_s=''): |
|
2447 | 2447 | """Exit IPython, confirming if configured to do so. |
|
2448 | 2448 | |
|
2449 | 2449 | You can configure whether IPython asks for confirmation upon exit by |
|
2450 | 2450 | setting the confirm_exit flag in the ipythonrc file.""" |
|
2451 | 2451 | |
|
2452 | 2452 | self.shell.exit() |
|
2453 | 2453 | |
|
2454 | 2454 | def magic_quit(self, parameter_s=''): |
|
2455 | 2455 | """Exit IPython, confirming if configured to do so (like %exit)""" |
|
2456 | 2456 | |
|
2457 | 2457 | self.shell.exit() |
|
2458 | 2458 | |
|
2459 | 2459 | def magic_Exit(self, parameter_s=''): |
|
2460 | 2460 | """Exit IPython without confirmation.""" |
|
2461 | 2461 | |
|
2462 | 2462 | self.shell.exit_now = True |
|
2463 | 2463 | |
|
2464 | 2464 | #...................................................................... |
|
2465 | 2465 | # Functions to implement unix shell-type things |
|
2466 | 2466 | |
|
2467 | 2467 | def magic_alias(self, parameter_s = ''): |
|
2468 | 2468 | """Define an alias for a system command. |
|
2469 | 2469 | |
|
2470 | 2470 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2471 | 2471 | |
|
2472 | 2472 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2473 | 2473 | params' (from your underlying operating system). |
|
2474 | 2474 | |
|
2475 | 2475 | Aliases have lower precedence than magic functions and Python normal |
|
2476 | 2476 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2477 | 2477 | alias can not be executed until 'del foo' removes the Python variable. |
|
2478 | 2478 | |
|
2479 | 2479 | You can use the %l specifier in an alias definition to represent the |
|
2480 | 2480 | whole line when the alias is called. For example: |
|
2481 | 2481 | |
|
2482 | 2482 | In [2]: alias all echo "Input in brackets: <%l>"\\ |
|
2483 | 2483 | In [3]: all hello world\\ |
|
2484 | 2484 | Input in brackets: <hello world> |
|
2485 | 2485 | |
|
2486 | 2486 | You can also define aliases with parameters using %s specifiers (one |
|
2487 | 2487 | per parameter): |
|
2488 | 2488 | |
|
2489 | 2489 | In [1]: alias parts echo first %s second %s\\ |
|
2490 | 2490 | In [2]: %parts A B\\ |
|
2491 | 2491 | first A second B\\ |
|
2492 | 2492 | In [3]: %parts A\\ |
|
2493 | 2493 | Incorrect number of arguments: 2 expected.\\ |
|
2494 | 2494 | parts is an alias to: 'echo first %s second %s' |
|
2495 | 2495 | |
|
2496 | 2496 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2497 | 2497 | the other in your aliases. |
|
2498 | 2498 | |
|
2499 | 2499 | Aliases expand Python variables just like system calls using ! or !! |
|
2500 | 2500 | do: all expressions prefixed with '$' get expanded. For details of |
|
2501 | 2501 | the semantic rules, see PEP-215: |
|
2502 | 2502 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2503 | 2503 | IPython for variable expansion. If you want to access a true shell |
|
2504 | 2504 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2505 | 2505 | |
|
2506 | 2506 | In [6]: alias show echo\\ |
|
2507 | 2507 | In [7]: PATH='A Python string'\\ |
|
2508 | 2508 | In [8]: show $PATH\\ |
|
2509 | 2509 | A Python string\\ |
|
2510 | 2510 | In [9]: show $$PATH\\ |
|
2511 | 2511 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2512 | 2512 | |
|
2513 | 2513 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2514 | 2514 | and %rehashx functions, which automatically create aliases for the |
|
2515 | 2515 | contents of your $PATH. |
|
2516 | 2516 | |
|
2517 | 2517 | If called with no parameters, %alias prints the current alias table.""" |
|
2518 | 2518 | |
|
2519 | 2519 | par = parameter_s.strip() |
|
2520 | 2520 | if not par: |
|
2521 | 2521 | stored = self.db.get('stored_aliases', {} ) |
|
2522 | 2522 | atab = self.shell.alias_table |
|
2523 | 2523 | aliases = atab.keys() |
|
2524 | 2524 | aliases.sort() |
|
2525 | 2525 | res = [] |
|
2526 | 2526 | showlast = [] |
|
2527 | 2527 | for alias in aliases: |
|
2528 | 2528 | special = False |
|
2529 | 2529 | try: |
|
2530 | 2530 | tgt = atab[alias][1] |
|
2531 | 2531 | except (TypeError, AttributeError): |
|
2532 | 2532 | # unsubscriptable? probably a callable |
|
2533 | 2533 | tgt = atab[alias] |
|
2534 | 2534 | special = True |
|
2535 | 2535 | # 'interesting' aliases |
|
2536 | 2536 | if (alias in stored or |
|
2537 | 2537 | special or |
|
2538 | 2538 | alias.lower() != os.path.splitext(tgt)[0].lower() or |
|
2539 | 2539 | ' ' in tgt): |
|
2540 | 2540 | showlast.append((alias, tgt)) |
|
2541 | 2541 | else: |
|
2542 | 2542 | res.append((alias, tgt )) |
|
2543 | 2543 | |
|
2544 | 2544 | # show most interesting aliases last |
|
2545 | 2545 | res.extend(showlast) |
|
2546 | 2546 | print "Total number of aliases:",len(aliases) |
|
2547 | 2547 | return res |
|
2548 | 2548 | try: |
|
2549 | 2549 | alias,cmd = par.split(None,1) |
|
2550 | 2550 | except: |
|
2551 | 2551 | print OInspect.getdoc(self.magic_alias) |
|
2552 | 2552 | else: |
|
2553 | 2553 | nargs = cmd.count('%s') |
|
2554 | 2554 | if nargs>0 and cmd.find('%l')>=0: |
|
2555 | 2555 | error('The %s and %l specifiers are mutually exclusive ' |
|
2556 | 2556 | 'in alias definitions.') |
|
2557 | 2557 | else: # all looks OK |
|
2558 | 2558 | self.shell.alias_table[alias] = (nargs,cmd) |
|
2559 | 2559 | self.shell.alias_table_validate(verbose=0) |
|
2560 | 2560 | # end magic_alias |
|
2561 | 2561 | |
|
2562 | 2562 | def magic_unalias(self, parameter_s = ''): |
|
2563 | 2563 | """Remove an alias""" |
|
2564 | 2564 | |
|
2565 | 2565 | aname = parameter_s.strip() |
|
2566 | 2566 | if aname in self.shell.alias_table: |
|
2567 | 2567 | del self.shell.alias_table[aname] |
|
2568 | 2568 | stored = self.db.get('stored_aliases', {} ) |
|
2569 | 2569 | if aname in stored: |
|
2570 | 2570 | print "Removing %stored alias",aname |
|
2571 | 2571 | del stored[aname] |
|
2572 | 2572 | self.db['stored_aliases'] = stored |
|
2573 | 2573 | |
|
2574 | 2574 | |
|
2575 | 2575 | def magic_rehashx(self, parameter_s = ''): |
|
2576 | 2576 | """Update the alias table with all executable files in $PATH. |
|
2577 | 2577 | |
|
2578 | 2578 | This version explicitly checks that every entry in $PATH is a file |
|
2579 | 2579 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2580 | 2580 | |
|
2581 | 2581 | Under Windows, it checks executability as a match agains a |
|
2582 | 2582 | '|'-separated string of extensions, stored in the IPython config |
|
2583 | 2583 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2584 | 2584 | |
|
2585 | 2585 | This function also resets the root module cache of module completer, |
|
2586 | 2586 | used on slow filesystems. |
|
2587 | 2587 | """ |
|
2588 | 2588 | |
|
2589 | 2589 | |
|
2590 | 2590 | ip = self.api |
|
2591 | 2591 | |
|
2592 | 2592 | # for the benefit of module completer in ipy_completers.py |
|
2593 | 2593 | del ip.db['rootmodules'] |
|
2594 | 2594 | |
|
2595 | 2595 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2596 | 2596 | os.environ.get('PATH','').split(os.pathsep)] |
|
2597 | 2597 | path = filter(os.path.isdir,path) |
|
2598 | 2598 | |
|
2599 | 2599 | alias_table = self.shell.alias_table |
|
2600 | 2600 | syscmdlist = [] |
|
2601 | 2601 | if os.name == 'posix': |
|
2602 | 2602 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2603 | 2603 | os.access(fname,os.X_OK) |
|
2604 | 2604 | else: |
|
2605 | 2605 | |
|
2606 | 2606 | try: |
|
2607 | 2607 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2608 | 2608 | except KeyError: |
|
2609 | 2609 | winext = 'exe|com|bat|py' |
|
2610 | 2610 | if 'py' not in winext: |
|
2611 | 2611 | winext += '|py' |
|
2612 | 2612 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2613 | 2613 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2614 | 2614 | savedir = os.getcwd() |
|
2615 | 2615 | try: |
|
2616 | 2616 | # write the whole loop for posix/Windows so we don't have an if in |
|
2617 | 2617 | # the innermost part |
|
2618 | 2618 | if os.name == 'posix': |
|
2619 | 2619 | for pdir in path: |
|
2620 | 2620 | os.chdir(pdir) |
|
2621 | 2621 | for ff in os.listdir(pdir): |
|
2622 | 2622 | if isexec(ff) and ff not in self.shell.no_alias: |
|
2623 | 2623 | # each entry in the alias table must be (N,name), |
|
2624 | 2624 | # where N is the number of positional arguments of the |
|
2625 | 2625 | # alias. |
|
2626 | 2626 | alias_table[ff] = (0,ff) |
|
2627 | 2627 | syscmdlist.append(ff) |
|
2628 | 2628 | else: |
|
2629 | 2629 | for pdir in path: |
|
2630 | 2630 | os.chdir(pdir) |
|
2631 | 2631 | for ff in os.listdir(pdir): |
|
2632 | 2632 | base, ext = os.path.splitext(ff) |
|
2633 | 2633 | if isexec(ff) and base.lower() not in self.shell.no_alias: |
|
2634 | 2634 | if ext.lower() == '.exe': |
|
2635 | 2635 | ff = base |
|
2636 | 2636 | alias_table[base.lower()] = (0,ff) |
|
2637 | 2637 | syscmdlist.append(ff) |
|
2638 | 2638 | # Make sure the alias table doesn't contain keywords or builtins |
|
2639 | 2639 | self.shell.alias_table_validate() |
|
2640 | 2640 | # Call again init_auto_alias() so we get 'rm -i' and other |
|
2641 | 2641 | # modified aliases since %rehashx will probably clobber them |
|
2642 | 2642 | |
|
2643 | 2643 | # no, we don't want them. if %rehashx clobbers them, good, |
|
2644 | 2644 | # we'll probably get better versions |
|
2645 | 2645 | # self.shell.init_auto_alias() |
|
2646 | 2646 | db = ip.db |
|
2647 | 2647 | db['syscmdlist'] = syscmdlist |
|
2648 | 2648 | finally: |
|
2649 | 2649 | os.chdir(savedir) |
|
2650 | 2650 | |
|
2651 | 2651 | def magic_pwd(self, parameter_s = ''): |
|
2652 | 2652 | """Return the current working directory path.""" |
|
2653 | 2653 | return os.getcwd() |
|
2654 | 2654 | |
|
2655 | 2655 | def magic_cd(self, parameter_s=''): |
|
2656 | 2656 | """Change the current working directory. |
|
2657 | 2657 | |
|
2658 | 2658 | This command automatically maintains an internal list of directories |
|
2659 | 2659 | you visit during your IPython session, in the variable _dh. The |
|
2660 | 2660 | command %dhist shows this history nicely formatted. You can also |
|
2661 | 2661 | do 'cd -<tab>' to see directory history conveniently. |
|
2662 | 2662 | |
|
2663 | 2663 | Usage: |
|
2664 | 2664 | |
|
2665 | 2665 | cd 'dir': changes to directory 'dir'. |
|
2666 | 2666 | |
|
2667 | 2667 | cd -: changes to the last visited directory. |
|
2668 | 2668 | |
|
2669 | 2669 | cd -<n>: changes to the n-th directory in the directory history. |
|
2670 | 2670 | |
|
2671 | 2671 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2672 | 2672 | (note: cd <bookmark_name> is enough if there is no |
|
2673 | 2673 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2674 | 2674 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2675 | 2675 | |
|
2676 | 2676 | Options: |
|
2677 | 2677 | |
|
2678 | 2678 | -q: quiet. Do not print the working directory after the cd command is |
|
2679 | 2679 | executed. By default IPython's cd command does print this directory, |
|
2680 | 2680 | since the default prompts do not display path information. |
|
2681 | 2681 | |
|
2682 | 2682 | Note that !cd doesn't work for this purpose because the shell where |
|
2683 | 2683 | !command runs is immediately discarded after executing 'command'.""" |
|
2684 | 2684 | |
|
2685 | 2685 | parameter_s = parameter_s.strip() |
|
2686 | 2686 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2687 | 2687 | |
|
2688 | 2688 | oldcwd = os.getcwd() |
|
2689 | 2689 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2690 | 2690 | # jump in directory history by number |
|
2691 | 2691 | if numcd: |
|
2692 | 2692 | nn = int(numcd.group(2)) |
|
2693 | 2693 | try: |
|
2694 | 2694 | ps = self.shell.user_ns['_dh'][nn] |
|
2695 | 2695 | except IndexError: |
|
2696 | 2696 | print 'The requested directory does not exist in history.' |
|
2697 | 2697 | return |
|
2698 | 2698 | else: |
|
2699 | 2699 | opts = {} |
|
2700 | 2700 | else: |
|
2701 | 2701 | #turn all non-space-escaping backslashes to slashes, |
|
2702 | 2702 | # for c:\windows\directory\names\ |
|
2703 | 2703 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2704 | 2704 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2705 | 2705 | # jump to previous |
|
2706 | 2706 | if ps == '-': |
|
2707 | 2707 | try: |
|
2708 | 2708 | ps = self.shell.user_ns['_dh'][-2] |
|
2709 | 2709 | except IndexError: |
|
2710 | 2710 | raise UsageError('%cd -: No previous directory to change to.') |
|
2711 | 2711 | # jump to bookmark if needed |
|
2712 | 2712 | else: |
|
2713 | 2713 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2714 | 2714 | bkms = self.db.get('bookmarks', {}) |
|
2715 | 2715 | |
|
2716 | 2716 | if bkms.has_key(ps): |
|
2717 | 2717 | target = bkms[ps] |
|
2718 | 2718 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2719 | 2719 | ps = target |
|
2720 | 2720 | else: |
|
2721 | 2721 | if opts.has_key('b'): |
|
2722 | 2722 | raise UsageError("Bookmark '%s' not found. " |
|
2723 | 2723 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2724 | 2724 | |
|
2725 | 2725 | # at this point ps should point to the target dir |
|
2726 | 2726 | if ps: |
|
2727 | 2727 | try: |
|
2728 | 2728 | os.chdir(os.path.expanduser(ps)) |
|
2729 | 2729 | if self.shell.rc.term_title: |
|
2730 | 2730 | #print 'set term title:',self.shell.rc.term_title # dbg |
|
2731 | 2731 | ttitle = 'IPy ' + abbrev_cwd() |
|
2732 | 2732 | platutils.set_term_title(ttitle) |
|
2733 | 2733 | except OSError: |
|
2734 | 2734 | print sys.exc_info()[1] |
|
2735 | 2735 | else: |
|
2736 | 2736 | cwd = os.getcwd() |
|
2737 | 2737 | dhist = self.shell.user_ns['_dh'] |
|
2738 | 2738 | if oldcwd != cwd: |
|
2739 | 2739 | dhist.append(cwd) |
|
2740 | 2740 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2741 | 2741 | |
|
2742 | 2742 | else: |
|
2743 | 2743 | os.chdir(self.shell.home_dir) |
|
2744 | 2744 | if self.shell.rc.term_title: |
|
2745 | 2745 | platutils.set_term_title("IPy ~") |
|
2746 | 2746 | cwd = os.getcwd() |
|
2747 | 2747 | dhist = self.shell.user_ns['_dh'] |
|
2748 | 2748 | |
|
2749 | 2749 | if oldcwd != cwd: |
|
2750 | 2750 | dhist.append(cwd) |
|
2751 | 2751 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2752 | 2752 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2753 | 2753 | print self.shell.user_ns['_dh'][-1] |
|
2754 | 2754 | |
|
2755 | 2755 | |
|
2756 | 2756 | def magic_env(self, parameter_s=''): |
|
2757 | 2757 | """List environment variables.""" |
|
2758 | 2758 | |
|
2759 | 2759 | return os.environ.data |
|
2760 | 2760 | |
|
2761 | 2761 | def magic_pushd(self, parameter_s=''): |
|
2762 | 2762 | """Place the current dir on stack and change directory. |
|
2763 | 2763 | |
|
2764 | 2764 | Usage:\\ |
|
2765 | 2765 | %pushd ['dirname'] |
|
2766 | 2766 | """ |
|
2767 | 2767 | |
|
2768 | 2768 | dir_s = self.shell.dir_stack |
|
2769 | 2769 | tgt = os.path.expanduser(parameter_s) |
|
2770 | 2770 | cwd = os.getcwd().replace(self.home_dir,'~') |
|
2771 | 2771 | if tgt: |
|
2772 | 2772 | self.magic_cd(parameter_s) |
|
2773 | 2773 | dir_s.insert(0,cwd) |
|
2774 | 2774 | return self.magic_dirs() |
|
2775 | 2775 | |
|
2776 | 2776 | def magic_popd(self, parameter_s=''): |
|
2777 | 2777 | """Change to directory popped off the top of the stack. |
|
2778 | 2778 | """ |
|
2779 | 2779 | if not self.shell.dir_stack: |
|
2780 | 2780 | raise UsageError("%popd on empty stack") |
|
2781 | 2781 | top = self.shell.dir_stack.pop(0) |
|
2782 | 2782 | self.magic_cd(top) |
|
2783 | 2783 | print "popd ->",top |
|
2784 | 2784 | |
|
2785 | 2785 | def magic_dirs(self, parameter_s=''): |
|
2786 | 2786 | """Return the current directory stack.""" |
|
2787 | 2787 | |
|
2788 | 2788 | return self.shell.dir_stack |
|
2789 | 2789 | |
|
2790 | 2790 | def magic_dhist(self, parameter_s=''): |
|
2791 | 2791 | """Print your history of visited directories. |
|
2792 | 2792 | |
|
2793 | 2793 | %dhist -> print full history\\ |
|
2794 | 2794 | %dhist n -> print last n entries only\\ |
|
2795 | 2795 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2796 | 2796 | |
|
2797 | 2797 | This history is automatically maintained by the %cd command, and |
|
2798 | 2798 | always available as the global list variable _dh. You can use %cd -<n> |
|
2799 | 2799 | to go to directory number <n>. |
|
2800 | 2800 | |
|
2801 | 2801 | Note that most of time, you should view directory history by entering |
|
2802 | 2802 | cd -<TAB>. |
|
2803 | 2803 | |
|
2804 | 2804 | """ |
|
2805 | 2805 | |
|
2806 | 2806 | dh = self.shell.user_ns['_dh'] |
|
2807 | 2807 | if parameter_s: |
|
2808 | 2808 | try: |
|
2809 | 2809 | args = map(int,parameter_s.split()) |
|
2810 | 2810 | except: |
|
2811 | 2811 | self.arg_err(Magic.magic_dhist) |
|
2812 | 2812 | return |
|
2813 | 2813 | if len(args) == 1: |
|
2814 | 2814 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2815 | 2815 | elif len(args) == 2: |
|
2816 | 2816 | ini,fin = args |
|
2817 | 2817 | else: |
|
2818 | 2818 | self.arg_err(Magic.magic_dhist) |
|
2819 | 2819 | return |
|
2820 | 2820 | else: |
|
2821 | 2821 | ini,fin = 0,len(dh) |
|
2822 | 2822 | nlprint(dh, |
|
2823 | 2823 | header = 'Directory history (kept in _dh)', |
|
2824 | 2824 | start=ini,stop=fin) |
|
2825 | 2825 | |
|
2826 | 2826 | |
|
2827 | 2827 | def magic_sc(self, parameter_s=''): |
|
2828 | 2828 | """Shell capture - execute a shell command and capture its output. |
|
2829 | 2829 | |
|
2830 | 2830 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2831 | 2831 | |
|
2832 | 2832 | You should use the form 'var = !command' instead. Example: |
|
2833 | 2833 | |
|
2834 | 2834 | "%sc -l myfiles = ls ~" should now be written as |
|
2835 | 2835 | |
|
2836 | 2836 | "myfiles = !ls ~" |
|
2837 | 2837 | |
|
2838 | 2838 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2839 | 2839 | below. |
|
2840 | 2840 | |
|
2841 | 2841 | -- |
|
2842 | 2842 | %sc [options] varname=command |
|
2843 | 2843 | |
|
2844 | 2844 | IPython will run the given command using commands.getoutput(), and |
|
2845 | 2845 | will then update the user's interactive namespace with a variable |
|
2846 | 2846 | called varname, containing the value of the call. Your command can |
|
2847 | 2847 | contain shell wildcards, pipes, etc. |
|
2848 | 2848 | |
|
2849 | 2849 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2850 | 2850 | supply must follow Python's standard conventions for valid names. |
|
2851 | 2851 | |
|
2852 | 2852 | (A special format without variable name exists for internal use) |
|
2853 | 2853 | |
|
2854 | 2854 | Options: |
|
2855 | 2855 | |
|
2856 | 2856 | -l: list output. Split the output on newlines into a list before |
|
2857 | 2857 | assigning it to the given variable. By default the output is stored |
|
2858 | 2858 | as a single string. |
|
2859 | 2859 | |
|
2860 | 2860 | -v: verbose. Print the contents of the variable. |
|
2861 | 2861 | |
|
2862 | 2862 | In most cases you should not need to split as a list, because the |
|
2863 | 2863 | returned value is a special type of string which can automatically |
|
2864 | 2864 | provide its contents either as a list (split on newlines) or as a |
|
2865 | 2865 | space-separated string. These are convenient, respectively, either |
|
2866 | 2866 | for sequential processing or to be passed to a shell command. |
|
2867 | 2867 | |
|
2868 | 2868 | For example: |
|
2869 | 2869 | |
|
2870 | 2870 | # Capture into variable a |
|
2871 | 2871 | In [9]: sc a=ls *py |
|
2872 | 2872 | |
|
2873 | 2873 | # a is a string with embedded newlines |
|
2874 | 2874 | In [10]: a |
|
2875 | 2875 | Out[10]: 'setup.py\nwin32_manual_post_install.py' |
|
2876 | 2876 | |
|
2877 | 2877 | # which can be seen as a list: |
|
2878 | 2878 | In [11]: a.l |
|
2879 | 2879 | Out[11]: ['setup.py', 'win32_manual_post_install.py'] |
|
2880 | 2880 | |
|
2881 | 2881 | # or as a whitespace-separated string: |
|
2882 | 2882 | In [12]: a.s |
|
2883 | 2883 | Out[12]: 'setup.py win32_manual_post_install.py' |
|
2884 | 2884 | |
|
2885 | 2885 | # a.s is useful to pass as a single command line: |
|
2886 | 2886 | In [13]: !wc -l $a.s |
|
2887 | 2887 | 146 setup.py |
|
2888 | 2888 | 130 win32_manual_post_install.py |
|
2889 | 2889 | 276 total |
|
2890 | 2890 | |
|
2891 | 2891 | # while the list form is useful to loop over: |
|
2892 | 2892 | In [14]: for f in a.l: |
|
2893 | 2893 | ....: !wc -l $f |
|
2894 | 2894 | ....: |
|
2895 | 2895 | 146 setup.py |
|
2896 | 2896 | 130 win32_manual_post_install.py |
|
2897 | 2897 | |
|
2898 | 2898 | Similiarly, the lists returned by the -l option are also special, in |
|
2899 | 2899 | the sense that you can equally invoke the .s attribute on them to |
|
2900 | 2900 | automatically get a whitespace-separated string from their contents: |
|
2901 | 2901 | |
|
2902 | 2902 | In [1]: sc -l b=ls *py |
|
2903 | 2903 | |
|
2904 | 2904 | In [2]: b |
|
2905 | 2905 | Out[2]: ['setup.py', 'win32_manual_post_install.py'] |
|
2906 | 2906 | |
|
2907 | 2907 | In [3]: b.s |
|
2908 | 2908 | Out[3]: 'setup.py win32_manual_post_install.py' |
|
2909 | 2909 | |
|
2910 | 2910 | In summary, both the lists and strings used for ouptut capture have |
|
2911 | 2911 | the following special attributes: |
|
2912 | 2912 | |
|
2913 | 2913 | .l (or .list) : value as list. |
|
2914 | 2914 | .n (or .nlstr): value as newline-separated string. |
|
2915 | 2915 | .s (or .spstr): value as space-separated string. |
|
2916 | 2916 | """ |
|
2917 | 2917 | |
|
2918 | 2918 | opts,args = self.parse_options(parameter_s,'lv') |
|
2919 | 2919 | # Try to get a variable name and command to run |
|
2920 | 2920 | try: |
|
2921 | 2921 | # the variable name must be obtained from the parse_options |
|
2922 | 2922 | # output, which uses shlex.split to strip options out. |
|
2923 | 2923 | var,_ = args.split('=',1) |
|
2924 | 2924 | var = var.strip() |
|
2925 | 2925 | # But the the command has to be extracted from the original input |
|
2926 | 2926 | # parameter_s, not on what parse_options returns, to avoid the |
|
2927 | 2927 | # quote stripping which shlex.split performs on it. |
|
2928 | 2928 | _,cmd = parameter_s.split('=',1) |
|
2929 | 2929 | except ValueError: |
|
2930 | 2930 | var,cmd = '','' |
|
2931 | 2931 | # If all looks ok, proceed |
|
2932 | 2932 | out,err = self.shell.getoutputerror(cmd) |
|
2933 | 2933 | if err: |
|
2934 | 2934 | print >> Term.cerr,err |
|
2935 | 2935 | if opts.has_key('l'): |
|
2936 | 2936 | out = SList(out.split('\n')) |
|
2937 | 2937 | else: |
|
2938 | 2938 | out = LSString(out) |
|
2939 | 2939 | if opts.has_key('v'): |
|
2940 | 2940 | print '%s ==\n%s' % (var,pformat(out)) |
|
2941 | 2941 | if var: |
|
2942 | 2942 | self.shell.user_ns.update({var:out}) |
|
2943 | 2943 | else: |
|
2944 | 2944 | return out |
|
2945 | 2945 | |
|
2946 | 2946 | def magic_sx(self, parameter_s=''): |
|
2947 | 2947 | """Shell execute - run a shell command and capture its output. |
|
2948 | 2948 | |
|
2949 | 2949 | %sx command |
|
2950 | 2950 | |
|
2951 | 2951 | IPython will run the given command using commands.getoutput(), and |
|
2952 | 2952 | return the result formatted as a list (split on '\\n'). Since the |
|
2953 | 2953 | output is _returned_, it will be stored in ipython's regular output |
|
2954 | 2954 | cache Out[N] and in the '_N' automatic variables. |
|
2955 | 2955 | |
|
2956 | 2956 | Notes: |
|
2957 | 2957 | |
|
2958 | 2958 | 1) If an input line begins with '!!', then %sx is automatically |
|
2959 | 2959 | invoked. That is, while: |
|
2960 | 2960 | !ls |
|
2961 | 2961 | causes ipython to simply issue system('ls'), typing |
|
2962 | 2962 | !!ls |
|
2963 | 2963 | is a shorthand equivalent to: |
|
2964 | 2964 | %sx ls |
|
2965 | 2965 | |
|
2966 | 2966 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
2967 | 2967 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
2968 | 2968 | to process line-oriented shell output via further python commands. |
|
2969 | 2969 | %sc is meant to provide much finer control, but requires more |
|
2970 | 2970 | typing. |
|
2971 | 2971 | |
|
2972 | 2972 | 3) Just like %sc -l, this is a list with special attributes: |
|
2973 | 2973 | |
|
2974 | 2974 | .l (or .list) : value as list. |
|
2975 | 2975 | .n (or .nlstr): value as newline-separated string. |
|
2976 | 2976 | .s (or .spstr): value as whitespace-separated string. |
|
2977 | 2977 | |
|
2978 | 2978 | This is very useful when trying to use such lists as arguments to |
|
2979 | 2979 | system commands.""" |
|
2980 | 2980 | |
|
2981 | 2981 | if parameter_s: |
|
2982 | 2982 | out,err = self.shell.getoutputerror(parameter_s) |
|
2983 | 2983 | if err: |
|
2984 | 2984 | print >> Term.cerr,err |
|
2985 | 2985 | return SList(out.split('\n')) |
|
2986 | 2986 | |
|
2987 | 2987 | def magic_bg(self, parameter_s=''): |
|
2988 | 2988 | """Run a job in the background, in a separate thread. |
|
2989 | 2989 | |
|
2990 | 2990 | For example, |
|
2991 | 2991 | |
|
2992 | 2992 | %bg myfunc(x,y,z=1) |
|
2993 | 2993 | |
|
2994 | 2994 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the |
|
2995 | 2995 | execution starts, a message will be printed indicating the job |
|
2996 | 2996 | number. If your job number is 5, you can use |
|
2997 | 2997 | |
|
2998 | 2998 | myvar = jobs.result(5) or myvar = jobs[5].result |
|
2999 | 2999 | |
|
3000 | 3000 | to assign this result to variable 'myvar'. |
|
3001 | 3001 | |
|
3002 | 3002 | IPython has a job manager, accessible via the 'jobs' object. You can |
|
3003 | 3003 | type jobs? to get more information about it, and use jobs.<TAB> to see |
|
3004 | 3004 | its attributes. All attributes not starting with an underscore are |
|
3005 | 3005 | meant for public use. |
|
3006 | 3006 | |
|
3007 | 3007 | In particular, look at the jobs.new() method, which is used to create |
|
3008 | 3008 | new jobs. This magic %bg function is just a convenience wrapper |
|
3009 | 3009 | around jobs.new(), for expression-based jobs. If you want to create a |
|
3010 | 3010 | new job with an explicit function object and arguments, you must call |
|
3011 | 3011 | jobs.new() directly. |
|
3012 | 3012 | |
|
3013 | 3013 | The jobs.new docstring also describes in detail several important |
|
3014 | 3014 | caveats associated with a thread-based model for background job |
|
3015 | 3015 | execution. Type jobs.new? for details. |
|
3016 | 3016 | |
|
3017 | 3017 | You can check the status of all jobs with jobs.status(). |
|
3018 | 3018 | |
|
3019 | 3019 | The jobs variable is set by IPython into the Python builtin namespace. |
|
3020 | 3020 | If you ever declare a variable named 'jobs', you will shadow this |
|
3021 | 3021 | name. You can either delete your global jobs variable to regain |
|
3022 | 3022 | access to the job manager, or make a new name and assign it manually |
|
3023 | 3023 | to the manager (stored in IPython's namespace). For example, to |
|
3024 | 3024 | assign the job manager to the Jobs name, use: |
|
3025 | 3025 | |
|
3026 | 3026 | Jobs = __builtins__.jobs""" |
|
3027 | 3027 | |
|
3028 | 3028 | self.shell.jobs.new(parameter_s,self.shell.user_ns) |
|
3029 | 3029 | |
|
3030 | 3030 | def magic_r(self, parameter_s=''): |
|
3031 | 3031 | """Repeat previous input. |
|
3032 | 3032 | |
|
3033 | 3033 | Note: Consider using the more powerfull %rep instead! |
|
3034 | 3034 | |
|
3035 | 3035 | If given an argument, repeats the previous command which starts with |
|
3036 | 3036 | the same string, otherwise it just repeats the previous input. |
|
3037 | 3037 | |
|
3038 | 3038 | Shell escaped commands (with ! as first character) are not recognized |
|
3039 | 3039 | by this system, only pure python code and magic commands. |
|
3040 | 3040 | """ |
|
3041 | 3041 | |
|
3042 | 3042 | start = parameter_s.strip() |
|
3043 | 3043 | esc_magic = self.shell.ESC_MAGIC |
|
3044 | 3044 | # Identify magic commands even if automagic is on (which means |
|
3045 | 3045 | # the in-memory version is different from that typed by the user). |
|
3046 | 3046 | if self.shell.rc.automagic: |
|
3047 | 3047 | start_magic = esc_magic+start |
|
3048 | 3048 | else: |
|
3049 | 3049 | start_magic = start |
|
3050 | 3050 | # Look through the input history in reverse |
|
3051 | 3051 | for n in range(len(self.shell.input_hist)-2,0,-1): |
|
3052 | 3052 | input = self.shell.input_hist[n] |
|
3053 | 3053 | # skip plain 'r' lines so we don't recurse to infinity |
|
3054 | 3054 | if input != '_ip.magic("r")\n' and \ |
|
3055 | 3055 | (input.startswith(start) or input.startswith(start_magic)): |
|
3056 | 3056 | #print 'match',`input` # dbg |
|
3057 | 3057 | print 'Executing:',input, |
|
3058 | 3058 | self.shell.runlines(input) |
|
3059 | 3059 | return |
|
3060 | 3060 | print 'No previous input matching `%s` found.' % start |
|
3061 | 3061 | |
|
3062 | 3062 | |
|
3063 | 3063 | def magic_bookmark(self, parameter_s=''): |
|
3064 | 3064 | """Manage IPython's bookmark system. |
|
3065 | 3065 | |
|
3066 | 3066 | %bookmark <name> - set bookmark to current dir |
|
3067 | 3067 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3068 | 3068 | %bookmark -l - list all bookmarks |
|
3069 | 3069 | %bookmark -d <name> - remove bookmark |
|
3070 | 3070 | %bookmark -r - remove all bookmarks |
|
3071 | 3071 | |
|
3072 | 3072 | You can later on access a bookmarked folder with: |
|
3073 | 3073 | %cd -b <name> |
|
3074 | 3074 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3075 | 3075 | there is such a bookmark defined. |
|
3076 | 3076 | |
|
3077 | 3077 | Your bookmarks persist through IPython sessions, but they are |
|
3078 | 3078 | associated with each profile.""" |
|
3079 | 3079 | |
|
3080 | 3080 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3081 | 3081 | if len(args) > 2: |
|
3082 | 3082 | raise UsageError("%bookmark: too many arguments") |
|
3083 | 3083 | |
|
3084 | 3084 | bkms = self.db.get('bookmarks',{}) |
|
3085 | 3085 | |
|
3086 | 3086 | if opts.has_key('d'): |
|
3087 | 3087 | try: |
|
3088 | 3088 | todel = args[0] |
|
3089 | 3089 | except IndexError: |
|
3090 | 3090 | raise UsageError( |
|
3091 | 3091 | "%bookmark -d: must provide a bookmark to delete") |
|
3092 | 3092 | else: |
|
3093 | 3093 | try: |
|
3094 | 3094 | del bkms[todel] |
|
3095 | 3095 | except KeyError: |
|
3096 | 3096 | raise UsageError( |
|
3097 | 3097 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3098 | 3098 | |
|
3099 | 3099 | elif opts.has_key('r'): |
|
3100 | 3100 | bkms = {} |
|
3101 | 3101 | elif opts.has_key('l'): |
|
3102 | 3102 | bks = bkms.keys() |
|
3103 | 3103 | bks.sort() |
|
3104 | 3104 | if bks: |
|
3105 | 3105 | size = max(map(len,bks)) |
|
3106 | 3106 | else: |
|
3107 | 3107 | size = 0 |
|
3108 | 3108 | fmt = '%-'+str(size)+'s -> %s' |
|
3109 | 3109 | print 'Current bookmarks:' |
|
3110 | 3110 | for bk in bks: |
|
3111 | 3111 | print fmt % (bk,bkms[bk]) |
|
3112 | 3112 | else: |
|
3113 | 3113 | if not args: |
|
3114 | 3114 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3115 | 3115 | elif len(args)==1: |
|
3116 | 3116 | bkms[args[0]] = os.getcwd() |
|
3117 | 3117 | elif len(args)==2: |
|
3118 | 3118 | bkms[args[0]] = args[1] |
|
3119 | 3119 | self.db['bookmarks'] = bkms |
|
3120 | 3120 | |
|
3121 | 3121 | def magic_pycat(self, parameter_s=''): |
|
3122 | 3122 | """Show a syntax-highlighted file through a pager. |
|
3123 | 3123 | |
|
3124 | 3124 | This magic is similar to the cat utility, but it will assume the file |
|
3125 | 3125 | to be Python source and will show it with syntax highlighting. """ |
|
3126 | 3126 | |
|
3127 | 3127 | try: |
|
3128 | 3128 | filename = get_py_filename(parameter_s) |
|
3129 | 3129 | cont = file_read(filename) |
|
3130 | 3130 | except IOError: |
|
3131 | 3131 | try: |
|
3132 | 3132 | cont = eval(parameter_s,self.user_ns) |
|
3133 | 3133 | except NameError: |
|
3134 | 3134 | cont = None |
|
3135 | 3135 | if cont is None: |
|
3136 | 3136 | print "Error: no such file or variable" |
|
3137 | 3137 | return |
|
3138 | 3138 | |
|
3139 | 3139 | page(self.shell.pycolorize(cont), |
|
3140 | 3140 | screen_lines=self.shell.rc.screen_length) |
|
3141 | 3141 | |
|
3142 | 3142 | def magic_cpaste(self, parameter_s=''): |
|
3143 | 3143 | """Allows you to paste & execute a pre-formatted code block from clipboard |
|
3144 | 3144 | |
|
3145 | 3145 | You must terminate the block with '--' (two minus-signs) alone on the |
|
3146 | 3146 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' |
|
3147 | 3147 | is the new sentinel for this operation) |
|
3148 | 3148 | |
|
3149 | 3149 | The block is dedented prior to execution to enable execution of method |
|
3150 | 3150 | definitions. '>' and '+' characters at the beginning of a line are |
|
3151 | 3151 | ignored, to allow pasting directly from e-mails or diff files. The |
|
3152 | 3152 | executed block is also assigned to variable named 'pasted_block' for |
|
3153 | 3153 | later editing with '%edit pasted_block'. |
|
3154 | 3154 | |
|
3155 | 3155 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
3156 | 3156 | This assigns the pasted block to variable 'foo' as string, without |
|
3157 | 3157 | dedenting or executing it. |
|
3158 | 3158 | |
|
3159 | 3159 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
3160 | 3160 | Just press enter and type -- (and press enter again) and the block |
|
3161 | 3161 | will be what was just pasted. |
|
3162 | 3162 | |
|
3163 | 3163 | IPython statements (magics, shell escapes) are not supported (yet). |
|
3164 | 3164 | """ |
|
3165 | 3165 | opts,args = self.parse_options(parameter_s,'s:',mode='string') |
|
3166 | 3166 | par = args.strip() |
|
3167 | 3167 | sentinel = opts.get('s','--') |
|
3168 | 3168 | |
|
3169 | 3169 | strip_from_start = [re.compile(e) for e in |
|
3170 | 3170 | ['^(.?>)+','^In \[\d+\]:','^\++']] |
|
3171 | 3171 | from IPython import iplib |
|
3172 | 3172 | lines = [] |
|
3173 | 3173 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3174 | 3174 | while 1: |
|
3175 | 3175 | l = iplib.raw_input_original(':') |
|
3176 | 3176 | if l ==sentinel: |
|
3177 | 3177 | break |
|
3178 | 3178 | |
|
3179 | 3179 | for pat in strip_from_start: |
|
3180 | 3180 | l = pat.sub('',l) |
|
3181 | 3181 | lines.append(l) |
|
3182 | 3182 | |
|
3183 | 3183 | block = "\n".join(lines) + '\n' |
|
3184 | 3184 | #print "block:\n",block |
|
3185 | 3185 | if not par: |
|
3186 | 3186 | b = textwrap.dedent(block) |
|
3187 | 3187 | exec b in self.user_ns |
|
3188 | 3188 | self.user_ns['pasted_block'] = b |
|
3189 | 3189 | else: |
|
3190 | 3190 | self.user_ns[par] = block |
|
3191 | 3191 | print "Block assigned to '%s'" % par |
|
3192 | 3192 | |
|
3193 | 3193 | def magic_quickref(self,arg): |
|
3194 | 3194 | """ Show a quick reference sheet """ |
|
3195 | 3195 | import IPython.usage |
|
3196 | 3196 | qr = IPython.usage.quick_reference + self.magic_magic('-brief') |
|
3197 | 3197 | |
|
3198 | 3198 | page(qr) |
|
3199 | 3199 | |
|
3200 | 3200 | def magic_upgrade(self,arg): |
|
3201 | 3201 | """ Upgrade your IPython installation |
|
3202 | 3202 | |
|
3203 | 3203 | This will copy the config files that don't yet exist in your |
|
3204 | 3204 | ipython dir from the system config dir. Use this after upgrading |
|
3205 | 3205 | IPython if you don't wish to delete your .ipython dir. |
|
3206 | 3206 | |
|
3207 | 3207 | Call with -nolegacy to get rid of ipythonrc* files (recommended for |
|
3208 | 3208 | new users) |
|
3209 | 3209 | |
|
3210 | 3210 | """ |
|
3211 | 3211 | ip = self.getapi() |
|
3212 | 3212 | ipinstallation = path(IPython.__file__).dirname() |
|
3213 | 3213 | upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py') |
|
3214 | 3214 | src_config = ipinstallation / 'UserConfig' |
|
3215 | 3215 | userdir = path(ip.options.ipythondir) |
|
3216 | 3216 | cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir) |
|
3217 | 3217 | print ">",cmd |
|
3218 | 3218 | shell(cmd) |
|
3219 | 3219 | if arg == '-nolegacy': |
|
3220 | 3220 | legacy = userdir.files('ipythonrc*') |
|
3221 | 3221 | print "Nuking legacy files:",legacy |
|
3222 | 3222 | |
|
3223 | 3223 | [p.remove() for p in legacy] |
|
3224 | 3224 | suffix = (sys.platform == 'win32' and '.ini' or '') |
|
3225 | 3225 | (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n') |
|
3226 | 3226 | |
|
3227 | 3227 | |
|
3228 | 3228 | def magic_doctest_mode(self,parameter_s=''): |
|
3229 | 3229 | """Toggle doctest mode on and off. |
|
3230 | 3230 | |
|
3231 | 3231 | This mode allows you to toggle the prompt behavior between normal |
|
3232 | 3232 | IPython prompts and ones that are as similar to the default IPython |
|
3233 | 3233 | interpreter as possible. |
|
3234 | 3234 | |
|
3235 | 3235 | It also supports the pasting of code snippets that have leading '>>>' |
|
3236 | 3236 | and '...' prompts in them. This means that you can paste doctests from |
|
3237 | 3237 | files or docstrings (even if they have leading whitespace), and the |
|
3238 | 3238 | code will execute correctly. You can then use '%history -tn' to see |
|
3239 | 3239 | the translated history without line numbers; this will give you the |
|
3240 | 3240 | input after removal of all the leading prompts and whitespace, which |
|
3241 | 3241 | can be pasted back into an editor. |
|
3242 | 3242 | |
|
3243 | 3243 | With these features, you can switch into this mode easily whenever you |
|
3244 | 3244 | need to do testing and changes to doctests, without having to leave |
|
3245 | 3245 | your existing IPython session. |
|
3246 | 3246 | """ |
|
3247 | 3247 | |
|
3248 | 3248 | # XXX - Fix this to have cleaner activate/deactivate calls. |
|
3249 | 3249 | from IPython.Extensions import InterpreterPasteInput as ipaste |
|
3250 | 3250 | from IPython.ipstruct import Struct |
|
3251 | 3251 | |
|
3252 | 3252 | # Shorthands |
|
3253 | 3253 | shell = self.shell |
|
3254 | 3254 | oc = shell.outputcache |
|
3255 | 3255 | rc = shell.rc |
|
3256 | 3256 | meta = shell.meta |
|
3257 | 3257 | # dstore is a data store kept in the instance metadata bag to track any |
|
3258 | 3258 | # changes we make, so we can undo them later. |
|
3259 | 3259 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3260 | 3260 | save_dstore = dstore.setdefault |
|
3261 | 3261 | |
|
3262 | 3262 | # save a few values we'll need to recover later |
|
3263 | 3263 | mode = save_dstore('mode',False) |
|
3264 | 3264 | save_dstore('rc_pprint',rc.pprint) |
|
3265 | 3265 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3266 | 3266 | save_dstore('rc_separate_out',rc.separate_out) |
|
3267 | 3267 | save_dstore('rc_separate_out2',rc.separate_out2) |
|
3268 | 3268 | save_dstore('rc_prompts_pad_left',rc.prompts_pad_left) |
|
3269 | 3269 | |
|
3270 | 3270 | if mode == False: |
|
3271 | 3271 | # turn on |
|
3272 | 3272 | ipaste.activate_prefilter() |
|
3273 | 3273 | |
|
3274 | 3274 | oc.prompt1.p_template = '>>> ' |
|
3275 | 3275 | oc.prompt2.p_template = '... ' |
|
3276 | 3276 | oc.prompt_out.p_template = '' |
|
3277 | 3277 | |
|
3278 | 3278 | oc.output_sep = '' |
|
3279 | 3279 | oc.output_sep2 = '' |
|
3280 | 3280 | |
|
3281 | 3281 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3282 | 3282 | oc.prompt_out.pad_left = False |
|
3283 | 3283 | |
|
3284 | 3284 | rc.pprint = False |
|
3285 | 3285 | |
|
3286 | 3286 | shell.magic_xmode('Plain') |
|
3287 | 3287 | |
|
3288 | 3288 | else: |
|
3289 | 3289 | # turn off |
|
3290 | 3290 | ipaste.deactivate_prefilter() |
|
3291 | 3291 | |
|
3292 | 3292 | oc.prompt1.p_template = rc.prompt_in1 |
|
3293 | 3293 | oc.prompt2.p_template = rc.prompt_in2 |
|
3294 | 3294 | oc.prompt_out.p_template = rc.prompt_out |
|
3295 | 3295 | |
|
3296 | 3296 | oc.output_sep = dstore.rc_separate_out |
|
3297 | 3297 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3298 | 3298 | |
|
3299 | 3299 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3300 | 3300 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3301 | 3301 | |
|
3302 | 3302 | rc.pprint = dstore.rc_pprint |
|
3303 | 3303 | |
|
3304 | 3304 | shell.magic_xmode(dstore.xmode) |
|
3305 | 3305 | |
|
3306 | 3306 | # Store new mode and inform |
|
3307 | 3307 | dstore.mode = bool(1-int(mode)) |
|
3308 | 3308 | print 'Doctest mode is:', |
|
3309 | 3309 | print ['OFF','ON'][dstore.mode] |
|
3310 | 3310 | |
|
3311 | 3311 | # end Magic |
@@ -1,460 +1,460 b'' | |||
|
1 | 1 | #!/usr/bin/python |
|
2 | 2 | # -*- coding: iso-8859-15 -*- |
|
3 | 3 | ''' |
|
4 | 4 | Provides IPython remote instance. |
|
5 | 5 | |
|
6 | 6 | @author: Laurent Dufrechou |
|
7 | 7 | laurent.dufrechou _at_ gmail.com |
|
8 | 8 | @license: BSD |
|
9 | 9 | |
|
10 | 10 | All rights reserved. This program and the accompanying materials are made |
|
11 | 11 | available under the terms of the BSD which accompanies this distribution, and |
|
12 | 12 | is available at U{http://www.opensource.org/licenses/bsd-license.php} |
|
13 | 13 | ''' |
|
14 | 14 | |
|
15 | 15 | __version__ = 0.9 |
|
16 | 16 | __author__ = "Laurent Dufrechou" |
|
17 | 17 | __email__ = "laurent.dufrechou _at_ gmail.com" |
|
18 | 18 | __license__ = "BSD" |
|
19 | 19 | |
|
20 | 20 | import re |
|
21 | 21 | import sys |
|
22 | 22 | import os |
|
23 | 23 | import locale |
|
24 | 24 | import time |
|
25 | 25 | import pydoc,__builtin__,site |
|
26 | 26 | from thread_ex import ThreadEx |
|
27 | 27 | from StringIO import StringIO |
|
28 | 28 | |
|
29 | 29 | try: |
|
30 | 30 | import IPython |
|
31 | 31 | except Exception,e: |
|
32 | 32 | raise "Error importing IPython (%s)" % str(e) |
|
33 | 33 | |
|
34 | 34 | ############################################################################## |
|
35 | 35 | class _Helper(object): |
|
36 | 36 | """Redefine the built-in 'help'. |
|
37 | 37 | This is a wrapper around pydoc.help (with a twist). |
|
38 | 38 | """ |
|
39 | 39 | |
|
40 | 40 | def __init__(self,pager): |
|
41 | 41 | self._pager = pager |
|
42 | 42 | |
|
43 | 43 | def __repr__(self): |
|
44 | 44 | return "Type help() for interactive help, " \ |
|
45 | 45 | "or help(object) for help about object." |
|
46 | 46 | |
|
47 | 47 | def __call__(self, *args, **kwds): |
|
48 | 48 | class DummyWriter(object): |
|
49 | 49 | def __init__(self,pager): |
|
50 | 50 | self._pager = pager |
|
51 | 51 | |
|
52 | 52 | def write(self,data): |
|
53 | 53 | self._pager(data) |
|
54 | 54 | |
|
55 | 55 | import pydoc |
|
56 | 56 | pydoc.help.output = DummyWriter(self._pager) |
|
57 | 57 | pydoc.help.interact = lambda :1 |
|
58 | 58 | |
|
59 | 59 | return pydoc.help(*args, **kwds) |
|
60 | 60 | |
|
61 | 61 | |
|
62 | 62 | ############################################################################## |
|
63 | 63 | class _CodeExecutor(ThreadEx): |
|
64 | 64 | |
|
65 | 65 | def __init__(self, instance, after): |
|
66 | 66 | ThreadEx.__init__(self) |
|
67 | 67 | self.instance = instance |
|
68 | 68 | self._afterExecute=after |
|
69 | 69 | |
|
70 | 70 | def run(self): |
|
71 | 71 | try: |
|
72 | 72 | self.instance._doc_text = None |
|
73 | 73 | self.instance._help_text = None |
|
74 | 74 | self.instance._execute() |
|
75 | 75 | # used for uper class to generate event after execution |
|
76 | 76 | self._afterExecute() |
|
77 | 77 | |
|
78 | 78 | except KeyboardInterrupt: |
|
79 | 79 | pass |
|
80 | 80 | |
|
81 | 81 | |
|
82 | 82 | ############################################################################## |
|
83 | 83 | class NonBlockingIPShell(object): |
|
84 | 84 | ''' |
|
85 | 85 | Create an IPython instance, running the commands in a separate, |
|
86 | 86 | non-blocking thread. |
|
87 | 87 | This allows embedding in any GUI without blockage. |
|
88 | 88 | |
|
89 | 89 | Note: The ThreadEx class supports asynchroneous function call |
|
90 | 90 | via raise_exc() |
|
91 | 91 | ''' |
|
92 | 92 | |
|
93 | 93 | def __init__(self,argv=[],user_ns={},user_global_ns=None, |
|
94 | 94 | cin=None, cout=None, cerr=None, |
|
95 | 95 | ask_exit_handler=None): |
|
96 | 96 | ''' |
|
97 | 97 | @param argv: Command line options for IPython |
|
98 | 98 | @type argv: list |
|
99 | 99 | @param user_ns: User namespace. |
|
100 | 100 | @type user_ns: dictionary |
|
101 | 101 | @param user_global_ns: User global namespace. |
|
102 | 102 | @type user_global_ns: dictionary. |
|
103 | 103 | @param cin: Console standard input. |
|
104 | 104 | @type cin: IO stream |
|
105 | 105 | @param cout: Console standard output. |
|
106 | 106 | @type cout: IO stream |
|
107 | 107 | @param cerr: Console standard error. |
|
108 | 108 | @type cerr: IO stream |
|
109 | 109 | @param exit_handler: Replacement for builtin exit() function |
|
110 | 110 | @type exit_handler: function |
|
111 | 111 | @param time_loop: Define the sleep time between two thread's loop |
|
112 | 112 | @type int |
|
113 | 113 | ''' |
|
114 | 114 | #ipython0 initialisation |
|
115 | 115 | self.initIpython0(argv, user_ns, user_global_ns, |
|
116 | 116 | cin, cout, cerr, |
|
117 | 117 | ask_exit_handler) |
|
118 | 118 | |
|
119 | 119 | #vars used by _execute |
|
120 | 120 | self._iter_more = 0 |
|
121 | 121 | self._history_level = 0 |
|
122 | self._complete_sep = re.compile('[\s\{\}\[\]\(\)]') | |
|
122 | self._complete_sep = re.compile('[\s\{\}\[\]\(\)\=]') | |
|
123 | 123 | self._prompt = str(self._IP.outputcache.prompt1).strip() |
|
124 | 124 | |
|
125 | 125 | #thread working vars |
|
126 | 126 | self._line_to_execute = '' |
|
127 | 127 | |
|
128 | 128 | #vars that will be checked by GUI loop to handle thread states... |
|
129 | 129 | #will be replaced later by PostEvent GUI funtions... |
|
130 | 130 | self._doc_text = None |
|
131 | 131 | self._help_text = None |
|
132 | 132 | self._add_button = None |
|
133 | 133 | |
|
134 | 134 | def initIpython0(self, argv=[], user_ns={}, user_global_ns=None, |
|
135 | 135 | cin=None, cout=None, cerr=None, |
|
136 | 136 | ask_exit_handler=None): |
|
137 | 137 | #first we redefine in/out/error functions of IPython |
|
138 | 138 | if cin: |
|
139 | 139 | IPython.Shell.Term.cin = cin |
|
140 | 140 | if cout: |
|
141 | 141 | IPython.Shell.Term.cout = cout |
|
142 | 142 | if cerr: |
|
143 | 143 | IPython.Shell.Term.cerr = cerr |
|
144 | 144 | |
|
145 | 145 | # This is to get rid of the blockage that accurs during |
|
146 | 146 | # IPython.Shell.InteractiveShell.user_setup() |
|
147 | 147 | IPython.iplib.raw_input = lambda x: None |
|
148 | 148 | |
|
149 | 149 | self._term = IPython.genutils.IOTerm(cin=cin, cout=cout, cerr=cerr) |
|
150 | 150 | |
|
151 | 151 | excepthook = sys.excepthook |
|
152 | 152 | |
|
153 | 153 | self._IP = IPython.Shell.make_IPython( |
|
154 | 154 | argv,user_ns=user_ns, |
|
155 | 155 | user_global_ns=user_global_ns, |
|
156 | 156 | embedded=True, |
|
157 | 157 | shell_class=IPython.Shell.InteractiveShell) |
|
158 | 158 | |
|
159 | 159 | #we replace IPython default encoding by wx locale encoding |
|
160 | 160 | loc = locale.getpreferredencoding() |
|
161 | 161 | if loc: |
|
162 | 162 | self._IP.stdin_encoding = loc |
|
163 | 163 | #we replace the ipython default pager by our pager |
|
164 | 164 | self._IP.set_hook('show_in_pager',self._pager) |
|
165 | 165 | |
|
166 | 166 | #we replace the ipython default shell command caller by our shell handler |
|
167 | 167 | self._IP.set_hook('shell_hook',self._shell) |
|
168 | 168 | |
|
169 | 169 | #we replace the ipython default input command caller by our method |
|
170 | 170 | IPython.iplib.raw_input_original = self._raw_input |
|
171 | 171 | #we replace the ipython default exit command by our method |
|
172 | 172 | self._IP.exit = ask_exit_handler |
|
173 | 173 | #we replace the help command |
|
174 | 174 | self._IP.user_ns['help'] = _Helper(self._pager_help) |
|
175 | 175 | |
|
176 | 176 | #we disable cpase magic... until we found a way to use it properly. |
|
177 | 177 | #import IPython.ipapi |
|
178 | 178 | ip = IPython.ipapi.get() |
|
179 | 179 | def bypassMagic(self, arg): |
|
180 | 180 | print '%this magic is currently disabled.' |
|
181 | 181 | ip.expose_magic('cpaste', bypassMagic) |
|
182 | 182 | |
|
183 | 183 | sys.excepthook = excepthook |
|
184 | 184 | |
|
185 | 185 | #----------------------- Thread management section ---------------------- |
|
186 | 186 | def doExecute(self,line): |
|
187 | 187 | """ |
|
188 | 188 | Tell the thread to process the 'line' command |
|
189 | 189 | """ |
|
190 | 190 | |
|
191 | 191 | self._line_to_execute = line |
|
192 | 192 | #we launch the ipython line execution in a thread to make it interruptible |
|
193 | 193 | self.ce = _CodeExecutor(self,self._afterExecute) |
|
194 | 194 | self.ce.start() |
|
195 | 195 | |
|
196 | 196 | #----------------------- IPython management section ---------------------- |
|
197 | 197 | def getDocText(self): |
|
198 | 198 | """ |
|
199 | 199 | Returns the output of the processing that need to be paged (if any) |
|
200 | 200 | |
|
201 | 201 | @return: The std output string. |
|
202 | 202 | @rtype: string |
|
203 | 203 | """ |
|
204 | 204 | return self._doc_text |
|
205 | 205 | |
|
206 | 206 | def getHelpText(self): |
|
207 | 207 | """ |
|
208 | 208 | Returns the output of the processing that need to be paged via help pager(if any) |
|
209 | 209 | |
|
210 | 210 | @return: The std output string. |
|
211 | 211 | @rtype: string |
|
212 | 212 | """ |
|
213 | 213 | return self._help_text |
|
214 | 214 | |
|
215 | 215 | def getBanner(self): |
|
216 | 216 | """ |
|
217 | 217 | Returns the IPython banner for useful info on IPython instance |
|
218 | 218 | |
|
219 | 219 | @return: The banner string. |
|
220 | 220 | @rtype: string |
|
221 | 221 | """ |
|
222 | 222 | return self._IP.BANNER |
|
223 | 223 | |
|
224 | 224 | def getPromptCount(self): |
|
225 | 225 | """ |
|
226 | 226 | Returns the prompt number. |
|
227 | 227 | Each time a user execute a line in the IPython shell the prompt count is increased |
|
228 | 228 | |
|
229 | 229 | @return: The prompt number |
|
230 | 230 | @rtype: int |
|
231 | 231 | """ |
|
232 | 232 | return self._IP.outputcache.prompt_count |
|
233 | 233 | |
|
234 | 234 | def getPrompt(self): |
|
235 | 235 | """ |
|
236 | 236 | Returns current prompt inside IPython instance |
|
237 | 237 | (Can be In [...]: ot ...:) |
|
238 | 238 | |
|
239 | 239 | @return: The current prompt. |
|
240 | 240 | @rtype: string |
|
241 | 241 | """ |
|
242 | 242 | return self._prompt |
|
243 | 243 | |
|
244 | 244 | def getIndentation(self): |
|
245 | 245 | """ |
|
246 | 246 | Returns the current indentation level |
|
247 | 247 | Usefull to put the caret at the good start position if we want to do autoindentation. |
|
248 | 248 | |
|
249 | 249 | @return: The indentation level. |
|
250 | 250 | @rtype: int |
|
251 | 251 | """ |
|
252 | 252 | return self._IP.indent_current_nsp |
|
253 | 253 | |
|
254 | 254 | def updateNamespace(self, ns_dict): |
|
255 | 255 | ''' |
|
256 | 256 | Add the current dictionary to the shell namespace. |
|
257 | 257 | |
|
258 | 258 | @param ns_dict: A dictionary of symbol-values. |
|
259 | 259 | @type ns_dict: dictionary |
|
260 | 260 | ''' |
|
261 | 261 | self._IP.user_ns.update(ns_dict) |
|
262 | 262 | |
|
263 | 263 | def complete(self, line): |
|
264 | 264 | ''' |
|
265 | 265 | Returns an auto completed line and/or posibilities for completion. |
|
266 | 266 | |
|
267 | 267 | @param line: Given line so far. |
|
268 | 268 | @type line: string |
|
269 | 269 | |
|
270 | 270 | @return: Line completed as for as possible, |
|
271 | 271 | and possible further completions. |
|
272 | 272 | @rtype: tuple |
|
273 | 273 | ''' |
|
274 | 274 | split_line = self._complete_sep.split(line) |
|
275 | 275 | possibilities = self._IP.complete(split_line[-1]) |
|
276 | 276 | if possibilities: |
|
277 | 277 | |
|
278 | 278 | def _commonPrefix(str1, str2): |
|
279 | 279 | ''' |
|
280 | 280 | Reduction function. returns common prefix of two given strings. |
|
281 | 281 | |
|
282 | 282 | @param str1: First string. |
|
283 | 283 | @type str1: string |
|
284 | 284 | @param str2: Second string |
|
285 | 285 | @type str2: string |
|
286 | 286 | |
|
287 | 287 | @return: Common prefix to both strings. |
|
288 | 288 | @rtype: string |
|
289 | 289 | ''' |
|
290 | 290 | for i in range(len(str1)): |
|
291 | 291 | if not str2.startswith(str1[:i+1]): |
|
292 | 292 | return str1[:i] |
|
293 | 293 | return str1 |
|
294 | 294 | common_prefix = reduce(_commonPrefix, possibilities) |
|
295 | 295 | completed = line[:-len(split_line[-1])]+common_prefix |
|
296 | 296 | else: |
|
297 | 297 | completed = line |
|
298 | 298 | return completed, possibilities |
|
299 | 299 | |
|
300 | 300 | def historyBack(self): |
|
301 | 301 | ''' |
|
302 | 302 | Provides one history command back. |
|
303 | 303 | |
|
304 | 304 | @return: The command string. |
|
305 | 305 | @rtype: string |
|
306 | 306 | ''' |
|
307 | 307 | history = '' |
|
308 | 308 | #the below while loop is used to suppress empty history lines |
|
309 | 309 | while((history == '' or history == '\n') and self._history_level >0): |
|
310 | 310 | if self._history_level>=1: |
|
311 | 311 | self._history_level -= 1 |
|
312 | 312 | history = self._getHistory() |
|
313 | 313 | return history |
|
314 | 314 | |
|
315 | 315 | def historyForward(self): |
|
316 | 316 | ''' |
|
317 | 317 | Provides one history command forward. |
|
318 | 318 | |
|
319 | 319 | @return: The command string. |
|
320 | 320 | @rtype: string |
|
321 | 321 | ''' |
|
322 | 322 | history = '' |
|
323 | 323 | #the below while loop is used to suppress empty history lines |
|
324 | 324 | while((history == '' or history == '\n') and self._history_level <= self._getHistoryMaxIndex()): |
|
325 | 325 | if self._history_level < self._getHistoryMaxIndex(): |
|
326 | 326 | self._history_level += 1 |
|
327 | 327 | history = self._getHistory() |
|
328 | 328 | else: |
|
329 | 329 | if self._history_level == self._getHistoryMaxIndex(): |
|
330 | 330 | history = self._getHistory() |
|
331 | 331 | self._history_level += 1 |
|
332 | 332 | else: |
|
333 | 333 | history = '' |
|
334 | 334 | return history |
|
335 | 335 | |
|
336 | 336 | def initHistoryIndex(self): |
|
337 | 337 | ''' |
|
338 | 338 | set history to last command entered |
|
339 | 339 | ''' |
|
340 | 340 | self._history_level = self._getHistoryMaxIndex()+1 |
|
341 | 341 | |
|
342 | 342 | #----------------------- IPython PRIVATE management section -------------- |
|
343 | 343 | def _afterExecute(self): |
|
344 | 344 | ''' |
|
345 | 345 | Can be redefined to generate post event after excution is done |
|
346 | 346 | ''' |
|
347 | 347 | pass |
|
348 | 348 | |
|
349 | 349 | #def _askExit(self): |
|
350 | 350 | # ''' |
|
351 | 351 | # Can be redefined to generate post event to exit the Ipython shell |
|
352 | 352 | # ''' |
|
353 | 353 | # pass |
|
354 | 354 | |
|
355 | 355 | def _getHistoryMaxIndex(self): |
|
356 | 356 | ''' |
|
357 | 357 | returns the max length of the history buffer |
|
358 | 358 | |
|
359 | 359 | @return: history length |
|
360 | 360 | @rtype: int |
|
361 | 361 | ''' |
|
362 | 362 | return len(self._IP.input_hist_raw)-1 |
|
363 | 363 | |
|
364 | 364 | def _getHistory(self): |
|
365 | 365 | ''' |
|
366 | 366 | Get's the command string of the current history level. |
|
367 | 367 | |
|
368 | 368 | @return: Historic command stri |
|
369 | 369 | @rtype: string |
|
370 | 370 | ''' |
|
371 | 371 | rv = self._IP.input_hist_raw[self._history_level].strip('\n') |
|
372 | 372 | return rv |
|
373 | 373 | |
|
374 | 374 | def _pager_help(self,text): |
|
375 | 375 | ''' |
|
376 | 376 | This function is used as a callback replacment to IPython help pager function |
|
377 | 377 | |
|
378 | 378 | It puts the 'text' value inside the self._help_text string that can be retrived via getHelpText |
|
379 | 379 | function. |
|
380 | 380 | ''' |
|
381 | 381 | if self._help_text == None: |
|
382 | 382 | self._help_text = text |
|
383 | 383 | else: |
|
384 | 384 | self._help_text += text |
|
385 | 385 | |
|
386 | 386 | def _pager(self,IP,text): |
|
387 | 387 | ''' |
|
388 | 388 | This function is used as a callback replacment to IPython pager function |
|
389 | 389 | |
|
390 | 390 | It puts the 'text' value inside the self._doc_text string that can be retrived via getDocText |
|
391 | 391 | function. |
|
392 | 392 | ''' |
|
393 | 393 | self._doc_text = text |
|
394 | 394 | |
|
395 | 395 | def _raw_input(self, prompt=''): |
|
396 | 396 | ''' |
|
397 | 397 | Custom raw_input() replacement. Get's current line from console buffer. |
|
398 | 398 | |
|
399 | 399 | @param prompt: Prompt to print. Here for compatability as replacement. |
|
400 | 400 | @type prompt: string |
|
401 | 401 | |
|
402 | 402 | @return: The current command line text. |
|
403 | 403 | @rtype: string |
|
404 | 404 | ''' |
|
405 | 405 | return self._line_to_execute |
|
406 | 406 | |
|
407 | 407 | def _execute(self): |
|
408 | 408 | ''' |
|
409 | 409 | Executes the current line provided by the shell object. |
|
410 | 410 | ''' |
|
411 | 411 | orig_stdout = sys.stdout |
|
412 | 412 | sys.stdout = IPython.Shell.Term.cout |
|
413 | 413 | |
|
414 | 414 | try: |
|
415 | 415 | line = self._IP.raw_input(None, self._iter_more) |
|
416 | 416 | if self._IP.autoindent: |
|
417 | 417 | self._IP.readline_startup_hook(None) |
|
418 | 418 | |
|
419 | 419 | except KeyboardInterrupt: |
|
420 | 420 | self._IP.write('\nKeyboardInterrupt\n') |
|
421 | 421 | self._IP.resetbuffer() |
|
422 | 422 | # keep cache in sync with the prompt counter: |
|
423 | 423 | self._IP.outputcache.prompt_count -= 1 |
|
424 | 424 | |
|
425 | 425 | if self._IP.autoindent: |
|
426 | 426 | self._IP.indent_current_nsp = 0 |
|
427 | 427 | self._iter_more = 0 |
|
428 | 428 | except: |
|
429 | 429 | self._IP.showtraceback() |
|
430 | 430 | else: |
|
431 | 431 | self._iter_more = self._IP.push(line) |
|
432 | 432 | if (self._IP.SyntaxTB.last_syntax_error and |
|
433 | 433 | self._IP.rc.autoedit_syntax): |
|
434 | 434 | self._IP.edit_syntax_error() |
|
435 | 435 | if self._iter_more: |
|
436 | 436 | self._prompt = str(self._IP.outputcache.prompt2).strip() |
|
437 | 437 | if self._IP.autoindent: |
|
438 | 438 | self._IP.readline_startup_hook(self._IP.pre_readline) |
|
439 | 439 | else: |
|
440 | 440 | self._prompt = str(self._IP.outputcache.prompt1).strip() |
|
441 | 441 | self._IP.indent_current_nsp = 0 #we set indentation to 0 |
|
442 | 442 | sys.stdout = orig_stdout |
|
443 | 443 | |
|
444 | 444 | def _shell(self, ip, cmd): |
|
445 | 445 | ''' |
|
446 | 446 | Replacement method to allow shell commands without them blocking. |
|
447 | 447 | |
|
448 | 448 | @param ip: Ipython instance, same as self._IP |
|
449 | 449 | @type cmd: Ipython instance |
|
450 | 450 | @param cmd: Shell command to execute. |
|
451 | 451 | @type cmd: string |
|
452 | 452 | ''' |
|
453 | 453 | stdin, stdout = os.popen4(cmd) |
|
454 | 454 | result = stdout.read().decode('cp437').encode(locale.getpreferredencoding()) |
|
455 | 455 | #we use print command because the shell command is called inside IPython instance and thus is |
|
456 | 456 | #redirected to thread cout |
|
457 | 457 | #"\x01\x1b[1;36m\x02" <-- add colour to the text... |
|
458 | 458 | print "\x01\x1b[1;36m\x02"+result |
|
459 | 459 | stdout.close() |
|
460 | 460 | stdin.close() |
@@ -1,411 +1,475 b'' | |||
|
1 | 1 | #!/usr/bin/python |
|
2 | 2 | # -*- coding: iso-8859-15 -*- |
|
3 | 3 | import wx |
|
4 | 4 | import wx.stc as stc |
|
5 | 5 | import keyword |
|
6 | 6 | |
|
7 | 7 | #----------------------------------------- |
|
8 | 8 | # History widget for IPython |
|
9 | 9 | __version__ = 0.5 |
|
10 | 10 | __author__ = "Laurent Dufrechou" |
|
11 | 11 | __email__ = "laurent.dufrechou _at_ gmail.com" |
|
12 | 12 | __license__ = "BSD" |
|
13 | 13 | #----------------------------------------- |
|
14 | 14 | class IPythonHistoryPanel(wx.Panel): |
|
15 | 15 | |
|
16 | 16 | def __init__(self, parent,flt_empty=True, |
|
17 | 17 | flt_doc=True,flt_cmd=True,flt_magic=True): |
|
18 | 18 | |
|
19 | 19 | wx.Panel.__init__(self,parent,-1) |
|
20 | 20 | #text_ctrl = wx.TextCtrl(self, -1, style=wx.TE_MULTILINE) |
|
21 | 21 | text_ctrl = PythonSTC(self, -1) |
|
22 | 22 | |
|
23 | 23 | |
|
24 | 24 | st_filt = wx.StaticText(self, -1, " Filter:") |
|
25 | 25 | |
|
26 | 26 | self.filter_empty = wx.CheckBox(self, -1, "Empty commands") |
|
27 | 27 | self.filter_doc = wx.CheckBox(self, -1, "?: Doc commands") |
|
28 | 28 | self.filter_cmd = wx.CheckBox(self, -1, "!: Sys commands") |
|
29 | 29 | self.filter_magic = wx.CheckBox(self, -1, "%: Magic keys") |
|
30 | 30 | |
|
31 |
self.filter_empty |
|
|
32 | self.filter_doc.SetValue(flt_doc) | |
|
33 | self.filter_cmd.SetValue(flt_cmd) | |
|
34 | self.filter_magic.SetValue(flt_magic) | |
|
31 | self.options={'filter_empty':{'value':'True', | |
|
32 | 'checkbox':self.filter_empty,'True':True,'False':False, | |
|
33 | 'setfunc':lambda x:None}, | |
|
34 | 'filter_doc':{'value':'True', | |
|
35 | 'checkbox':self.filter_doc,'True':True,'False':False, | |
|
36 | 'setfunc':lambda x:None}, | |
|
37 | 'filter_cmd':{'value':'True', | |
|
38 | 'checkbox':self.filter_cmd,'True':True,'False':False, | |
|
39 | 'setfunc':lambda x:None}, | |
|
40 | 'filter_magic':{'value':'True', | |
|
41 | 'checkbox':self.filter_magic,'True':True,'False':False, | |
|
42 | 'setfunc':lambda x:None}, | |
|
43 | } | |
|
44 | self.reloadOptions(self.options) | |
|
45 | ||
|
46 | self.filter_empty.Bind(wx.EVT_CHECKBOX, self.evtCheckEmptyFilter) | |
|
47 | self.filter_doc.Bind(wx.EVT_CHECKBOX, self.evtCheckDocFilter) | |
|
48 | self.filter_cmd.Bind(wx.EVT_CHECKBOX, self.evtCheckCmdFilter) | |
|
49 | self.filter_magic.Bind(wx.EVT_CHECKBOX, self.evtCheckMagicFilter) | |
|
50 | ||
|
51 | #self.filter_empty.SetValue(flt_empty) | |
|
52 | #self.filter_doc.SetValue(flt_doc) | |
|
53 | #self.filter_cmd.SetValue(flt_cmd) | |
|
54 | #self.filter_magic.SetValue(flt_magic) | |
|
35 | 55 | |
|
36 | 56 | sizer = wx.BoxSizer(wx.VERTICAL) |
|
37 | 57 | |
|
38 | 58 | sizer.Add(text_ctrl, 1, wx.EXPAND) |
|
39 | 59 | sizer.AddMany( [(5,5), |
|
40 | 60 | st_filt, |
|
41 | 61 | (10,10), |
|
42 | 62 | self.filter_empty, |
|
43 | 63 | self.filter_doc, |
|
44 | 64 | self.filter_cmd, |
|
45 | 65 | self.filter_magic, |
|
46 | 66 | (10,10), |
|
47 | 67 | ]) |
|
48 | 68 | self.SetAutoLayout(True) |
|
49 | 69 | sizer.Fit(self) |
|
50 | 70 | sizer.SetSizeHints(self) |
|
51 | 71 | self.SetSizer(sizer) |
|
52 | 72 | self.text_ctrl=text_ctrl |
|
53 | 73 | #text_ctrl.SetText(demoText + open('Main.py').read()) |
|
54 | 74 | text_ctrl.EmptyUndoBuffer() |
|
55 | 75 | text_ctrl.Colourise(0, -1) |
|
56 | 76 | |
|
57 | 77 | # line numbers in the margin |
|
58 | 78 | text_ctrl.SetMarginType(1, stc.STC_MARGIN_NUMBER) |
|
59 | 79 | text_ctrl.SetMarginWidth(1, 15) |
|
60 | 80 | |
|
61 | 81 | |
|
62 | 82 | def write(self,history_line): |
|
63 | 83 | add = True |
|
64 | 84 | if self.filter_empty.GetValue() == True and history_line == '': |
|
65 | 85 | add = False |
|
66 | 86 | if len(history_line)>0: |
|
67 | 87 | if self.filter_doc.GetValue() == True and history_line[-1:] == '?': |
|
68 | 88 | add = False |
|
69 | 89 | if self.filter_cmd.GetValue() == True and history_line[0] == '!': |
|
70 | 90 | add = False |
|
71 | 91 | if self.filter_magic.GetValue() == True and history_line[0] == '%': |
|
72 | 92 | add = False |
|
73 | 93 | if add: |
|
74 | 94 | self.text_ctrl.AppendText(history_line+'\n') |
|
75 | 95 | |
|
96 | #------------------------ Option Section ----------------------------------- | |
|
97 | def processOptionCheckedEvt(self, event, name): | |
|
98 | if event.IsChecked(): | |
|
99 | self.options[name]['value']='True' | |
|
100 | else: | |
|
101 | self.options[name]['value']='False' | |
|
102 | self.updateOptionTracker(name, | |
|
103 | self.options[name]['value']) | |
|
104 | ||
|
105 | def evtCheckEmptyFilter(self, event): | |
|
106 | self.processOptionCheckedEvt(event, 'filter_empty') | |
|
107 | ||
|
108 | def evtCheckDocFilter(self, event): | |
|
109 | self.processOptionCheckedEvt(event, 'filter_doc') | |
|
110 | ||
|
111 | def evtCheckCmdFilter(self, event): | |
|
112 | self.processOptionCheckedEvt(event, 'filter_cmd') | |
|
76 | 113 | |
|
114 | def evtCheckMagicFilter(self, event): | |
|
115 | self.processOptionCheckedEvt(event, 'filter_magic') | |
|
116 | ||
|
117 | def getOptions(self): | |
|
118 | return self.options | |
|
119 | ||
|
120 | def reloadOptions(self,options): | |
|
121 | self.options = options | |
|
122 | for key in self.options.keys(): | |
|
123 | value = self.options[key]['value'] | |
|
124 | self.options[key]['checkbox'].SetValue(self.options[key][value]) | |
|
125 | self.options[key]['setfunc'](value) | |
|
126 | ||
|
127 | #------------------------ Hook Section ----------------------------------- | |
|
128 | def updateOptionTracker(self,name,value): | |
|
129 | ''' | |
|
130 | Default history tracker (does nothing) | |
|
131 | ''' | |
|
132 | pass | |
|
133 | ||
|
134 | def setOptionTrackerHook(self,func): | |
|
135 | ''' | |
|
136 | Define a new history tracker | |
|
137 | ''' | |
|
138 | self.updateOptionTracker = func | |
|
139 | ||
|
140 | ||
|
77 | 141 | #---------------------------------------------------------------------- |
|
78 | 142 | # Font definition for Styled Text Control |
|
79 | 143 | |
|
80 | 144 | if wx.Platform == '__WXMSW__': |
|
81 | 145 | faces = { 'times': 'Times New Roman', |
|
82 | 146 | 'mono' : 'Courier New', |
|
83 | 147 | 'helv' : 'Arial', |
|
84 | 148 | 'other': 'Comic Sans MS', |
|
85 | 149 | 'size' : 8, |
|
86 | 150 | 'size2': 6, |
|
87 | 151 | } |
|
88 | 152 | elif wx.Platform == '__WXMAC__': |
|
89 | 153 | faces = { 'times': 'Times New Roman', |
|
90 | 154 | 'mono' : 'Monaco', |
|
91 | 155 | 'helv' : 'Arial', |
|
92 | 156 | 'other': 'Comic Sans MS', |
|
93 | 157 | 'size' : 8, |
|
94 | 158 | 'size2': 6, |
|
95 | 159 | } |
|
96 | 160 | else: |
|
97 | 161 | faces = { 'times': 'Times', |
|
98 | 162 | 'mono' : 'Courier', |
|
99 | 163 | 'helv' : 'Helvetica', |
|
100 | 164 | 'other': 'new century schoolbook', |
|
101 | 165 | 'size' : 8, |
|
102 | 166 | 'size2': 6, |
|
103 | 167 | } |
|
104 | 168 | |
|
105 | 169 | |
|
106 | 170 | #---------------------------------------------------------------------- |
|
107 | 171 | |
|
108 | 172 | class PythonSTC(stc.StyledTextCtrl): |
|
109 | 173 | |
|
110 | 174 | fold_symbols = 3 |
|
111 | 175 | |
|
112 | 176 | def __init__(self, parent, ID, |
|
113 | 177 | pos=wx.DefaultPosition, size=wx.DefaultSize, |
|
114 | 178 | style=0): |
|
115 | 179 | stc.StyledTextCtrl.__init__(self, parent, ID, pos, size, style) |
|
116 | 180 | #self.CmdKeyAssign(ord('B'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMIN) |
|
117 | 181 | #self.CmdKeyAssign(ord('N'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMOUT) |
|
118 | 182 | |
|
119 | 183 | self.SetLexer(stc.STC_LEX_PYTHON) |
|
120 | 184 | self.SetKeyWords(0, " ".join(keyword.kwlist)) |
|
121 | 185 | |
|
122 | 186 | #self.SetProperty("fold", "1") |
|
123 | 187 | #self.SetProperty("tab.timmy.whinge.level", "1") |
|
124 | 188 | #self.SetMargins(0,0) |
|
125 | 189 | |
|
126 | 190 | #self.SetViewWhiteSpace(False) |
|
127 | 191 | #self.SetBufferedDraw(False) |
|
128 | 192 | #self.SetViewEOL(True) |
|
129 | 193 | self.SetEOLMode(stc.STC_EOL_CRLF) |
|
130 | 194 | #self.SetUseAntiAliasing(True) |
|
131 | 195 | |
|
132 | 196 | self.SetEdgeMode(stc.STC_EDGE_LINE) |
|
133 | 197 | self.SetEdgeColumn(80) |
|
134 | 198 | self.SetEdgeColour(wx.LIGHT_GREY) |
|
135 | 199 | self.SetLayoutCache(stc.STC_CACHE_PAGE) |
|
136 | 200 | |
|
137 | 201 | # Setup a margin to hold fold markers |
|
138 | 202 | #self.SetFoldFlags(16) ### WHAT IS THIS VALUE? WHAT ARE THE OTHER FLAGS? DOES IT MATTER? |
|
139 | 203 | self.SetMarginType(2, stc.STC_MARGIN_SYMBOL) |
|
140 | 204 | self.SetMarginMask(2, stc.STC_MASK_FOLDERS) |
|
141 | 205 | self.SetMarginSensitive(2, True) |
|
142 | 206 | self.SetMarginWidth(2, 12) |
|
143 | 207 | |
|
144 | 208 | if self.fold_symbols == 0: |
|
145 | 209 | # Arrow pointing right for contracted folders, arrow pointing down for expanded |
|
146 | 210 | self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, stc.STC_MARK_ARROWDOWN, "black", "black") |
|
147 | 211 | self.MarkerDefine(stc.STC_MARKNUM_FOLDER, stc.STC_MARK_ARROW, "black", "black") |
|
148 | 212 | self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, stc.STC_MARK_EMPTY, "black", "black") |
|
149 | 213 | self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, stc.STC_MARK_EMPTY, "black", "black") |
|
150 | 214 | self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND, stc.STC_MARK_EMPTY, "white", "black") |
|
151 | 215 | self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, stc.STC_MARK_EMPTY, "white", "black") |
|
152 | 216 | self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, stc.STC_MARK_EMPTY, "white", "black") |
|
153 | 217 | |
|
154 | 218 | elif self.fold_symbols == 1: |
|
155 | 219 | # Plus for contracted folders, minus for expanded |
|
156 | 220 | self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, stc.STC_MARK_MINUS, "white", "black") |
|
157 | 221 | self.MarkerDefine(stc.STC_MARKNUM_FOLDER, stc.STC_MARK_PLUS, "white", "black") |
|
158 | 222 | self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, stc.STC_MARK_EMPTY, "white", "black") |
|
159 | 223 | self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, stc.STC_MARK_EMPTY, "white", "black") |
|
160 | 224 | self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND, stc.STC_MARK_EMPTY, "white", "black") |
|
161 | 225 | self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, stc.STC_MARK_EMPTY, "white", "black") |
|
162 | 226 | self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, stc.STC_MARK_EMPTY, "white", "black") |
|
163 | 227 | |
|
164 | 228 | elif self.fold_symbols == 2: |
|
165 | 229 | # Like a flattened tree control using circular headers and curved joins |
|
166 | 230 | self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, stc.STC_MARK_CIRCLEMINUS, "white", "#404040") |
|
167 | 231 | self.MarkerDefine(stc.STC_MARKNUM_FOLDER, stc.STC_MARK_CIRCLEPLUS, "white", "#404040") |
|
168 | 232 | self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, stc.STC_MARK_VLINE, "white", "#404040") |
|
169 | 233 | self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, stc.STC_MARK_LCORNERCURVE, "white", "#404040") |
|
170 | 234 | self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND, stc.STC_MARK_CIRCLEPLUSCONNECTED, "white", "#404040") |
|
171 | 235 | self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, stc.STC_MARK_CIRCLEMINUSCONNECTED, "white", "#404040") |
|
172 | 236 | self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, stc.STC_MARK_TCORNERCURVE, "white", "#404040") |
|
173 | 237 | |
|
174 | 238 | elif self.fold_symbols == 3: |
|
175 | 239 | # Like a flattened tree control using square headers |
|
176 | 240 | self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, stc.STC_MARK_BOXMINUS, "white", "#808080") |
|
177 | 241 | self.MarkerDefine(stc.STC_MARKNUM_FOLDER, stc.STC_MARK_BOXPLUS, "white", "#808080") |
|
178 | 242 | self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, stc.STC_MARK_VLINE, "white", "#808080") |
|
179 | 243 | self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, stc.STC_MARK_LCORNER, "white", "#808080") |
|
180 | 244 | self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND, stc.STC_MARK_BOXPLUSCONNECTED, "white", "#808080") |
|
181 | 245 | self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, stc.STC_MARK_BOXMINUSCONNECTED, "white", "#808080") |
|
182 | 246 | self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, stc.STC_MARK_TCORNER, "white", "#808080") |
|
183 | 247 | |
|
184 | 248 | |
|
185 | 249 | self.Bind(stc.EVT_STC_UPDATEUI, self.OnUpdateUI) |
|
186 | 250 | self.Bind(stc.EVT_STC_MARGINCLICK, self.OnMarginClick) |
|
187 | 251 | self.Bind(wx.EVT_KEY_DOWN, self.OnKeyPressed) |
|
188 | 252 | |
|
189 | 253 | # Make some styles, The lexer defines what each style is used for, we |
|
190 | 254 | # just have to define what each style looks like. This set is adapted from |
|
191 | 255 | # Scintilla sample property files. |
|
192 | 256 | |
|
193 | 257 | # Global default styles for all languages |
|
194 | 258 | self.StyleSetSpec(stc.STC_STYLE_DEFAULT, "face:%(helv)s,size:%(size)d" % faces) |
|
195 | 259 | self.StyleClearAll() # Reset all to be like the default |
|
196 | 260 | |
|
197 | 261 | # Global default styles for all languages |
|
198 | 262 | self.StyleSetSpec(stc.STC_STYLE_DEFAULT, "face:%(helv)s,size:%(size)d" % faces) |
|
199 | 263 | self.StyleSetSpec(stc.STC_STYLE_LINENUMBER, "back:#C0C0C0,face:%(helv)s,size:%(size2)d" % faces) |
|
200 | 264 | self.StyleSetSpec(stc.STC_STYLE_CONTROLCHAR, "face:%(other)s" % faces) |
|
201 | 265 | self.StyleSetSpec(stc.STC_STYLE_BRACELIGHT, "fore:#FFFFFF,back:#0000FF,bold") |
|
202 | 266 | self.StyleSetSpec(stc.STC_STYLE_BRACEBAD, "fore:#000000,back:#FF0000,bold") |
|
203 | 267 | |
|
204 | 268 | # Python styles |
|
205 | 269 | # Default |
|
206 | 270 | self.StyleSetSpec(stc.STC_P_DEFAULT, "fore:#000000,face:%(helv)s,size:%(size)d" % faces) |
|
207 | 271 | # Comments |
|
208 | 272 | self.StyleSetSpec(stc.STC_P_COMMENTLINE, "fore:#007F00,face:%(other)s,size:%(size)d" % faces) |
|
209 | 273 | # Number |
|
210 | 274 | self.StyleSetSpec(stc.STC_P_NUMBER, "fore:#007F7F,size:%(size)d" % faces) |
|
211 | 275 | # String |
|
212 | 276 | self.StyleSetSpec(stc.STC_P_STRING, "fore:#7F007F,face:%(helv)s,size:%(size)d" % faces) |
|
213 | 277 | # Single quoted string |
|
214 | 278 | self.StyleSetSpec(stc.STC_P_CHARACTER, "fore:#7F007F,face:%(helv)s,size:%(size)d" % faces) |
|
215 | 279 | # Keyword |
|
216 | 280 | self.StyleSetSpec(stc.STC_P_WORD, "fore:#00007F,bold,size:%(size)d" % faces) |
|
217 | 281 | # Triple quotes |
|
218 | 282 | self.StyleSetSpec(stc.STC_P_TRIPLE, "fore:#7F0000,size:%(size)d" % faces) |
|
219 | 283 | # Triple double quotes |
|
220 | 284 | self.StyleSetSpec(stc.STC_P_TRIPLEDOUBLE, "fore:#7F0000,size:%(size)d" % faces) |
|
221 | 285 | # Class name definition |
|
222 | 286 | self.StyleSetSpec(stc.STC_P_CLASSNAME, "fore:#0000FF,bold,underline,size:%(size)d" % faces) |
|
223 | 287 | # Function or method name definition |
|
224 | 288 | self.StyleSetSpec(stc.STC_P_DEFNAME, "fore:#007F7F,bold,size:%(size)d" % faces) |
|
225 | 289 | # Operators |
|
226 | 290 | self.StyleSetSpec(stc.STC_P_OPERATOR, "bold,size:%(size)d" % faces) |
|
227 | 291 | # Identifiers |
|
228 | 292 | self.StyleSetSpec(stc.STC_P_IDENTIFIER, "fore:#000000,face:%(helv)s,size:%(size)d" % faces) |
|
229 | 293 | # Comment-blocks |
|
230 | 294 | self.StyleSetSpec(stc.STC_P_COMMENTBLOCK, "fore:#7F7F7F,size:%(size)d" % faces) |
|
231 | 295 | # End of line where string is not closed |
|
232 | 296 | self.StyleSetSpec(stc.STC_P_STRINGEOL, "fore:#000000,face:%(mono)s,back:#E0C0E0,eol,size:%(size)d" % faces) |
|
233 | 297 | |
|
234 | 298 | self.SetCaretForeground("BLUE") |
|
235 | 299 | |
|
236 | 300 | |
|
237 | 301 | # register some images for use in the AutoComplete box. |
|
238 | 302 | #self.RegisterImage(1, images.getSmilesBitmap()) |
|
239 | 303 | #self.RegisterImage(2, |
|
240 | 304 | # wx.ArtProvider.GetBitmap(wx.ART_NEW, size=(16,16))) |
|
241 | 305 | #self.RegisterImage(3, |
|
242 | 306 | # wx.ArtProvider.GetBitmap(wx.ART_COPY, size=(16,16))) |
|
243 | 307 | |
|
244 | 308 | |
|
245 | 309 | def OnKeyPressed(self, event): |
|
246 | 310 | if self.CallTipActive(): |
|
247 | 311 | self.CallTipCancel() |
|
248 | 312 | key = event.GetKeyCode() |
|
249 | 313 | |
|
250 | 314 | if key == 32 and event.ControlDown(): |
|
251 | 315 | pos = self.GetCurrentPos() |
|
252 | 316 | |
|
253 | 317 | # Tips |
|
254 | 318 | if event.ShiftDown(): |
|
255 | 319 | self.CallTipSetBackground("yellow") |
|
256 | 320 | self.CallTipShow(pos, 'lots of of text: blah, blah, blah\n\n' |
|
257 | 321 | 'show some suff, maybe parameters..\n\n' |
|
258 | 322 | 'fubar(param1, param2)') |
|
259 | 323 | # Code completion |
|
260 | 324 | else: |
|
261 | 325 | #lst = [] |
|
262 | 326 | #for x in range(50000): |
|
263 | 327 | # lst.append('%05d' % x) |
|
264 | 328 | #st = " ".join(lst) |
|
265 | 329 | #print len(st) |
|
266 | 330 | #self.AutoCompShow(0, st) |
|
267 | 331 | |
|
268 | 332 | kw = keyword.kwlist[:] |
|
269 | 333 | |
|
270 | 334 | kw.sort() # Python sorts are case sensitive |
|
271 | 335 | self.AutoCompSetIgnoreCase(False) # so this needs to match |
|
272 | 336 | |
|
273 | 337 | # Images are specified with a appended "?type" |
|
274 | 338 | for i in range(len(kw)): |
|
275 | 339 | if kw[i] in keyword.kwlist: |
|
276 | 340 | kw[i] = kw[i]# + "?1" |
|
277 | 341 | |
|
278 | 342 | self.AutoCompShow(0, " ".join(kw)) |
|
279 | 343 | else: |
|
280 | 344 | event.Skip() |
|
281 | 345 | |
|
282 | 346 | |
|
283 | 347 | def OnUpdateUI(self, evt): |
|
284 | 348 | # check for matching braces |
|
285 | 349 | braceAtCaret = -1 |
|
286 | 350 | braceOpposite = -1 |
|
287 | 351 | charBefore = None |
|
288 | 352 | caretPos = self.GetCurrentPos() |
|
289 | 353 | |
|
290 | 354 | if caretPos > 0: |
|
291 | 355 | charBefore = self.GetCharAt(caretPos - 1) |
|
292 | 356 | styleBefore = self.GetStyleAt(caretPos - 1) |
|
293 | 357 | |
|
294 | 358 | # check before |
|
295 | 359 | if charBefore and chr(charBefore) in "[]{}()" and styleBefore == stc.STC_P_OPERATOR: |
|
296 | 360 | braceAtCaret = caretPos - 1 |
|
297 | 361 | |
|
298 | 362 | # check after |
|
299 | 363 | if braceAtCaret < 0: |
|
300 | 364 | charAfter = self.GetCharAt(caretPos) |
|
301 | 365 | styleAfter = self.GetStyleAt(caretPos) |
|
302 | 366 | |
|
303 | 367 | if charAfter and chr(charAfter) in "[]{}()" and styleAfter == stc.STC_P_OPERATOR: |
|
304 | 368 | braceAtCaret = caretPos |
|
305 | 369 | |
|
306 | 370 | if braceAtCaret >= 0: |
|
307 | 371 | braceOpposite = self.BraceMatch(braceAtCaret) |
|
308 | 372 | |
|
309 | 373 | if braceAtCaret != -1 and braceOpposite == -1: |
|
310 | 374 | self.BraceBadLight(braceAtCaret) |
|
311 | 375 | else: |
|
312 | 376 | self.BraceHighlight(braceAtCaret, braceOpposite) |
|
313 | 377 | #pt = self.PointFromPosition(braceOpposite) |
|
314 | 378 | #self.Refresh(True, wxRect(pt.x, pt.y, 5,5)) |
|
315 | 379 | #print pt |
|
316 | 380 | #self.Refresh(False) |
|
317 | 381 | |
|
318 | 382 | |
|
319 | 383 | def OnMarginClick(self, evt): |
|
320 | 384 | # fold and unfold as needed |
|
321 | 385 | if evt.GetMargin() == 2: |
|
322 | 386 | if evt.GetShift() and evt.GetControl(): |
|
323 | 387 | self.FoldAll() |
|
324 | 388 | else: |
|
325 | 389 | lineClicked = self.LineFromPosition(evt.GetPosition()) |
|
326 | 390 | |
|
327 | 391 | if self.GetFoldLevel(lineClicked) & stc.STC_FOLDLEVELHEADERFLAG: |
|
328 | 392 | if evt.GetShift(): |
|
329 | 393 | self.SetFoldExpanded(lineClicked, True) |
|
330 | 394 | self.Expand(lineClicked, True, True, 1) |
|
331 | 395 | elif evt.GetControl(): |
|
332 | 396 | if self.GetFoldExpanded(lineClicked): |
|
333 | 397 | self.SetFoldExpanded(lineClicked, False) |
|
334 | 398 | self.Expand(lineClicked, False, True, 0) |
|
335 | 399 | else: |
|
336 | 400 | self.SetFoldExpanded(lineClicked, True) |
|
337 | 401 | self.Expand(lineClicked, True, True, 100) |
|
338 | 402 | else: |
|
339 | 403 | self.ToggleFold(lineClicked) |
|
340 | 404 | |
|
341 | 405 | |
|
342 | 406 | def FoldAll(self): |
|
343 | 407 | lineCount = self.GetLineCount() |
|
344 | 408 | expanding = True |
|
345 | 409 | |
|
346 | 410 | # find out if we are folding or unfolding |
|
347 | 411 | for lineNum in range(lineCount): |
|
348 | 412 | if self.GetFoldLevel(lineNum) & stc.STC_FOLDLEVELHEADERFLAG: |
|
349 | 413 | expanding = not self.GetFoldExpanded(lineNum) |
|
350 | 414 | break |
|
351 | 415 | |
|
352 | 416 | lineNum = 0 |
|
353 | 417 | |
|
354 | 418 | while lineNum < lineCount: |
|
355 | 419 | level = self.GetFoldLevel(lineNum) |
|
356 | 420 | if level & stc.STC_FOLDLEVELHEADERFLAG and \ |
|
357 | 421 | (level & stc.STC_FOLDLEVELNUMBERMASK) == stc.STC_FOLDLEVELBASE: |
|
358 | 422 | |
|
359 | 423 | if expanding: |
|
360 | 424 | self.SetFoldExpanded(lineNum, True) |
|
361 | 425 | lineNum = self.Expand(lineNum, True) |
|
362 | 426 | lineNum = lineNum - 1 |
|
363 | 427 | else: |
|
364 | 428 | lastChild = self.GetLastChild(lineNum, -1) |
|
365 | 429 | self.SetFoldExpanded(lineNum, False) |
|
366 | 430 | |
|
367 | 431 | if lastChild > lineNum: |
|
368 | 432 | self.HideLines(lineNum+1, lastChild) |
|
369 | 433 | |
|
370 | 434 | lineNum = lineNum + 1 |
|
371 | 435 | |
|
372 | 436 | |
|
373 | 437 | |
|
374 | 438 | def Expand(self, line, doExpand, force=False, visLevels=0, level=-1): |
|
375 | 439 | lastChild = self.GetLastChild(line, level) |
|
376 | 440 | line = line + 1 |
|
377 | 441 | |
|
378 | 442 | while line <= lastChild: |
|
379 | 443 | if force: |
|
380 | 444 | if visLevels > 0: |
|
381 | 445 | self.ShowLines(line, line) |
|
382 | 446 | else: |
|
383 | 447 | self.HideLines(line, line) |
|
384 | 448 | else: |
|
385 | 449 | if doExpand: |
|
386 | 450 | self.ShowLines(line, line) |
|
387 | 451 | |
|
388 | 452 | if level == -1: |
|
389 | 453 | level = self.GetFoldLevel(line) |
|
390 | 454 | |
|
391 | 455 | if level & stc.STC_FOLDLEVELHEADERFLAG: |
|
392 | 456 | if force: |
|
393 | 457 | if visLevels > 1: |
|
394 | 458 | self.SetFoldExpanded(line, True) |
|
395 | 459 | else: |
|
396 | 460 | self.SetFoldExpanded(line, False) |
|
397 | 461 | |
|
398 | 462 | line = self.Expand(line, doExpand, force, visLevels-1) |
|
399 | 463 | |
|
400 | 464 | else: |
|
401 | 465 | if doExpand and self.GetFoldExpanded(line): |
|
402 | 466 | line = self.Expand(line, True, force, visLevels-1) |
|
403 | 467 | else: |
|
404 | 468 | line = self.Expand(line, False, force, visLevels-1) |
|
405 | 469 | else: |
|
406 | 470 | line = line + 1 |
|
407 | 471 | |
|
408 | 472 | return line |
|
409 | 473 | |
|
410 | 474 | |
|
411 | 475 | #---------------------------------------------------------------------- |
@@ -1,752 +1,874 b'' | |||
|
1 | 1 | #!/usr/bin/python |
|
2 | 2 | # -*- coding: iso-8859-15 -*- |
|
3 | 3 | ''' |
|
4 | 4 | Provides IPython WX console widgets. |
|
5 | 5 | |
|
6 | 6 | @author: Laurent Dufrechou |
|
7 | 7 | laurent.dufrechou _at_ gmail.com |
|
8 | 8 | This WX widget is based on the original work of Eitan Isaacson |
|
9 | 9 | that provided the console for the GTK toolkit. |
|
10 | 10 | |
|
11 | 11 | Original work from: |
|
12 | 12 | @author: Eitan Isaacson |
|
13 | 13 | @organization: IBM Corporation |
|
14 | 14 | @copyright: Copyright (c) 2007 IBM Corporation |
|
15 | 15 | @license: BSD |
|
16 | 16 | |
|
17 | 17 | All rights reserved. This program and the accompanying materials are made |
|
18 | 18 | available under the terms of the BSD which accompanies this distribution, and |
|
19 | 19 | is available at U{http://www.opensource.org/licenses/bsd-license.php} |
|
20 | 20 | ''' |
|
21 | 21 | |
|
22 | 22 | __version__ = 0.8 |
|
23 | 23 | __author__ = "Laurent Dufrechou" |
|
24 | 24 | __email__ = "laurent.dufrechou _at_ gmail.com" |
|
25 | 25 | __license__ = "BSD" |
|
26 | 26 | |
|
27 | 27 | import wx |
|
28 | 28 | import wx.stc as stc |
|
29 | import wx.lib.newevent | |
|
30 | 29 | |
|
31 | 30 | import re |
|
32 | 31 | import sys |
|
33 | 32 | import locale |
|
34 | 33 | from StringIO import StringIO |
|
35 | 34 | try: |
|
36 | 35 | import IPython |
|
37 | 36 | except Exception,e: |
|
38 | 37 | raise "Error importing IPython (%s)" % str(e) |
|
39 | 38 | |
|
40 | 39 | from ipshell_nonblocking import NonBlockingIPShell |
|
41 | 40 | |
|
42 | ||
|
43 | 41 | class WxNonBlockingIPShell(NonBlockingIPShell): |
|
44 | 42 | ''' |
|
45 | 43 | An NonBlockingIPShell Thread that is WX dependent. |
|
46 | 44 | ''' |
|
47 | 45 | def __init__(self, parent, |
|
48 | 46 | argv=[],user_ns={},user_global_ns=None, |
|
49 | 47 | cin=None, cout=None, cerr=None, |
|
50 | 48 | ask_exit_handler=None): |
|
51 | 49 | |
|
52 | 50 | NonBlockingIPShell.__init__(self,argv,user_ns,user_global_ns, |
|
53 | 51 | cin, cout, cerr, |
|
54 | 52 | ask_exit_handler) |
|
55 | 53 | |
|
56 | 54 | self.parent = parent |
|
57 | 55 | |
|
58 | 56 | self.ask_exit_callback = ask_exit_handler |
|
59 | 57 | self._IP.exit = self._askExit |
|
60 | 58 | |
|
61 | 59 | def addGUIShortcut(self,text,func): |
|
62 | 60 | wx.CallAfter(self.parent.add_button_handler, |
|
63 | 61 | button_info={ 'text':text, |
|
64 | 62 | 'func':self.parent.doExecuteLine(func)}) |
|
65 | 63 | |
|
66 | 64 | def _askExit(self): |
|
67 | 65 | wx.CallAfter(self.ask_exit_callback, ()) |
|
68 | 66 | |
|
69 | 67 | def _afterExecute(self): |
|
70 | 68 | wx.CallAfter(self.parent.evtStateExecuteDone, ()) |
|
71 | 69 | |
|
72 | 70 | |
|
73 | 71 | class WxConsoleView(stc.StyledTextCtrl): |
|
74 | 72 | ''' |
|
75 | 73 | Specialized styled text control view for console-like workflow. |
|
76 | 74 | We use here a scintilla frontend thus it can be reused in any GUI that |
|
77 | 75 | supports scintilla with less work. |
|
78 | 76 | |
|
79 | 77 | @cvar ANSI_COLORS_BLACK: Mapping of terminal colors to X11 names. |
|
80 | 78 | (with Black background) |
|
81 | 79 | @type ANSI_COLORS_BLACK: dictionary |
|
82 | 80 | |
|
83 | 81 | @cvar ANSI_COLORS_WHITE: Mapping of terminal colors to X11 names. |
|
84 | 82 | (with White background) |
|
85 | 83 | @type ANSI_COLORS_WHITE: dictionary |
|
86 | 84 | |
|
87 | 85 | @ivar color_pat: Regex of terminal color pattern |
|
88 | 86 | @type color_pat: _sre.SRE_Pattern |
|
89 | 87 | ''' |
|
90 | 88 | ANSI_STYLES_BLACK={'0;30': [0,'WHITE'], '0;31': [1,'RED'], |
|
91 | 89 | '0;32': [2,'GREEN'], '0;33': [3,'BROWN'], |
|
92 | 90 | '0;34': [4,'BLUE'], '0;35': [5,'PURPLE'], |
|
93 | 91 | '0;36': [6,'CYAN'], '0;37': [7,'LIGHT GREY'], |
|
94 | 92 | '1;30': [8,'DARK GREY'], '1;31': [9,'RED'], |
|
95 | 93 | '1;32': [10,'SEA GREEN'], '1;33': [11,'YELLOW'], |
|
96 | 94 | '1;34': [12,'LIGHT BLUE'], '1;35': |
|
97 | 95 | [13,'MEDIUM VIOLET RED'], |
|
98 | 96 | '1;36': [14,'LIGHT STEEL BLUE'],'1;37': [15,'YELLOW']} |
|
99 | 97 | |
|
100 | 98 | ANSI_STYLES_WHITE={'0;30': [0,'BLACK'], '0;31': [1,'RED'], |
|
101 | 99 | '0;32': [2,'GREEN'], '0;33': [3,'BROWN'], |
|
102 | 100 | '0;34': [4,'BLUE'], '0;35': [5,'PURPLE'], |
|
103 | 101 | '0;36': [6,'CYAN'], '0;37': [7,'LIGHT GREY'], |
|
104 | 102 | '1;30': [8,'DARK GREY'], '1;31': [9,'RED'], |
|
105 | 103 | '1;32': [10,'SEA GREEN'], '1;33': [11,'YELLOW'], |
|
106 | 104 | '1;34': [12,'LIGHT BLUE'], '1;35': |
|
107 | 105 | [13,'MEDIUM VIOLET RED'], |
|
108 | 106 | '1;36': [14,'LIGHT STEEL BLUE'],'1;37': [15,'YELLOW']} |
|
109 | 107 | |
|
110 | 108 | def __init__(self,parent,prompt,intro="",background_color="BLACK", |
|
111 | 109 | pos=wx.DefaultPosition, ID = -1, size=wx.DefaultSize, |
|
112 | style=0): | |
|
110 | style=0, autocomplete_mode = 'IPYTHON'): | |
|
113 | 111 | ''' |
|
114 | 112 | Initialize console view. |
|
115 | 113 | |
|
116 | 114 | @param parent: Parent widget |
|
117 | 115 | @param prompt: User specified prompt |
|
118 | 116 | @type intro: string |
|
119 | 117 | @param intro: User specified startup introduction string |
|
120 | 118 | @type intro: string |
|
121 | 119 | @param background_color: Can be BLACK or WHITE |
|
122 | 120 | @type background_color: string |
|
123 | 121 | @param other: init param of styledTextControl (can be used as-is) |
|
122 | @param autocomplete_mode: Can be 'IPYTHON' or 'STC' | |
|
123 | 'IPYTHON' show autocompletion the ipython way | |
|
124 | 'STC" show it scintilla text control way | |
|
124 | 125 | ''' |
|
125 | 126 | stc.StyledTextCtrl.__init__(self, parent, ID, pos, size, style) |
|
126 | 127 | |
|
127 | 128 | ####### Scintilla configuration ################################### |
|
128 | 129 | |
|
129 | 130 | # Ctrl + B or Ctrl + N can be used to zoomin/zoomout the text inside |
|
130 | 131 | # the widget |
|
131 | 132 | self.CmdKeyAssign(ord('B'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMIN) |
|
132 | 133 | self.CmdKeyAssign(ord('N'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMOUT) |
|
133 | 134 | |
|
135 | #We draw a line at position 80 | |
|
136 | self.SetEdgeMode(stc.STC_EDGE_LINE) | |
|
137 | self.SetEdgeColumn(80) | |
|
138 | self.SetEdgeColour(wx.LIGHT_GREY) | |
|
139 | ||
|
140 | #self.SetViewWhiteSpace(True) | |
|
141 | #self.SetViewEOL(True) | |
|
142 | self.SetEOLMode(stc.STC_EOL_CRLF) | |
|
143 | #self.SetWrapMode(stc.STC_WRAP_CHAR) | |
|
144 | #self.SetWrapMode(stc.STC_WRAP_WORD) | |
|
145 | self.SetBufferedDraw(True) | |
|
146 | #self.SetUseAntiAliasing(True) | |
|
147 | self.SetLayoutCache(stc.STC_CACHE_PAGE) | |
|
148 | self.SetUndoCollection(False) | |
|
149 | ||
|
150 | self.EnsureCaretVisible() | |
|
151 | ||
|
152 | self.SetMargins(3,3) #text is moved away from border with 3px | |
|
153 | # Suppressing Scintilla margins | |
|
154 | self.SetMarginWidth(0,0) | |
|
155 | self.SetMarginWidth(1,0) | |
|
156 | self.SetMarginWidth(2,0) | |
|
157 | ||
|
158 | self.background_color = background_color | |
|
159 | self.buildStyles() | |
|
160 | ||
|
161 | self.indent = 0 | |
|
162 | self.prompt_count = 0 | |
|
163 | self.color_pat = re.compile('\x01?\x1b\[(.*?)m\x02?') | |
|
164 | ||
|
165 | self.write(intro) | |
|
166 | self.setPrompt(prompt) | |
|
167 | self.showPrompt() | |
|
168 | ||
|
169 | self.autocomplete_mode = autocomplete_mode | |
|
170 | ||
|
171 | self.Bind(wx.EVT_KEY_DOWN, self._onKeypress) | |
|
172 | ||
|
173 | def buildStyles(self): | |
|
134 | 174 | #we define platform specific fonts |
|
135 | 175 | if wx.Platform == '__WXMSW__': |
|
136 | 176 | faces = { 'times': 'Times New Roman', |
|
137 | 177 | 'mono' : 'Courier New', |
|
138 | 178 | 'helv' : 'Arial', |
|
139 | 179 | 'other': 'Comic Sans MS', |
|
140 | 180 | 'size' : 10, |
|
141 | 181 | 'size2': 8, |
|
142 | 182 | } |
|
143 | 183 | elif wx.Platform == '__WXMAC__': |
|
144 | 184 | faces = { 'times': 'Times New Roman', |
|
145 | 185 | 'mono' : 'Monaco', |
|
146 | 186 | 'helv' : 'Arial', |
|
147 | 187 | 'other': 'Comic Sans MS', |
|
148 | 188 | 'size' : 10, |
|
149 | 189 | 'size2': 8, |
|
150 | 190 | } |
|
151 | 191 | else: |
|
152 | 192 | faces = { 'times': 'Times', |
|
153 | 193 | 'mono' : 'Courier', |
|
154 | 194 | 'helv' : 'Helvetica', |
|
155 | 195 | 'other': 'new century schoolbook', |
|
156 | 196 | 'size' : 10, |
|
157 | 197 | 'size2': 8, |
|
158 | 198 | } |
|
159 | 199 | |
|
160 | #We draw a line at position 80 | |
|
161 | self.SetEdgeMode(stc.STC_EDGE_LINE) | |
|
162 | self.SetEdgeColumn(80) | |
|
163 | self.SetEdgeColour(wx.LIGHT_GREY) | |
|
164 | ||
|
165 | #self.SetViewWhiteSpace(True) | |
|
166 | #self.SetViewEOL(True) | |
|
167 | self.SetEOLMode(stc.STC_EOL_CRLF) | |
|
168 | #self.SetWrapMode(stc.STC_WRAP_CHAR) | |
|
169 | #self.SetWrapMode(stc.STC_WRAP_WORD) | |
|
170 | self.SetBufferedDraw(True) | |
|
171 | #self.SetUseAntiAliasing(True) | |
|
172 | self.SetLayoutCache(stc.STC_CACHE_PAGE) | |
|
173 | ||
|
174 | self.EnsureCaretVisible() | |
|
175 | ||
|
176 | self.SetMargins(3,3) #text is moved away from border with 3px | |
|
177 | # Suppressing Scintilla margins | |
|
178 | self.SetMarginWidth(0,0) | |
|
179 | self.SetMarginWidth(1,0) | |
|
180 | self.SetMarginWidth(2,0) | |
|
181 | ||
|
182 | 200 | # make some styles |
|
183 | if background_color != "BLACK": | |
|
201 | if self.background_color != "BLACK": | |
|
184 | 202 | self.background_color = "WHITE" |
|
185 | 203 | self.SetCaretForeground("BLACK") |
|
186 | 204 | self.ANSI_STYLES = self.ANSI_STYLES_WHITE |
|
187 | 205 | else: |
|
188 | self.background_color = background_color | |
|
189 | 206 | self.SetCaretForeground("WHITE") |
|
190 | 207 | self.ANSI_STYLES = self.ANSI_STYLES_BLACK |
|
191 | 208 | |
|
192 | 209 | self.StyleSetSpec(stc.STC_STYLE_DEFAULT, |
|
193 | 210 | "fore:%s,back:%s,size:%d,face:%s" |
|
194 | 211 | % (self.ANSI_STYLES['0;30'][1], |
|
195 | 212 | self.background_color, |
|
196 | 213 | faces['size'], faces['mono'])) |
|
197 | 214 | self.StyleClearAll() |
|
198 | 215 | self.StyleSetSpec(stc.STC_STYLE_BRACELIGHT, |
|
199 | 216 | "fore:#FF0000,back:#0000FF,bold") |
|
200 | 217 | self.StyleSetSpec(stc.STC_STYLE_BRACEBAD, |
|
201 | 218 | "fore:#000000,back:#FF0000,bold") |
|
202 | ||
|
219 | ||
|
203 | 220 | for style in self.ANSI_STYLES.values(): |
|
204 | 221 | self.StyleSetSpec(style[0], "bold,fore:%s" % style[1]) |
|
205 | 222 | |
|
206 | 223 | ####################################################################### |
|
207 | 224 | |
|
208 | self.indent = 0 | |
|
209 |
self. |
|
|
210 | self.color_pat = re.compile('\x01?\x1b\[(.*?)m\x02?') | |
|
211 | ||
|
212 | self.write(intro) | |
|
213 | self.setPrompt(prompt) | |
|
214 | self.showPrompt() | |
|
215 | ||
|
216 | self.Bind(wx.EVT_KEY_DOWN, self._onKeypress, self) | |
|
225 | def setBackgroundColor(self,color): | |
|
226 | self.background_color = color | |
|
227 | self.buildStyles() | |
|
217 | 228 | |
|
229 | def getBackgroundColor(self,color): | |
|
230 | return self.background_color | |
|
231 | ||
|
218 | 232 | def asyncWrite(self, text): |
|
219 | 233 | ''' |
|
220 | 234 | Write given text to buffer in an asynchroneous way. |
|
221 | 235 | It is used from another thread to be able to acces the GUI. |
|
222 | 236 | @param text: Text to append |
|
223 | 237 | @type text: string |
|
224 | 238 | ''' |
|
225 | 239 | try: |
|
226 | 240 | #print >>sys.__stdout__,'entering' |
|
227 | 241 | wx.MutexGuiEnter() |
|
228 | 242 | #print >>sys.__stdout__,'locking the GUI' |
|
229 | 243 | |
|
230 | 244 | #be sure not to be interrutpted before the MutexGuiLeave! |
|
231 | 245 | self.write(text) |
|
246 | ||
|
232 | 247 | #print >>sys.__stdout__,'done' |
|
233 | 248 | |
|
234 | 249 | except KeyboardInterrupt: |
|
235 | 250 | #print >>sys.__stdout__,'got keyboard interrupt' |
|
236 | 251 | wx.MutexGuiLeave() |
|
237 | 252 | #print >>sys.__stdout__,'interrupt unlock the GUI' |
|
238 | 253 | raise KeyboardInterrupt |
|
239 | 254 | wx.MutexGuiLeave() |
|
240 | 255 | #print >>sys.__stdout__,'normal unlock the GUI' |
|
241 | 256 | |
|
242 | 257 | |
|
243 | 258 | def write(self, text): |
|
244 | 259 | ''' |
|
245 | 260 | Write given text to buffer. |
|
246 | 261 | |
|
247 | 262 | @param text: Text to append. |
|
248 | 263 | @type text: string |
|
249 | 264 | ''' |
|
250 | 265 | segments = self.color_pat.split(text) |
|
251 | 266 | segment = segments.pop(0) |
|
252 | 267 | self.StartStyling(self.getCurrentLineEnd(),0xFF) |
|
253 | 268 | self.AppendText(segment) |
|
254 | 269 | |
|
255 | 270 | if segments: |
|
256 | 271 | ansi_tags = self.color_pat.findall(text) |
|
257 | 272 | |
|
258 | 273 | for tag in ansi_tags: |
|
259 | 274 | i = segments.index(tag) |
|
260 | 275 | self.StartStyling(self.getCurrentLineEnd(),0xFF) |
|
261 | 276 | self.AppendText(segments[i+1]) |
|
262 | 277 | |
|
263 | 278 | if tag != '0': |
|
264 | 279 | self.SetStyling(len(segments[i+1]),self.ANSI_STYLES[tag][0]) |
|
265 | 280 | |
|
266 | 281 | segments.pop(i) |
|
267 | 282 | |
|
268 | 283 | self.moveCursor(self.getCurrentLineEnd()) |
|
269 | 284 | |
|
270 | 285 | def getPromptLen(self): |
|
271 | 286 | ''' |
|
272 | 287 | Return the length of current prompt |
|
273 | 288 | ''' |
|
274 | 289 | return len(str(self.prompt_count)) + 7 |
|
275 | 290 | |
|
276 | 291 | def setPrompt(self,prompt): |
|
277 | 292 | self.prompt = prompt |
|
278 | 293 | |
|
279 | 294 | def setIndentation(self,indentation): |
|
280 | 295 | self.indent = indentation |
|
281 | 296 | |
|
282 | 297 | def setPromptCount(self,count): |
|
283 | 298 | self.prompt_count = count |
|
284 | 299 | |
|
285 | 300 | def showPrompt(self): |
|
286 | 301 | ''' |
|
287 | 302 | Prints prompt at start of line. |
|
288 | 303 | |
|
289 | 304 | @param prompt: Prompt to print. |
|
290 | 305 | @type prompt: string |
|
291 | 306 | ''' |
|
292 | 307 | self.write(self.prompt) |
|
293 | 308 | #now we update the position of end of prompt |
|
294 | 309 | self.current_start = self.getCurrentLineEnd() |
|
295 | 310 | |
|
296 | 311 | autoindent = self.indent*' ' |
|
297 | 312 | autoindent = autoindent.replace(' ','\t') |
|
298 | 313 | self.write(autoindent) |
|
299 | 314 | |
|
300 | 315 | def changeLine(self, text): |
|
301 | 316 | ''' |
|
302 | 317 | Replace currently entered command line with given text. |
|
303 | 318 | |
|
304 | 319 | @param text: Text to use as replacement. |
|
305 | 320 | @type text: string |
|
306 | 321 | ''' |
|
307 | 322 | self.SetSelection(self.getCurrentPromptStart(),self.getCurrentLineEnd()) |
|
308 | 323 | self.ReplaceSelection(text) |
|
309 | 324 | self.moveCursor(self.getCurrentLineEnd()) |
|
310 | 325 | |
|
311 | 326 | def getCurrentPromptStart(self): |
|
312 | 327 | return self.current_start |
|
313 | 328 | |
|
314 | 329 | def getCurrentLineStart(self): |
|
315 | 330 | return self.GotoLine(self.LineFromPosition(self.GetCurrentPos())) |
|
316 | 331 | |
|
317 | 332 | def getCurrentLineEnd(self): |
|
318 | 333 | return self.GetLength() |
|
319 | 334 | |
|
320 | 335 | def getCurrentLine(self): |
|
321 | 336 | ''' |
|
322 | 337 | Get text in current command line. |
|
323 | 338 | |
|
324 | 339 | @return: Text of current command line. |
|
325 | 340 | @rtype: string |
|
326 | 341 | ''' |
|
327 | 342 | return self.GetTextRange(self.getCurrentPromptStart(), |
|
328 | 343 | self.getCurrentLineEnd()) |
|
329 | 344 | |
|
330 | 345 | def moveCursorOnNewValidKey(self): |
|
331 | 346 | #If cursor is at wrong position put it at last line... |
|
332 | 347 | if self.GetCurrentPos() < self.getCurrentPromptStart(): |
|
333 | 348 | self.GotoPos(self.getCurrentPromptStart()) |
|
334 | 349 | |
|
335 | 350 | def removeFromTo(self,from_pos,to_pos): |
|
336 | 351 | if from_pos < to_pos: |
|
337 | 352 | self.SetSelection(from_pos,to_pos) |
|
338 | 353 | self.DeleteBack() |
|
339 | 354 | |
|
340 | 355 | def removeCurrentLine(self): |
|
341 | 356 | self.LineDelete() |
|
342 | 357 | |
|
343 | 358 | def moveCursor(self,position): |
|
344 | 359 | self.GotoPos(position) |
|
345 | 360 | |
|
346 | 361 | def getCursorPos(self): |
|
347 | 362 | return self.GetCurrentPos() |
|
348 | 363 | |
|
349 | 364 | def selectFromTo(self,from_pos,to_pos): |
|
350 | 365 | self.SetSelectionStart(from_pos) |
|
351 | 366 | self.SetSelectionEnd(to_pos) |
|
352 | 367 | |
|
353 | 368 | def writeHistory(self,history): |
|
354 | 369 | self.removeFromTo(self.getCurrentPromptStart(),self.getCurrentLineEnd()) |
|
355 | 370 | self.changeLine(history) |
|
371 | ||
|
372 | def setCompletionMethod(self, completion): | |
|
373 | if completion in ['IPYTHON','STC']: | |
|
374 | self.autocomplete_mode = completion | |
|
375 | else: | |
|
376 | raise AttributeError | |
|
377 | ||
|
378 | def getCompletionMethod(self, completion): | |
|
379 | return self.autocomplete_mode | |
|
356 | 380 | |
|
357 | 381 | def writeCompletion(self, possibilities): |
|
358 | max_len = len(max(possibilities,key=len)) | |
|
359 | max_symbol =' '*max_len | |
|
360 | ||
|
361 | #now we check how much symbol we can put on a line... | |
|
362 | cursor_pos = self.getCursorPos() | |
|
363 | test_buffer = max_symbol + ' '*4 | |
|
364 | current_lines = self.GetLineCount() | |
|
365 | ||
|
366 | allowed_symbols = 80/len(test_buffer) | |
|
367 |
|
|
|
368 |
|
|
|
382 | if self.autocomplete_mode == 'IPYTHON': | |
|
383 | max_len = len(max(possibilities,key=len)) | |
|
384 | max_symbol =' '*max_len | |
|
385 | ||
|
386 | #now we check how much symbol we can put on a line... | |
|
387 | cursor_pos = self.getCursorPos() | |
|
388 | test_buffer = max_symbol + ' '*4 | |
|
389 | current_lines = self.GetLineCount() | |
|
390 | ||
|
391 | allowed_symbols = 80/len(test_buffer) | |
|
392 | if allowed_symbols == 0: | |
|
393 | allowed_symbols = 1 | |
|
394 | ||
|
395 | pos = 1 | |
|
396 | buf = '' | |
|
397 | for symbol in possibilities: | |
|
398 | #buf += symbol+'\n'#*spaces) | |
|
399 | if pos<allowed_symbols: | |
|
400 | spaces = max_len - len(symbol) + 4 | |
|
401 | buf += symbol+' '*spaces | |
|
402 | pos += 1 | |
|
403 | else: | |
|
404 | buf+=symbol+'\n' | |
|
405 | pos = 1 | |
|
406 | self.write(buf) | |
|
407 | else: | |
|
408 | possibilities.sort() # Python sorts are case sensitive | |
|
409 | self.AutoCompSetIgnoreCase(False) | |
|
410 | self.AutoCompSetAutoHide(False) | |
|
411 | #let compute the length ot last word | |
|
412 | splitter = [' ','(','[','{'] | |
|
413 | last_word = self.getCurrentLine() | |
|
414 | for breaker in splitter: | |
|
415 | last_word = last_word.split(breaker)[-1] | |
|
416 | self.AutoCompShow(len(last_word), " ".join(possibilities)) | |
|
369 | 417 | |
|
370 | pos = 1 | |
|
371 | buf = '' | |
|
372 | for symbol in possibilities: | |
|
373 | #buf += symbol+'\n'#*spaces) | |
|
374 | if pos<allowed_symbols: | |
|
375 | spaces = max_len - len(symbol) + 4 | |
|
376 | buf += symbol+' '*spaces | |
|
377 | pos += 1 | |
|
378 | else: | |
|
379 | buf+=symbol+'\n' | |
|
380 | pos = 1 | |
|
381 | self.write(buf) | |
|
382 | ||
|
383 | 418 | def _onKeypress(self, event, skip=True): |
|
384 | 419 | ''' |
|
385 | 420 | Key press callback used for correcting behavior for console-like |
|
386 | 421 | interfaces. For example 'home' should go to prompt, not to begining of |
|
387 | 422 | line. |
|
388 | 423 | |
|
389 | 424 | @param widget: Widget that key press accored in. |
|
390 | 425 | @type widget: gtk.Widget |
|
391 | 426 | @param event: Event object |
|
392 | 427 | @type event: gtk.gdk.Event |
|
393 | 428 | |
|
394 | 429 | @return: Return True if event as been catched. |
|
395 | 430 | @rtype: boolean |
|
396 | 431 | ''' |
|
397 | ||
|
398 | if event.GetKeyCode() == wx.WXK_HOME: | |
|
399 | if event.Modifiers == wx.MOD_NONE: | |
|
400 | self.moveCursorOnNewValidKey() | |
|
401 | self.moveCursor(self.getCurrentPromptStart()) | |
|
402 | return True | |
|
403 | elif event.Modifiers == wx.MOD_SHIFT: | |
|
404 | self.moveCursorOnNewValidKey() | |
|
405 | self.selectFromTo(self.getCurrentPromptStart(),self.getCursorPos()) | |
|
406 | return True | |
|
407 | else: | |
|
408 | return False | |
|
409 | 432 | |
|
410 | elif event.GetKeyCode() == wx.WXK_LEFT: | |
|
411 |
if event. |
|
|
412 | self.moveCursorOnNewValidKey() | |
|
413 | ||
|
414 | self.moveCursor(self.getCursorPos()-1) | |
|
415 | if self.getCursorPos() < self.getCurrentPromptStart(): | |
|
433 | if not self.AutoCompActive(): | |
|
434 | if event.GetKeyCode() == wx.WXK_HOME: | |
|
435 | if event.Modifiers == wx.MOD_NONE: | |
|
436 | self.moveCursorOnNewValidKey() | |
|
416 | 437 | self.moveCursor(self.getCurrentPromptStart()) |
|
438 | return True | |
|
439 | elif event.Modifiers == wx.MOD_SHIFT: | |
|
440 | self.moveCursorOnNewValidKey() | |
|
441 | self.selectFromTo(self.getCurrentPromptStart(),self.getCursorPos()) | |
|
442 | return True | |
|
443 | else: | |
|
444 | return False | |
|
445 | ||
|
446 | elif event.GetKeyCode() == wx.WXK_LEFT: | |
|
447 | if event.Modifiers == wx.MOD_NONE: | |
|
448 | self.moveCursorOnNewValidKey() | |
|
449 | ||
|
450 | self.moveCursor(self.getCursorPos()-1) | |
|
451 | if self.getCursorPos() < self.getCurrentPromptStart(): | |
|
452 | self.moveCursor(self.getCurrentPromptStart()) | |
|
453 | return True | |
|
454 | ||
|
455 | elif event.GetKeyCode() == wx.WXK_BACK: | |
|
456 | self.moveCursorOnNewValidKey() | |
|
457 | if self.getCursorPos() > self.getCurrentPromptStart(): | |
|
458 | event.Skip() | |
|
417 | 459 | return True |
|
418 | ||
|
419 | elif event.GetKeyCode() == wx.WXK_BACK: | |
|
420 | self.moveCursorOnNewValidKey() | |
|
421 | if self.getCursorPos() > self.getCurrentPromptStart(): | |
|
460 | ||
|
461 | if skip: | |
|
462 | if event.GetKeyCode() not in [wx.WXK_PAGEUP,wx.WXK_PAGEDOWN] and event.Modifiers == wx.MOD_NONE: | |
|
463 | self.moveCursorOnNewValidKey() | |
|
464 | ||
|
422 | 465 | event.Skip() |
|
423 | return True | |
|
424 | ||
|
425 |
|
|
|
426 | if event.GetKeyCode() not in [wx.WXK_PAGEUP,wx.WXK_PAGEDOWN] and event.Modifiers == wx.MOD_NONE: | |
|
427 | self.moveCursorOnNewValidKey() | |
|
428 | ||
|
466 | return True | |
|
467 | return False | |
|
468 | else: | |
|
429 | 469 | event.Skip() |
|
430 |
|
|
|
431 | return False | |
|
432 | ||
|
470 | ||
|
433 | 471 | def OnUpdateUI(self, evt): |
|
434 | 472 | # check for matching braces |
|
435 | 473 | braceAtCaret = -1 |
|
436 | 474 | braceOpposite = -1 |
|
437 | 475 | charBefore = None |
|
438 | 476 | caretPos = self.GetCurrentPos() |
|
439 | 477 | |
|
440 | 478 | if caretPos > 0: |
|
441 | 479 | charBefore = self.GetCharAt(caretPos - 1) |
|
442 | 480 | styleBefore = self.GetStyleAt(caretPos - 1) |
|
443 | 481 | |
|
444 | 482 | # check before |
|
445 | 483 | if charBefore and chr(charBefore) in "[]{}()" and styleBefore == stc.STC_P_OPERATOR: |
|
446 | 484 | braceAtCaret = caretPos - 1 |
|
447 | 485 | |
|
448 | 486 | # check after |
|
449 | 487 | if braceAtCaret < 0: |
|
450 | 488 | charAfter = self.GetCharAt(caretPos) |
|
451 | 489 | styleAfter = self.GetStyleAt(caretPos) |
|
452 | 490 | |
|
453 | 491 | if charAfter and chr(charAfter) in "[]{}()" and styleAfter == stc.STC_P_OPERATOR: |
|
454 | 492 | braceAtCaret = caretPos |
|
455 | 493 | |
|
456 | 494 | if braceAtCaret >= 0: |
|
457 | 495 | braceOpposite = self.BraceMatch(braceAtCaret) |
|
458 | 496 | |
|
459 | 497 | if braceAtCaret != -1 and braceOpposite == -1: |
|
460 | 498 | self.BraceBadLight(braceAtCaret) |
|
461 | 499 | else: |
|
462 | 500 | self.BraceHighlight(braceAtCaret, braceOpposite) |
|
463 | 501 | #pt = self.PointFromPosition(braceOpposite) |
|
464 | 502 | #self.Refresh(True, wxRect(pt.x, pt.y, 5,5)) |
|
465 | 503 | #print pt |
|
466 | 504 | #self.Refresh(False) |
|
467 | 505 | |
|
468 | 506 | class IPShellWidget(wx.Panel): |
|
469 | 507 | ''' |
|
470 | 508 | This is wx.Panel that embbed the IPython Thread and the wx.StyledTextControl |
|
471 | 509 | If you want to port this to any other GUI toolkit, just replace the |
|
472 | 510 | WxConsoleView by YOURGUIConsoleView and make YOURGUIIPythonView derivate |
|
473 | 511 | from whatever container you want. I've choosed to derivate from a wx.Panel |
|
474 | 512 | because it seems to be more useful |
|
475 | 513 | Any idea to make it more 'generic' welcomed. |
|
476 | 514 | ''' |
|
477 | 515 | |
|
478 | 516 | def __init__(self, parent, intro=None, |
|
479 | 517 | background_color="BLACK", add_button_handler=None, |
|
480 | 518 | wx_ip_shell=None, user_ns={},user_global_ns=None, |
|
481 | 519 | ): |
|
482 | 520 | ''' |
|
483 | 521 | Initialize. |
|
484 | 522 | Instanciate an IPython thread. |
|
485 | 523 | Instanciate a WxConsoleView. |
|
486 | 524 | Redirect I/O to console. |
|
487 | 525 | ''' |
|
488 |
wx.Panel.__init__(self,parent, |
|
|
526 | wx.Panel.__init__(self,parent,wx.ID_ANY) | |
|
489 | 527 | |
|
528 | self.parent = parent | |
|
490 | 529 | ### IPython non blocking shell instanciation ### |
|
491 | 530 | self.cout = StringIO() |
|
492 | 531 | self.add_button_handler = add_button_handler |
|
493 | 532 | |
|
494 | 533 | if wx_ip_shell is not None: |
|
495 | 534 | self.IP = wx_ip_shell |
|
496 | 535 | else: |
|
497 | 536 | self.IP = WxNonBlockingIPShell(self, |
|
498 | 537 | cout = self.cout, cerr = self.cout, |
|
499 | 538 | ask_exit_handler = self.askExitCallback) |
|
500 | 539 | |
|
501 | 540 | ### IPython wx console view instanciation ### |
|
502 | 541 | #If user didn't defined an intro text, we create one for him |
|
503 |
#If you really wnat an empty intr |
|
|
542 | #If you really wnat an empty intro just call wxIPythonViewPanel | |
|
504 | 543 | #with intro='' |
|
505 | 544 | if intro is None: |
|
506 | 545 | welcome_text = "Welcome to WxIPython Shell.\n\n" |
|
507 | 546 | welcome_text+= self.IP.getBanner() |
|
508 | 547 | welcome_text+= "!command -> Execute command in shell\n" |
|
509 | 548 | welcome_text+= "TAB -> Autocompletion\n" |
|
510 | 549 | else: |
|
511 | 550 | welcome_text = intro |
|
512 | 551 | |
|
513 | 552 | self.text_ctrl = WxConsoleView(self, |
|
514 | 553 | self.IP.getPrompt(), |
|
515 | 554 | intro=welcome_text, |
|
516 | 555 | background_color=background_color) |
|
517 | 556 | |
|
518 | 557 | self.cout.write = self.text_ctrl.asyncWrite |
|
558 | ||
|
559 | option_text = wx.StaticText(self, -1, "Options:") | |
|
560 | self.completion_option = wx.CheckBox(self, -1, "Scintilla Completion") | |
|
561 | #self.completion_option.SetValue(False) | |
|
562 | self.background_option = wx.CheckBox(self, -1, "White Background") | |
|
563 | #self.background_option.SetValue(False) | |
|
519 | 564 | |
|
520 | self.text_ctrl.Bind(wx.EVT_KEY_DOWN, self.keyPress, self.text_ctrl) | |
|
521 | ||
|
565 | self.options={'completion':{'value':'IPYTHON', | |
|
566 | 'checkbox':self.completion_option,'STC':True,'IPYTHON':False, | |
|
567 | 'setfunc':self.text_ctrl.setCompletionMethod}, | |
|
568 | 'background_color':{'value':'BLACK', | |
|
569 | 'checkbox':self.background_option,'WHITE':True,'BLACK':False, | |
|
570 | 'setfunc':self.text_ctrl.setBackgroundColor}, | |
|
571 | } | |
|
572 | self.reloadOptions(self.options) | |
|
573 | ||
|
574 | self.text_ctrl.Bind(wx.EVT_KEY_DOWN, self.keyPress) | |
|
575 | self.completion_option.Bind(wx.EVT_CHECKBOX, self.evtCheckOptionCompletion) | |
|
576 | self.background_option.Bind(wx.EVT_CHECKBOX, self.evtCheckOptionBackgroundColor) | |
|
577 | ||
|
522 | 578 | ### making the layout of the panel ### |
|
523 | 579 | sizer = wx.BoxSizer(wx.VERTICAL) |
|
524 | 580 | sizer.Add(self.text_ctrl, 1, wx.EXPAND) |
|
581 | option_sizer = wx.BoxSizer(wx.HORIZONTAL) | |
|
582 | sizer.Add(option_sizer, 0) | |
|
583 | option_sizer.AddMany([(10, 20), | |
|
584 | (option_text, 0, wx.ALIGN_CENTER_VERTICAL), | |
|
585 | (5, 5), | |
|
586 | (self.completion_option, 0, wx.ALIGN_CENTER_VERTICAL), | |
|
587 | (8, 8), | |
|
588 | (self.background_option, 0, wx.ALIGN_CENTER_VERTICAL) | |
|
589 | ]) | |
|
525 | 590 | self.SetAutoLayout(True) |
|
526 | 591 | sizer.Fit(self) |
|
527 | 592 | sizer.SetSizeHints(self) |
|
528 | 593 | self.SetSizer(sizer) |
|
529 | 594 | #and we focus on the widget :) |
|
530 | 595 | self.SetFocus() |
|
531 | 596 | |
|
532 | 597 | #widget state management (for key handling different cases) |
|
533 | 598 | self.setCurrentState('IDLE') |
|
534 | 599 | self.pager_state = 'DONE' |
|
535 | 600 | self.raw_input_current_line = 0 |
|
536 | 601 | |
|
537 | 602 | def askExitCallback(self, event): |
|
538 | 603 | self.askExitHandler(event) |
|
539 | 604 | |
|
540 | 605 | #---------------------- IPython Thread Management ------------------------ |
|
541 | 606 | def stateDoExecuteLine(self): |
|
542 | 607 | lines=self.text_ctrl.getCurrentLine() |
|
543 | 608 | self.text_ctrl.write('\n') |
|
544 | 609 | lines_to_execute = lines.replace('\t',' '*4) |
|
545 |
lines_to_execute = lines_to_execute.replace('\r |
|
|
546 | self.IP.doExecute(lines.encode('cp1252')) | |
|
610 | lines_to_execute = lines_to_execute.replace('\r','') | |
|
611 | self.IP.doExecute(lines_to_execute.encode('cp1252')) | |
|
547 | 612 | self.updateHistoryTracker(lines) |
|
548 | 613 | self.setCurrentState('WAIT_END_OF_EXECUTION') |
|
549 | 614 | |
|
550 | 615 | def evtStateExecuteDone(self,evt): |
|
551 | 616 | self.doc = self.IP.getDocText() |
|
552 | 617 | self.help = self.IP.getHelpText() |
|
553 | 618 | if self.doc: |
|
554 | 619 | self.pager_lines = self.doc[7:].split('\n') |
|
555 | 620 | self.pager_state = 'INIT' |
|
556 | 621 | self.setCurrentState('SHOW_DOC') |
|
557 | 622 | self.pager(self.doc) |
|
558 | 623 | elif self.help: |
|
559 | 624 | self.pager_lines = self.help.split('\n') |
|
560 | 625 | self.pager_state = 'INIT' |
|
561 | 626 | self.setCurrentState('SHOW_DOC') |
|
562 | 627 | self.pager(self.help) |
|
563 | 628 | else: |
|
564 | 629 | self.stateShowPrompt() |
|
565 | 630 | |
|
566 | 631 | def stateShowPrompt(self): |
|
567 | 632 | self.setCurrentState('SHOW_PROMPT') |
|
568 | 633 | self.text_ctrl.setPrompt(self.IP.getPrompt()) |
|
569 | 634 | self.text_ctrl.setIndentation(self.IP.getIndentation()) |
|
570 | 635 | self.text_ctrl.setPromptCount(self.IP.getPromptCount()) |
|
571 | 636 | self.text_ctrl.showPrompt() |
|
572 | 637 | self.IP.initHistoryIndex() |
|
573 | 638 | self.setCurrentState('IDLE') |
|
574 | 639 | |
|
575 | 640 | def setCurrentState(self, state): |
|
576 | 641 | self.cur_state = state |
|
577 | 642 | self.updateStatusTracker(self.cur_state) |
|
578 | 643 | |
|
579 | 644 | def pager(self,text): |
|
580 | 645 | |
|
581 | 646 | if self.pager_state == 'INIT': |
|
582 | 647 | #print >>sys.__stdout__,"PAGER state:",self.pager_state |
|
583 | 648 | self.pager_nb_lines = len(self.pager_lines) |
|
584 | 649 | self.pager_index = 0 |
|
585 | 650 | self.pager_do_remove = False |
|
586 | 651 | self.text_ctrl.write('\n') |
|
587 | 652 | self.pager_state = 'PROCESS_LINES' |
|
588 | 653 | |
|
589 | 654 | if self.pager_state == 'PROCESS_LINES': |
|
590 | 655 | #print >>sys.__stdout__,"PAGER state:",self.pager_state |
|
591 | 656 | if self.pager_do_remove == True: |
|
592 | 657 | self.text_ctrl.removeCurrentLine() |
|
593 | 658 | self.pager_do_remove = False |
|
594 | 659 | |
|
595 | 660 | if self.pager_nb_lines > 10: |
|
596 | 661 | #print >>sys.__stdout__,"PAGER processing 10 lines" |
|
597 | 662 | if self.pager_index > 0: |
|
598 | 663 | self.text_ctrl.write(">\x01\x1b[1;36m\x02"+self.pager_lines[self.pager_index]+'\n') |
|
599 | 664 | else: |
|
600 | 665 | self.text_ctrl.write("\x01\x1b[1;36m\x02 "+self.pager_lines[self.pager_index]+'\n') |
|
601 | 666 | |
|
602 | 667 | for line in self.pager_lines[self.pager_index+1:self.pager_index+9]: |
|
603 | 668 | self.text_ctrl.write("\x01\x1b[1;36m\x02 "+line+'\n') |
|
604 | 669 | self.pager_index += 10 |
|
605 | 670 | self.pager_nb_lines -= 10 |
|
606 | 671 | self.text_ctrl.write("--- Push Enter to continue or 'Q' to quit---") |
|
607 | 672 | self.pager_do_remove = True |
|
608 | 673 | self.pager_state = 'WAITING' |
|
609 | 674 | return |
|
610 | 675 | else: |
|
611 | 676 | #print >>sys.__stdout__,"PAGER processing last lines" |
|
612 | 677 | if self.pager_nb_lines > 0: |
|
613 | 678 | if self.pager_index > 0: |
|
614 | 679 | self.text_ctrl.write(">\x01\x1b[1;36m\x02"+self.pager_lines[self.pager_index]+'\n') |
|
615 | 680 | else: |
|
616 | 681 | self.text_ctrl.write("\x01\x1b[1;36m\x02 "+self.pager_lines[self.pager_index]+'\n') |
|
617 | 682 | |
|
618 | 683 | self.pager_index += 1 |
|
619 | 684 | self.pager_nb_lines -= 1 |
|
620 | 685 | if self.pager_nb_lines > 0: |
|
621 | 686 | for line in self.pager_lines[self.pager_index:]: |
|
622 | 687 | self.text_ctrl.write("\x01\x1b[1;36m\x02 "+line+'\n') |
|
623 | 688 | self.pager_nb_lines = 0 |
|
624 | 689 | self.pager_state = 'DONE' |
|
625 | 690 | self.stateShowPrompt() |
|
626 | 691 | |
|
627 | 692 | #------------------------ Key Handler ------------------------------------ |
|
628 | 693 | def keyPress(self, event): |
|
629 | 694 | ''' |
|
630 | 695 | Key press callback with plenty of shell goodness, like history, |
|
631 | 696 | autocompletions, etc. |
|
632 | 697 | ''' |
|
633 | ||
|
634 | 698 | if event.GetKeyCode() == ord('C'): |
|
635 | if event.Modifiers == wx.MOD_CONTROL: | |
|
699 | if event.Modifiers == wx.MOD_CONTROL or event.Modifiers == wx.MOD_ALT: | |
|
636 | 700 | if self.cur_state == 'WAIT_END_OF_EXECUTION': |
|
637 | 701 | #we raise an exception inside the IPython thread container |
|
638 | 702 | self.IP.ce.raise_exc(KeyboardInterrupt) |
|
639 | 703 | return |
|
640 | 704 | |
|
705 | #let this before 'wx.WXK_RETURN' because we have to put 'IDLE' | |
|
706 | #mode if AutoComp has been set as inactive | |
|
707 | if self.cur_state == 'COMPLETING': | |
|
708 | if not self.text_ctrl.AutoCompActive(): | |
|
709 | self.cur_state = 'IDLE' | |
|
710 | else: | |
|
711 | event.Skip() | |
|
712 | ||
|
641 | 713 | if event.KeyCode == wx.WXK_RETURN: |
|
642 | 714 | if self.cur_state == 'IDLE': |
|
643 | 715 | #we change the state ot the state machine |
|
644 | 716 | self.setCurrentState('DO_EXECUTE_LINE') |
|
645 | 717 | self.stateDoExecuteLine() |
|
646 | 718 | return |
|
719 | ||
|
647 | 720 | if self.pager_state == 'WAITING': |
|
648 | 721 | self.pager_state = 'PROCESS_LINES' |
|
649 | 722 | self.pager(self.doc) |
|
650 | 723 | return |
|
651 | 724 | |
|
652 | 725 | if self.cur_state == 'WAITING_USER_INPUT': |
|
653 | 726 | line=self.text_ctrl.getCurrentLine() |
|
654 | 727 | self.text_ctrl.write('\n') |
|
655 | 728 | self.setCurrentState('WAIT_END_OF_EXECUTION') |
|
656 | 729 | return |
|
657 | 730 | |
|
658 | 731 | if event.GetKeyCode() in [ord('q'),ord('Q')]: |
|
659 | 732 | if self.pager_state == 'WAITING': |
|
660 | 733 | self.pager_state = 'DONE' |
|
661 | 734 | self.text_ctrl.write('\n') |
|
662 | 735 | self.stateShowPrompt() |
|
663 | 736 | return |
|
664 | 737 | |
|
665 | 738 | if self.cur_state == 'WAITING_USER_INPUT': |
|
666 | 739 | event.Skip() |
|
667 | ||
|
740 | ||
|
668 | 741 | if self.cur_state == 'IDLE': |
|
669 | 742 | if event.KeyCode == wx.WXK_UP: |
|
670 | 743 | history = self.IP.historyBack() |
|
671 | 744 | self.text_ctrl.writeHistory(history) |
|
672 | 745 | return |
|
673 | 746 | if event.KeyCode == wx.WXK_DOWN: |
|
674 | 747 | history = self.IP.historyForward() |
|
675 | 748 | self.text_ctrl.writeHistory(history) |
|
676 | 749 | return |
|
677 | 750 | if event.KeyCode == wx.WXK_TAB: |
|
678 | 751 | #if line empty we disable tab completion |
|
679 | 752 | if not self.text_ctrl.getCurrentLine().strip(): |
|
680 | 753 | self.text_ctrl.write('\t') |
|
681 | 754 | return |
|
682 | 755 | completed, possibilities = self.IP.complete(self.text_ctrl.getCurrentLine()) |
|
683 | 756 | if len(possibilities) > 1: |
|
684 |
|
|
|
685 |
self.text_ctrl. |
|
|
686 |
self.text_ctrl.write |
|
|
687 |
self.text_ctrl.write( |
|
|
688 | ||
|
689 | self.text_ctrl.showPrompt() | |
|
690 |
self.text_ctrl. |
|
|
691 |
self.text_ctrl. |
|
|
692 | ||
|
757 | if self.text_ctrl.autocomplete_mode == 'IPYTHON': | |
|
758 | cur_slice = self.text_ctrl.getCurrentLine() | |
|
759 | self.text_ctrl.write('\n') | |
|
760 | self.text_ctrl.writeCompletion(possibilities) | |
|
761 | self.text_ctrl.write('\n') | |
|
762 | ||
|
763 | self.text_ctrl.showPrompt() | |
|
764 | self.text_ctrl.write(cur_slice) | |
|
765 | self.text_ctrl.changeLine(completed or cur_slice) | |
|
766 | else: | |
|
767 | self.cur_state = 'COMPLETING' | |
|
768 | self.text_ctrl.writeCompletion(possibilities) | |
|
769 | else: | |
|
770 | self.text_ctrl.changeLine(completed or cur_slice) | |
|
693 | 771 | return |
|
694 | 772 | event.Skip() |
|
695 | ||
|
773 | ||
|
774 | #------------------------ Option Section --------------------------------- | |
|
775 | def evtCheckOptionCompletion(self, event): | |
|
776 | if event.IsChecked(): | |
|
777 | self.options['completion']['value']='STC' | |
|
778 | else: | |
|
779 | self.options['completion']['value']='IPYTHON' | |
|
780 | self.text_ctrl.setCompletionMethod(self.options['completion']['value']) | |
|
781 | self.updateOptionTracker('completion', | |
|
782 | self.options['completion']['value']) | |
|
783 | self.text_ctrl.SetFocus() | |
|
784 | ||
|
785 | def evtCheckOptionBackgroundColor(self, event): | |
|
786 | if event.IsChecked(): | |
|
787 | self.options['background_color']['value']='WHITE' | |
|
788 | else: | |
|
789 | self.options['background_color']['value']='BLACK' | |
|
790 | self.text_ctrl.setBackgroundColor(self.options['background_color']['value']) | |
|
791 | self.updateOptionTracker('background_color', | |
|
792 | self.options['background_color']['value']) | |
|
793 | self.text_ctrl.SetFocus() | |
|
794 | ||
|
795 | def getOptions(self): | |
|
796 | return self.options | |
|
797 | ||
|
798 | def reloadOptions(self,options): | |
|
799 | self.options = options | |
|
800 | for key in self.options.keys(): | |
|
801 | value = self.options[key]['value'] | |
|
802 | self.options[key]['checkbox'].SetValue(self.options[key][value]) | |
|
803 | self.options[key]['setfunc'](value) | |
|
804 | ||
|
805 | ||
|
696 | 806 | #------------------------ Hook Section ----------------------------------- |
|
807 | def updateOptionTracker(self,name,value): | |
|
808 | ''' | |
|
809 | Default history tracker (does nothing) | |
|
810 | ''' | |
|
811 | pass | |
|
812 | ||
|
813 | def setOptionTrackerHook(self,func): | |
|
814 | ''' | |
|
815 | Define a new history tracker | |
|
816 | ''' | |
|
817 | self.updateOptionTracker = func | |
|
818 | ||
|
697 | 819 | def updateHistoryTracker(self,command_line): |
|
698 | 820 | ''' |
|
699 | 821 | Default history tracker (does nothing) |
|
700 | 822 | ''' |
|
701 | 823 | pass |
|
702 | 824 | |
|
703 | 825 | def setHistoryTrackerHook(self,func): |
|
704 | 826 | ''' |
|
705 | 827 | Define a new history tracker |
|
706 | 828 | ''' |
|
707 | 829 | self.updateHistoryTracker = func |
|
708 | 830 | |
|
709 | 831 | def updateStatusTracker(self,status): |
|
710 | 832 | ''' |
|
711 | 833 | Default status tracker (does nothing) |
|
712 | 834 | ''' |
|
713 | 835 | pass |
|
714 | 836 | |
|
715 | 837 | def setStatusTrackerHook(self,func): |
|
716 | 838 | ''' |
|
717 | 839 | Define a new status tracker |
|
718 | 840 | ''' |
|
719 | 841 | self.updateStatusTracker = func |
|
720 | 842 | |
|
721 | 843 | def askExitHandler(self, event): |
|
722 | 844 | ''' |
|
723 | 845 | Default exit handler |
|
724 | 846 | ''' |
|
725 | 847 | self.text_ctrl.write('\nExit callback has not been set.') |
|
726 | 848 | |
|
727 | 849 | def setAskExitHandler(self, func): |
|
728 | 850 | ''' |
|
729 | 851 | Define an exit handler |
|
730 | 852 | ''' |
|
731 | 853 | self.askExitHandler = func |
|
732 | 854 | |
|
733 | 855 | if __name__ == '__main__': |
|
734 | 856 | # Some simple code to test the shell widget. |
|
735 | 857 | class MainWindow(wx.Frame): |
|
736 | 858 | def __init__(self, parent, id, title): |
|
737 | 859 | wx.Frame.__init__(self, parent, id, title, size=(300,250)) |
|
738 | 860 | self._sizer = wx.BoxSizer(wx.VERTICAL) |
|
739 | 861 | self.shell = IPShellWidget(self) |
|
740 | 862 | self._sizer.Add(self.shell, 1, wx.EXPAND) |
|
741 | 863 | self.SetSizer(self._sizer) |
|
742 | 864 | self.SetAutoLayout(1) |
|
743 | 865 | self.Show(True) |
|
744 | 866 | |
|
745 | 867 | app = wx.PySimpleApp() |
|
746 | 868 | frame = MainWindow(None, wx.ID_ANY, 'Ipython') |
|
747 | 869 | frame.SetSize((780, 460)) |
|
748 | 870 | shell = frame.shell |
|
749 | 871 | |
|
750 | 872 | app.MainLoop() |
|
751 | 873 | |
|
752 | 874 |
@@ -1,202 +1,240 b'' | |||
|
1 | 1 | #!/usr/bin/python |
|
2 | 2 | # -*- coding: iso-8859-15 -*- |
|
3 | 3 | |
|
4 | 4 | import wx.aui |
|
5 | 5 | |
|
6 | 6 | #used for about dialog |
|
7 | 7 | from wx.lib.wordwrap import wordwrap |
|
8 | 8 | |
|
9 | 9 | #used for ipython GUI objects |
|
10 |
from IPython.gui.wx.ipython_view import IPShellWidget |
|
|
10 | from IPython.gui.wx.ipython_view import IPShellWidget | |
|
11 | 11 | from IPython.gui.wx.ipython_history import IPythonHistoryPanel |
|
12 | 12 | |
|
13 | 13 | __version__ = 0.8 |
|
14 | 14 | __author__ = "Laurent Dufrechou" |
|
15 | 15 | __email__ = "laurent.dufrechou _at_ gmail.com" |
|
16 | 16 | __license__ = "BSD" |
|
17 | 17 | |
|
18 | 18 | #----------------------------------------- |
|
19 | 19 | # Creating one main frame for our |
|
20 | 20 | # application with movables windows |
|
21 | 21 | #----------------------------------------- |
|
22 | 22 | class MyFrame(wx.Frame): |
|
23 | 23 | """Creating one main frame for our |
|
24 | 24 | application with movables windows""" |
|
25 | 25 | def __init__(self, parent=None, id=-1, title="WxIPython", |
|
26 | 26 | pos=wx.DefaultPosition, |
|
27 | 27 | size=(800, 600), style=wx.DEFAULT_FRAME_STYLE): |
|
28 | 28 | wx.Frame.__init__(self, parent, id, title, pos, size, style) |
|
29 | 29 | self._mgr = wx.aui.AuiManager() |
|
30 | 30 | |
|
31 | 31 | # notify PyAUI which frame to use |
|
32 | 32 | self._mgr.SetManagedWindow(self) |
|
33 | 33 | |
|
34 | 34 | #create differents panels and make them persistant |
|
35 | 35 | self.history_panel = IPythonHistoryPanel(self) |
|
36 | ||
|
37 | self.history_panel.setOptionTrackerHook(self.optionSave) | |
|
36 | 38 | |
|
37 | 39 | self.ipython_panel = IPShellWidget(self,background_color = "BLACK") |
|
38 | ||
|
39 | 40 | #self.ipython_panel = IPShellWidget(self,background_color = "WHITE") |
|
40 | 41 | |
|
41 | 42 | self.ipython_panel.setHistoryTrackerHook(self.history_panel.write) |
|
42 | 43 | self.ipython_panel.setStatusTrackerHook(self.updateStatus) |
|
43 | 44 | self.ipython_panel.setAskExitHandler(self.OnExitDlg) |
|
45 | self.ipython_panel.setOptionTrackerHook(self.optionSave) | |
|
44 | 46 | |
|
47 | self.optionLoad() | |
|
48 | ||
|
45 | 49 | self.statusbar = self.createStatus() |
|
46 | 50 | self.createMenu() |
|
47 | 51 | |
|
48 | 52 | ######################################################################## |
|
49 | 53 | ### add the panes to the manager |
|
50 | 54 | # main panels |
|
51 | 55 | self._mgr.AddPane(self.ipython_panel , wx.CENTER, "IPython Shell") |
|
52 | 56 | self._mgr.AddPane(self.history_panel , wx.RIGHT, "IPython history") |
|
53 | 57 | |
|
54 | 58 | # now we specify some panel characteristics |
|
55 | 59 | self._mgr.GetPane(self.ipython_panel).CaptionVisible(True); |
|
56 | 60 | self._mgr.GetPane(self.history_panel).CaptionVisible(True); |
|
57 | 61 | self._mgr.GetPane(self.history_panel).MinSize((200,400)); |
|
58 | 62 | |
|
59 | 63 | # tell the manager to "commit" all the changes just made |
|
60 | 64 | self._mgr.Update() |
|
61 | 65 | |
|
62 | 66 | #global event handling |
|
63 | 67 | self.Bind(wx.EVT_CLOSE, self.OnClose) |
|
64 | 68 | self.Bind(wx.EVT_MENU, self.OnClose,id=wx.ID_EXIT) |
|
65 | 69 | self.Bind(wx.EVT_MENU, self.OnShowIPythonPanel,id=wx.ID_HIGHEST+1) |
|
66 | 70 | self.Bind(wx.EVT_MENU, self.OnShowHistoryPanel,id=wx.ID_HIGHEST+2) |
|
67 | 71 | self.Bind(wx.EVT_MENU, self.OnShowAbout, id=wx.ID_HIGHEST+3) |
|
68 | 72 | self.Bind(wx.EVT_MENU, self.OnShowAllPanel,id=wx.ID_HIGHEST+6) |
|
69 | ||
|
73 | ||
|
70 | 74 | warn_text = 'Hello from IPython and wxPython.\n' |
|
71 | 75 | warn_text +='Please Note that this work is still EXPERIMENTAL\n' |
|
72 | 76 | warn_text +='It does NOT emulate currently all the IPython functions.\n' |
|
73 | 77 | |
|
74 | 78 | dlg = wx.MessageDialog(self, |
|
75 | 79 | warn_text, |
|
76 | 80 | 'Warning Box', |
|
77 | 81 | wx.OK | wx.ICON_INFORMATION |
|
78 | 82 | ) |
|
79 | 83 | dlg.ShowModal() |
|
80 | 84 | dlg.Destroy() |
|
81 | ||
|
85 | ||
|
86 | def optionSave(self, name, value): | |
|
87 | opt = open('options.conf','w') | |
|
88 | ||
|
89 | try: | |
|
90 | options_ipython_panel = self.ipython_panel.getOptions() | |
|
91 | options_history_panel = self.history_panel.getOptions() | |
|
92 | ||
|
93 | for key in options_ipython_panel.keys(): | |
|
94 | opt.write(key + '=' + options_ipython_panel[key]['value']+'\n') | |
|
95 | for key in options_history_panel.keys(): | |
|
96 | opt.write(key + '=' + options_history_panel[key]['value']+'\n') | |
|
97 | finally: | |
|
98 | opt.close() | |
|
99 | ||
|
100 | def optionLoad(self): | |
|
101 | opt = open('options.conf','r') | |
|
102 | lines = opt.readlines() | |
|
103 | opt.close() | |
|
104 | ||
|
105 | options_ipython_panel = self.ipython_panel.getOptions() | |
|
106 | options_history_panel = self.history_panel.getOptions() | |
|
107 | ||
|
108 | for line in lines: | |
|
109 | key = line.split('=')[0] | |
|
110 | value = line.split('=')[1].replace('\n','').replace('\r','') | |
|
111 | if key in options_ipython_panel.keys(): | |
|
112 | options_ipython_panel[key]['value'] = value | |
|
113 | elif key in options_history_panel.keys(): | |
|
114 | options_history_panel[key]['value'] = value | |
|
115 | else: | |
|
116 | print >>sys.__stdout__,"Warning: key ",key,"not found in widget options. Check Options.conf" | |
|
117 | self.ipython_panel.reloadOptions(options_ipython_panel) | |
|
118 | self.history_panel.reloadOptions(options_history_panel) | |
|
119 | ||
|
82 | 120 | def createMenu(self): |
|
83 | 121 | """local method used to create one menu bar""" |
|
84 | 122 | |
|
85 | 123 | mb = wx.MenuBar() |
|
86 | 124 | |
|
87 | 125 | file_menu = wx.Menu() |
|
88 | 126 | file_menu.Append(wx.ID_EXIT, "Exit") |
|
89 | 127 | |
|
90 | 128 | view_menu = wx.Menu() |
|
91 | 129 | view_menu.Append(wx.ID_HIGHEST+1, "Show IPython Panel") |
|
92 | 130 | view_menu.Append(wx.ID_HIGHEST+2, "Show History Panel") |
|
93 | 131 | view_menu.AppendSeparator() |
|
94 | 132 | view_menu.Append(wx.ID_HIGHEST+6, "Show All") |
|
95 | 133 | |
|
96 | 134 | about_menu = wx.Menu() |
|
97 | 135 | about_menu.Append(wx.ID_HIGHEST+3, "About") |
|
98 | 136 | |
|
99 | 137 | #view_menu.AppendSeparator() |
|
100 | 138 | #options_menu = wx.Menu() |
|
101 | 139 | #options_menu.AppendCheckItem(wx.ID_HIGHEST+7, "Allow Floating") |
|
102 | 140 | #options_menu.AppendCheckItem(wx.ID_HIGHEST+8, "Transparent Hint") |
|
103 | 141 | #options_menu.AppendCheckItem(wx.ID_HIGHEST+9, "Transparent Hint Fade-in") |
|
104 | 142 | |
|
105 | 143 | |
|
106 | 144 | mb.Append(file_menu, "File") |
|
107 | 145 | mb.Append(view_menu, "View") |
|
108 | 146 | mb.Append(about_menu, "About") |
|
109 | 147 | #mb.Append(options_menu, "Options") |
|
110 | 148 | |
|
111 | 149 | self.SetMenuBar(mb) |
|
112 | 150 | |
|
113 | 151 | def createStatus(self): |
|
114 | 152 | statusbar = self.CreateStatusBar(2, wx.ST_SIZEGRIP) |
|
115 | 153 | statusbar.SetStatusWidths([-2, -3]) |
|
116 | 154 | statusbar.SetStatusText("Ready", 0) |
|
117 | 155 | statusbar.SetStatusText("WxIPython "+str(__version__), 1) |
|
118 | 156 | return statusbar |
|
119 | 157 | |
|
120 | 158 | def updateStatus(self,text): |
|
121 | 159 | states = {'IDLE':'Idle', |
|
122 | 160 | 'DO_EXECUTE_LINE':'Send command', |
|
123 | 161 | 'WAIT_END_OF_EXECUTION':'Running command', |
|
124 | 162 | 'WAITING_USER_INPUT':'Waiting user input', |
|
125 | 163 | 'SHOW_DOC':'Showing doc', |
|
126 | 164 | 'SHOW_PROMPT':'Showing prompt'} |
|
127 | 165 | self.statusbar.SetStatusText(states[text], 0) |
|
128 | 166 | |
|
129 | 167 | def OnClose(self, event): |
|
130 | 168 | """#event used to close program """ |
|
131 | 169 | # deinitialize the frame manager |
|
132 | 170 | self._mgr.UnInit() |
|
133 | 171 | self.Destroy() |
|
134 | 172 | event.Skip() |
|
135 | 173 | |
|
136 | 174 | def OnExitDlg(self, event): |
|
137 | 175 | dlg = wx.MessageDialog(self, 'Are you sure you want to quit WxIPython', |
|
138 | 176 | 'WxIPython exit', |
|
139 | 177 | wx.ICON_QUESTION | |
|
140 | 178 | wx.YES_NO | wx.NO_DEFAULT |
|
141 | 179 | ) |
|
142 | 180 | if dlg.ShowModal() == wx.ID_YES: |
|
143 | 181 | dlg.Destroy() |
|
144 | 182 | self._mgr.UnInit() |
|
145 | 183 | self.Destroy() |
|
146 | 184 | dlg.Destroy() |
|
147 | 185 | |
|
148 | 186 | #event to display IPython pannel |
|
149 | 187 | def OnShowIPythonPanel(self,event): |
|
150 | 188 | """ #event to display Boxpannel """ |
|
151 | 189 | self._mgr.GetPane(self.ipython_panel).Show(True) |
|
152 | 190 | self._mgr.Update() |
|
153 | 191 | #event to display History pannel |
|
154 | 192 | def OnShowHistoryPanel(self,event): |
|
155 | 193 | self._mgr.GetPane(self.history_panel).Show(True) |
|
156 | 194 | self._mgr.Update() |
|
157 | 195 | |
|
158 | 196 | def OnShowAllPanel(self,event): |
|
159 | 197 | """#event to display all Pannels""" |
|
160 | 198 | self._mgr.GetPane(self.ipython_panel).Show(True) |
|
161 | 199 | self._mgr.GetPane(self.history_panel).Show(True) |
|
162 | 200 | self._mgr.Update() |
|
163 | 201 | |
|
164 | 202 | def OnShowAbout(self, event): |
|
165 | 203 | # First we create and fill the info object |
|
166 | 204 | info = wx.AboutDialogInfo() |
|
167 | 205 | info.Name = "WxIPython" |
|
168 | 206 | info.Version = str(__version__) |
|
169 | 207 | info.Copyright = "(C) 2007 Laurent Dufrechou" |
|
170 | 208 | info.Description = wordwrap( |
|
171 | 209 | "A Gui that embbed a multithreaded IPython Shell", |
|
172 | 210 | 350, wx.ClientDC(self)) |
|
173 | 211 | info.WebSite = ("http://ipython.scipy.org/", "IPython home page") |
|
174 | 212 | info.Developers = [ "Laurent Dufrechou" ] |
|
175 | 213 | licenseText="BSD License.\nAll rights reserved. This program and the accompanying materials are made available under the terms of the BSD which accompanies this distribution, and is available at http://www.opensource.org/licenses/bsd-license.php" |
|
176 | 214 | info.License = wordwrap(licenseText, 500, wx.ClientDC(self)) |
|
177 | 215 | |
|
178 | 216 | # Then we call wx.AboutBox giving it that info object |
|
179 | 217 | wx.AboutBox(info) |
|
180 | 218 | |
|
181 | 219 | #----------------------------------------- |
|
182 | 220 | #Creating our application |
|
183 | 221 | #----------------------------------------- |
|
184 | 222 | class MyApp(wx.PySimpleApp): |
|
185 | 223 | """Creating our application""" |
|
186 | 224 | def __init__(self): |
|
187 | 225 | wx.PySimpleApp.__init__(self) |
|
188 | 226 | |
|
189 | 227 | self.frame = MyFrame() |
|
190 | 228 | self.frame.Show() |
|
191 | 229 | |
|
192 | 230 | #----------------------------------------- |
|
193 | 231 | #Main loop |
|
194 | 232 | #----------------------------------------- |
|
195 | 233 | def main(): |
|
196 | 234 | app = MyApp() |
|
197 | 235 | app.SetTopWindow(app.frame) |
|
198 | 236 | app.MainLoop() |
|
199 | 237 | |
|
200 | 238 | #if launched as main program run this |
|
201 | 239 | if __name__ == '__main__': |
|
202 | 240 | main() |
@@ -1,2681 +1,2681 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | IPython -- An enhanced Interactive Python |
|
4 | 4 | |
|
5 | 5 | Requires Python 2.3 or newer. |
|
6 | 6 | |
|
7 | 7 | This file contains all the classes and helper functions specific to IPython. |
|
8 | 8 | |
|
9 | 9 | """ |
|
10 | 10 | |
|
11 | 11 | #***************************************************************************** |
|
12 | 12 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
13 | 13 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
14 | 14 | # |
|
15 | 15 | # Distributed under the terms of the BSD License. The full license is in |
|
16 | 16 | # the file COPYING, distributed as part of this software. |
|
17 | 17 | # |
|
18 | 18 | # Note: this code originally subclassed code.InteractiveConsole from the |
|
19 | 19 | # Python standard library. Over time, all of that class has been copied |
|
20 | 20 | # verbatim here for modifications which could not be accomplished by |
|
21 | 21 | # subclassing. At this point, there are no dependencies at all on the code |
|
22 | 22 | # module anymore (it is not even imported). The Python License (sec. 2) |
|
23 | 23 | # allows for this, but it's always nice to acknowledge credit where credit is |
|
24 | 24 | # due. |
|
25 | 25 | #***************************************************************************** |
|
26 | 26 | |
|
27 | 27 | #**************************************************************************** |
|
28 | 28 | # Modules and globals |
|
29 | 29 | |
|
30 | 30 | from IPython import Release |
|
31 | 31 | __author__ = '%s <%s>\n%s <%s>' % \ |
|
32 | 32 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) |
|
33 | 33 | __license__ = Release.license |
|
34 | 34 | __version__ = Release.version |
|
35 | 35 | |
|
36 | 36 | # Python standard modules |
|
37 | 37 | import __main__ |
|
38 | 38 | import __builtin__ |
|
39 | 39 | import StringIO |
|
40 | 40 | import bdb |
|
41 | 41 | import cPickle as pickle |
|
42 | 42 | import codeop |
|
43 | 43 | import exceptions |
|
44 | 44 | import glob |
|
45 | 45 | import inspect |
|
46 | 46 | import keyword |
|
47 | 47 | import new |
|
48 | 48 | import os |
|
49 | 49 | import pydoc |
|
50 | 50 | import re |
|
51 | 51 | import shutil |
|
52 | 52 | import string |
|
53 | 53 | import sys |
|
54 | 54 | import tempfile |
|
55 | 55 | import traceback |
|
56 | 56 | import types |
|
57 | 57 | from sets import Set |
|
58 | 58 | from pprint import pprint, pformat |
|
59 | 59 | |
|
60 | 60 | # IPython's own modules |
|
61 | 61 | #import IPython |
|
62 | 62 | from IPython import Debugger,OInspect,PyColorize,ultraTB |
|
63 | 63 | from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names |
|
64 | 64 | from IPython.Extensions import pickleshare |
|
65 | 65 | from IPython.FakeModule import FakeModule |
|
66 | 66 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns |
|
67 | 67 | from IPython.Logger import Logger |
|
68 | 68 | from IPython.Magic import Magic |
|
69 | 69 | from IPython.Prompts import CachedOutput |
|
70 | 70 | from IPython.ipstruct import Struct |
|
71 | 71 | from IPython.background_jobs import BackgroundJobManager |
|
72 | 72 | from IPython.usage import cmd_line_usage,interactive_usage |
|
73 | 73 | from IPython.genutils import * |
|
74 | 74 | from IPython.strdispatch import StrDispatch |
|
75 | 75 | import IPython.ipapi |
|
76 | 76 | import IPython.history |
|
77 | 77 | import IPython.prefilter as prefilter |
|
78 | 78 | import IPython.shadowns |
|
79 | 79 | # Globals |
|
80 | 80 | |
|
81 | 81 | # store the builtin raw_input globally, and use this always, in case user code |
|
82 | 82 | # overwrites it (like wx.py.PyShell does) |
|
83 | 83 | raw_input_original = raw_input |
|
84 | 84 | |
|
85 | 85 | # compiled regexps for autoindent management |
|
86 | 86 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
87 | 87 | |
|
88 | 88 | |
|
89 | 89 | #**************************************************************************** |
|
90 | 90 | # Some utility function definitions |
|
91 | 91 | |
|
92 | 92 | ini_spaces_re = re.compile(r'^(\s+)') |
|
93 | 93 | |
|
94 | 94 | def num_ini_spaces(strng): |
|
95 | 95 | """Return the number of initial spaces in a string""" |
|
96 | 96 | |
|
97 | 97 | ini_spaces = ini_spaces_re.match(strng) |
|
98 | 98 | if ini_spaces: |
|
99 | 99 | return ini_spaces.end() |
|
100 | 100 | else: |
|
101 | 101 | return 0 |
|
102 | 102 | |
|
103 | 103 | def softspace(file, newvalue): |
|
104 | 104 | """Copied from code.py, to remove the dependency""" |
|
105 | 105 | |
|
106 | 106 | oldvalue = 0 |
|
107 | 107 | try: |
|
108 | 108 | oldvalue = file.softspace |
|
109 | 109 | except AttributeError: |
|
110 | 110 | pass |
|
111 | 111 | try: |
|
112 | 112 | file.softspace = newvalue |
|
113 | 113 | except (AttributeError, TypeError): |
|
114 | 114 | # "attribute-less object" or "read-only attributes" |
|
115 | 115 | pass |
|
116 | 116 | return oldvalue |
|
117 | 117 | |
|
118 | 118 | |
|
119 | 119 | #**************************************************************************** |
|
120 | 120 | # Local use exceptions |
|
121 | 121 | class SpaceInInput(exceptions.Exception): pass |
|
122 | 122 | |
|
123 | 123 | |
|
124 | 124 | #**************************************************************************** |
|
125 | 125 | # Local use classes |
|
126 | 126 | class Bunch: pass |
|
127 | 127 | |
|
128 | 128 | class Undefined: pass |
|
129 | 129 | |
|
130 | 130 | class Quitter(object): |
|
131 | 131 | """Simple class to handle exit, similar to Python 2.5's. |
|
132 | 132 | |
|
133 | 133 | It handles exiting in an ipython-safe manner, which the one in Python 2.5 |
|
134 | 134 | doesn't do (obviously, since it doesn't know about ipython).""" |
|
135 | 135 | |
|
136 | 136 | def __init__(self,shell,name): |
|
137 | 137 | self.shell = shell |
|
138 | 138 | self.name = name |
|
139 | 139 | |
|
140 | 140 | def __repr__(self): |
|
141 | 141 | return 'Type %s() to exit.' % self.name |
|
142 | 142 | __str__ = __repr__ |
|
143 | 143 | |
|
144 | 144 | def __call__(self): |
|
145 | 145 | self.shell.exit() |
|
146 | 146 | |
|
147 | 147 | class InputList(list): |
|
148 | 148 | """Class to store user input. |
|
149 | 149 | |
|
150 | 150 | It's basically a list, but slices return a string instead of a list, thus |
|
151 | 151 | allowing things like (assuming 'In' is an instance): |
|
152 | 152 | |
|
153 | 153 | exec In[4:7] |
|
154 | 154 | |
|
155 | 155 | or |
|
156 | 156 | |
|
157 | 157 | exec In[5:9] + In[14] + In[21:25]""" |
|
158 | 158 | |
|
159 | 159 | def __getslice__(self,i,j): |
|
160 | 160 | return ''.join(list.__getslice__(self,i,j)) |
|
161 | 161 | |
|
162 | 162 | class SyntaxTB(ultraTB.ListTB): |
|
163 | 163 | """Extension which holds some state: the last exception value""" |
|
164 | 164 | |
|
165 | 165 | def __init__(self,color_scheme = 'NoColor'): |
|
166 | 166 | ultraTB.ListTB.__init__(self,color_scheme) |
|
167 | 167 | self.last_syntax_error = None |
|
168 | 168 | |
|
169 | 169 | def __call__(self, etype, value, elist): |
|
170 | 170 | self.last_syntax_error = value |
|
171 | 171 | ultraTB.ListTB.__call__(self,etype,value,elist) |
|
172 | 172 | |
|
173 | 173 | def clear_err_state(self): |
|
174 | 174 | """Return the current error state and clear it""" |
|
175 | 175 | e = self.last_syntax_error |
|
176 | 176 | self.last_syntax_error = None |
|
177 | 177 | return e |
|
178 | 178 | |
|
179 | 179 | #**************************************************************************** |
|
180 | 180 | # Main IPython class |
|
181 | 181 | |
|
182 | 182 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so |
|
183 | 183 | # until a full rewrite is made. I've cleaned all cross-class uses of |
|
184 | 184 | # attributes and methods, but too much user code out there relies on the |
|
185 | 185 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. |
|
186 | 186 | # |
|
187 | 187 | # But at least now, all the pieces have been separated and we could, in |
|
188 | 188 | # principle, stop using the mixin. This will ease the transition to the |
|
189 | 189 | # chainsaw branch. |
|
190 | 190 | |
|
191 | 191 | # For reference, the following is the list of 'self.foo' uses in the Magic |
|
192 | 192 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython |
|
193 | 193 | # class, to prevent clashes. |
|
194 | 194 | |
|
195 | 195 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', |
|
196 | 196 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', |
|
197 | 197 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', |
|
198 | 198 | # 'self.value'] |
|
199 | 199 | |
|
200 | 200 | class InteractiveShell(object,Magic): |
|
201 | 201 | """An enhanced console for Python.""" |
|
202 | 202 | |
|
203 | 203 | # class attribute to indicate whether the class supports threads or not. |
|
204 | 204 | # Subclasses with thread support should override this as needed. |
|
205 | 205 | isthreaded = False |
|
206 | 206 | |
|
207 | 207 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
208 | 208 | user_ns = None,user_global_ns=None,banner2='', |
|
209 | 209 | custom_exceptions=((),None),embedded=False): |
|
210 | 210 | |
|
211 | 211 | # log system |
|
212 | 212 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') |
|
213 | 213 | |
|
214 | 214 | # some minimal strict typechecks. For some core data structures, I |
|
215 | 215 | # want actual basic python types, not just anything that looks like |
|
216 | 216 | # one. This is especially true for namespaces. |
|
217 | 217 | for ns in (user_ns,user_global_ns): |
|
218 | 218 | if ns is not None and type(ns) != types.DictType: |
|
219 | 219 | raise TypeError,'namespace must be a dictionary' |
|
220 | 220 | # Job manager (for jobs run as background threads) |
|
221 | 221 | self.jobs = BackgroundJobManager() |
|
222 | 222 | |
|
223 | 223 | # Store the actual shell's name |
|
224 | 224 | self.name = name |
|
225 | 225 | self.more = False |
|
226 | 226 | |
|
227 | 227 | # We need to know whether the instance is meant for embedding, since |
|
228 | 228 | # global/local namespaces need to be handled differently in that case |
|
229 | 229 | self.embedded = embedded |
|
230 | 230 | if embedded: |
|
231 | 231 | # Control variable so users can, from within the embedded instance, |
|
232 | 232 | # permanently deactivate it. |
|
233 | 233 | self.embedded_active = True |
|
234 | 234 | |
|
235 | 235 | # command compiler |
|
236 | 236 | self.compile = codeop.CommandCompiler() |
|
237 | 237 | |
|
238 | 238 | # User input buffer |
|
239 | 239 | self.buffer = [] |
|
240 | 240 | |
|
241 | 241 | # Default name given in compilation of code |
|
242 | 242 | self.filename = '<ipython console>' |
|
243 | 243 | |
|
244 | 244 | # Install our own quitter instead of the builtins. For python2.3-2.4, |
|
245 | 245 | # this brings in behavior like 2.5, and for 2.5 it's identical. |
|
246 | 246 | __builtin__.exit = Quitter(self,'exit') |
|
247 | 247 | __builtin__.quit = Quitter(self,'quit') |
|
248 | 248 | |
|
249 | 249 | # Make an empty namespace, which extension writers can rely on both |
|
250 | 250 | # existing and NEVER being used by ipython itself. This gives them a |
|
251 | 251 | # convenient location for storing additional information and state |
|
252 | 252 | # their extensions may require, without fear of collisions with other |
|
253 | 253 | # ipython names that may develop later. |
|
254 | 254 | self.meta = Struct() |
|
255 | 255 | |
|
256 | 256 | # Create the namespace where the user will operate. user_ns is |
|
257 | 257 | # normally the only one used, and it is passed to the exec calls as |
|
258 | 258 | # the locals argument. But we do carry a user_global_ns namespace |
|
259 | 259 | # given as the exec 'globals' argument, This is useful in embedding |
|
260 | 260 | # situations where the ipython shell opens in a context where the |
|
261 | 261 | # distinction between locals and globals is meaningful. |
|
262 | 262 | |
|
263 | 263 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
264 | 264 | # level as a dict instead of a module. This is a manual fix, but I |
|
265 | 265 | # should really track down where the problem is coming from. Alex |
|
266 | 266 | # Schmolck reported this problem first. |
|
267 | 267 | |
|
268 | 268 | # A useful post by Alex Martelli on this topic: |
|
269 | 269 | # Re: inconsistent value from __builtins__ |
|
270 | 270 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
271 | 271 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
272 | 272 | # Gruppen: comp.lang.python |
|
273 | 273 | |
|
274 | 274 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
275 | 275 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
276 | 276 | # > <type 'dict'> |
|
277 | 277 | # > >>> print type(__builtins__) |
|
278 | 278 | # > <type 'module'> |
|
279 | 279 | # > Is this difference in return value intentional? |
|
280 | 280 | |
|
281 | 281 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
282 | 282 | # or a module, and it's been that way for a long time. Whether it's |
|
283 | 283 | # intentional (or sensible), I don't know. In any case, the idea is |
|
284 | 284 | # that if you need to access the built-in namespace directly, you |
|
285 | 285 | # should start with "import __builtin__" (note, no 's') which will |
|
286 | 286 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
287 | 287 | |
|
288 | 288 | # These routines return properly built dicts as needed by the rest of |
|
289 | 289 | # the code, and can also be used by extension writers to generate |
|
290 | 290 | # properly initialized namespaces. |
|
291 | 291 | user_ns = IPython.ipapi.make_user_ns(user_ns) |
|
292 | 292 | user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns) |
|
293 | 293 | |
|
294 | 294 | # Assign namespaces |
|
295 | 295 | # This is the namespace where all normal user variables live |
|
296 | 296 | self.user_ns = user_ns |
|
297 | 297 | # Embedded instances require a separate namespace for globals. |
|
298 | 298 | # Normally this one is unused by non-embedded instances. |
|
299 | 299 | self.user_global_ns = user_global_ns |
|
300 | 300 | # A namespace to keep track of internal data structures to prevent |
|
301 | 301 | # them from cluttering user-visible stuff. Will be updated later |
|
302 | 302 | self.internal_ns = {} |
|
303 | 303 | |
|
304 | 304 | # Namespace of system aliases. Each entry in the alias |
|
305 | 305 | # table must be a 2-tuple of the form (N,name), where N is the number |
|
306 | 306 | # of positional arguments of the alias. |
|
307 | 307 | self.alias_table = {} |
|
308 | 308 | |
|
309 | 309 | # A table holding all the namespaces IPython deals with, so that |
|
310 | 310 | # introspection facilities can search easily. |
|
311 | 311 | self.ns_table = {'user':user_ns, |
|
312 | 312 | 'user_global':user_global_ns, |
|
313 | 313 | 'alias':self.alias_table, |
|
314 | 314 | 'internal':self.internal_ns, |
|
315 | 315 | 'builtin':__builtin__.__dict__ |
|
316 | 316 | } |
|
317 | 317 | # The user namespace MUST have a pointer to the shell itself. |
|
318 | 318 | self.user_ns[name] = self |
|
319 | 319 | |
|
320 | 320 | # We need to insert into sys.modules something that looks like a |
|
321 | 321 | # module but which accesses the IPython namespace, for shelve and |
|
322 | 322 | # pickle to work interactively. Normally they rely on getting |
|
323 | 323 | # everything out of __main__, but for embedding purposes each IPython |
|
324 | 324 | # instance has its own private namespace, so we can't go shoving |
|
325 | 325 | # everything into __main__. |
|
326 | 326 | |
|
327 | 327 | # note, however, that we should only do this for non-embedded |
|
328 | 328 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
329 | 329 | # namespace. Embedded instances, on the other hand, should not do |
|
330 | 330 | # this because they need to manage the user local/global namespaces |
|
331 | 331 | # only, but they live within a 'normal' __main__ (meaning, they |
|
332 | 332 | # shouldn't overtake the execution environment of the script they're |
|
333 | 333 | # embedded in). |
|
334 | 334 | |
|
335 | 335 | if not embedded: |
|
336 | 336 | try: |
|
337 | 337 | main_name = self.user_ns['__name__'] |
|
338 | 338 | except KeyError: |
|
339 | 339 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' |
|
340 | 340 | else: |
|
341 | 341 | #print "pickle hack in place" # dbg |
|
342 | 342 | #print 'main_name:',main_name # dbg |
|
343 | 343 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
344 | 344 | |
|
345 | 345 | # Now that FakeModule produces a real module, we've run into a nasty |
|
346 | 346 | # problem: after script execution (via %run), the module where the user |
|
347 | 347 | # code ran is deleted. Now that this object is a true module (needed |
|
348 | 348 | # so docetst and other tools work correctly), the Python module |
|
349 | 349 | # teardown mechanism runs over it, and sets to None every variable |
|
350 | 350 | # present in that module. This means that later calls to functions |
|
351 | 351 | # defined in the script (which have become interactively visible after |
|
352 | 352 | # script exit) fail, because they hold references to objects that have |
|
353 | 353 | # become overwritten into None. The only solution I see right now is |
|
354 | 354 | # to protect every FakeModule used by %run by holding an internal |
|
355 | 355 | # reference to it. This private list will be used for that. The |
|
356 | 356 | # %reset command will flush it as well. |
|
357 | 357 | self._user_main_modules = [] |
|
358 | 358 | |
|
359 | 359 | # List of input with multi-line handling. |
|
360 | 360 | # Fill its zero entry, user counter starts at 1 |
|
361 | 361 | self.input_hist = InputList(['\n']) |
|
362 | 362 | # This one will hold the 'raw' input history, without any |
|
363 | 363 | # pre-processing. This will allow users to retrieve the input just as |
|
364 | 364 | # it was exactly typed in by the user, with %hist -r. |
|
365 | 365 | self.input_hist_raw = InputList(['\n']) |
|
366 | 366 | |
|
367 | 367 | # list of visited directories |
|
368 | 368 | try: |
|
369 | 369 | self.dir_hist = [os.getcwd()] |
|
370 | 370 | except OSError: |
|
371 | 371 | self.dir_hist = [] |
|
372 | 372 | |
|
373 | 373 | # dict of output history |
|
374 | 374 | self.output_hist = {} |
|
375 | 375 | |
|
376 | 376 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
377 | 377 | # under Win32 have it set to None, and we need to have a known valid |
|
378 | 378 | # encoding to use in the raw_input() method |
|
379 | 379 | try: |
|
380 | 380 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
381 | 381 | except AttributeError: |
|
382 | 382 | self.stdin_encoding = 'ascii' |
|
383 | 383 | |
|
384 | 384 | # dict of things NOT to alias (keywords, builtins and some magics) |
|
385 | 385 | no_alias = {} |
|
386 | 386 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] |
|
387 | 387 | for key in keyword.kwlist + no_alias_magics: |
|
388 | 388 | no_alias[key] = 1 |
|
389 | 389 | no_alias.update(__builtin__.__dict__) |
|
390 | 390 | self.no_alias = no_alias |
|
391 | 391 | |
|
392 | 392 | # make global variables for user access to these |
|
393 | 393 | self.user_ns['_ih'] = self.input_hist |
|
394 | 394 | self.user_ns['_oh'] = self.output_hist |
|
395 | 395 | self.user_ns['_dh'] = self.dir_hist |
|
396 | 396 | |
|
397 | 397 | # user aliases to input and output histories |
|
398 | 398 | self.user_ns['In'] = self.input_hist |
|
399 | 399 | self.user_ns['Out'] = self.output_hist |
|
400 | 400 | |
|
401 | 401 | self.user_ns['_sh'] = IPython.shadowns |
|
402 | 402 | # Object variable to store code object waiting execution. This is |
|
403 | 403 | # used mainly by the multithreaded shells, but it can come in handy in |
|
404 | 404 | # other situations. No need to use a Queue here, since it's a single |
|
405 | 405 | # item which gets cleared once run. |
|
406 | 406 | self.code_to_run = None |
|
407 | 407 | |
|
408 | 408 | # escapes for automatic behavior on the command line |
|
409 | 409 | self.ESC_SHELL = '!' |
|
410 | 410 | self.ESC_SH_CAP = '!!' |
|
411 | 411 | self.ESC_HELP = '?' |
|
412 | 412 | self.ESC_MAGIC = '%' |
|
413 | 413 | self.ESC_QUOTE = ',' |
|
414 | 414 | self.ESC_QUOTE2 = ';' |
|
415 | 415 | self.ESC_PAREN = '/' |
|
416 | 416 | |
|
417 | 417 | # And their associated handlers |
|
418 | 418 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, |
|
419 | 419 | self.ESC_QUOTE : self.handle_auto, |
|
420 | 420 | self.ESC_QUOTE2 : self.handle_auto, |
|
421 | 421 | self.ESC_MAGIC : self.handle_magic, |
|
422 | 422 | self.ESC_HELP : self.handle_help, |
|
423 | 423 | self.ESC_SHELL : self.handle_shell_escape, |
|
424 | 424 | self.ESC_SH_CAP : self.handle_shell_escape, |
|
425 | 425 | } |
|
426 | 426 | |
|
427 | 427 | # class initializations |
|
428 | 428 | Magic.__init__(self,self) |
|
429 | 429 | |
|
430 | 430 | # Python source parser/formatter for syntax highlighting |
|
431 | 431 | pyformat = PyColorize.Parser().format |
|
432 | 432 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) |
|
433 | 433 | |
|
434 | 434 | # hooks holds pointers used for user-side customizations |
|
435 | 435 | self.hooks = Struct() |
|
436 | 436 | |
|
437 | 437 | self.strdispatchers = {} |
|
438 | 438 | |
|
439 | 439 | # Set all default hooks, defined in the IPython.hooks module. |
|
440 | 440 | hooks = IPython.hooks |
|
441 | 441 | for hook_name in hooks.__all__: |
|
442 | 442 | # default hooks have priority 100, i.e. low; user hooks should have |
|
443 | 443 | # 0-100 priority |
|
444 | 444 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
445 | 445 | #print "bound hook",hook_name |
|
446 | 446 | |
|
447 | 447 | # Flag to mark unconditional exit |
|
448 | 448 | self.exit_now = False |
|
449 | 449 | |
|
450 | 450 | self.usage_min = """\ |
|
451 | 451 | An enhanced console for Python. |
|
452 | 452 | Some of its features are: |
|
453 | 453 | - Readline support if the readline library is present. |
|
454 | 454 | - Tab completion in the local namespace. |
|
455 | 455 | - Logging of input, see command-line options. |
|
456 | 456 | - System shell escape via ! , eg !ls. |
|
457 | 457 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) |
|
458 | 458 | - Keeps track of locally defined variables via %who, %whos. |
|
459 | 459 | - Show object information with a ? eg ?x or x? (use ?? for more info). |
|
460 | 460 | """ |
|
461 | 461 | if usage: self.usage = usage |
|
462 | 462 | else: self.usage = self.usage_min |
|
463 | 463 | |
|
464 | 464 | # Storage |
|
465 | 465 | self.rc = rc # This will hold all configuration information |
|
466 | 466 | self.pager = 'less' |
|
467 | 467 | # temporary files used for various purposes. Deleted at exit. |
|
468 | 468 | self.tempfiles = [] |
|
469 | 469 | |
|
470 | 470 | # Keep track of readline usage (later set by init_readline) |
|
471 | 471 | self.has_readline = False |
|
472 | 472 | |
|
473 | 473 | # template for logfile headers. It gets resolved at runtime by the |
|
474 | 474 | # logstart method. |
|
475 | 475 | self.loghead_tpl = \ |
|
476 | 476 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** |
|
477 | 477 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW |
|
478 | 478 | #log# opts = %s |
|
479 | 479 | #log# args = %s |
|
480 | 480 | #log# It is safe to make manual edits below here. |
|
481 | 481 | #log#----------------------------------------------------------------------- |
|
482 | 482 | """ |
|
483 | 483 | # for pushd/popd management |
|
484 | 484 | try: |
|
485 | 485 | self.home_dir = get_home_dir() |
|
486 | 486 | except HomeDirError,msg: |
|
487 | 487 | fatal(msg) |
|
488 | 488 | |
|
489 | 489 | self.dir_stack = [] |
|
490 | 490 | |
|
491 | 491 | # Functions to call the underlying shell. |
|
492 | 492 | |
|
493 | 493 | # The first is similar to os.system, but it doesn't return a value, |
|
494 | 494 | # and it allows interpolation of variables in the user's namespace. |
|
495 | 495 | self.system = lambda cmd: \ |
|
496 | 496 | self.hooks.shell_hook(self.var_expand(cmd,depth=2)) |
|
497 | 497 | |
|
498 | 498 | # These are for getoutput and getoutputerror: |
|
499 | 499 | self.getoutput = lambda cmd: \ |
|
500 | 500 | getoutput(self.var_expand(cmd,depth=2), |
|
501 | 501 | header=self.rc.system_header, |
|
502 | 502 | verbose=self.rc.system_verbose) |
|
503 | 503 | |
|
504 | 504 | self.getoutputerror = lambda cmd: \ |
|
505 | 505 | getoutputerror(self.var_expand(cmd,depth=2), |
|
506 | 506 | header=self.rc.system_header, |
|
507 | 507 | verbose=self.rc.system_verbose) |
|
508 | 508 | |
|
509 | 509 | |
|
510 | 510 | # keep track of where we started running (mainly for crash post-mortem) |
|
511 | 511 | self.starting_dir = os.getcwd() |
|
512 | 512 | |
|
513 | 513 | # Various switches which can be set |
|
514 | 514 | self.CACHELENGTH = 5000 # this is cheap, it's just text |
|
515 | 515 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ |
|
516 | 516 | self.banner2 = banner2 |
|
517 | 517 | |
|
518 | 518 | # TraceBack handlers: |
|
519 | 519 | |
|
520 | 520 | # Syntax error handler. |
|
521 | 521 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
522 | 522 | |
|
523 | 523 | # The interactive one is initialized with an offset, meaning we always |
|
524 | 524 | # want to remove the topmost item in the traceback, which is our own |
|
525 | 525 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
526 | 526 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', |
|
527 | 527 | color_scheme='NoColor', |
|
528 | 528 | tb_offset = 1) |
|
529 | 529 | |
|
530 | 530 | # IPython itself shouldn't crash. This will produce a detailed |
|
531 | 531 | # post-mortem if it does. But we only install the crash handler for |
|
532 | 532 | # non-threaded shells, the threaded ones use a normal verbose reporter |
|
533 | 533 | # and lose the crash handler. This is because exceptions in the main |
|
534 | 534 | # thread (such as in GUI code) propagate directly to sys.excepthook, |
|
535 | 535 | # and there's no point in printing crash dumps for every user exception. |
|
536 | 536 | if self.isthreaded: |
|
537 | 537 | ipCrashHandler = ultraTB.FormattedTB() |
|
538 | 538 | else: |
|
539 | 539 | from IPython import CrashHandler |
|
540 | 540 | ipCrashHandler = CrashHandler.IPythonCrashHandler(self) |
|
541 | 541 | self.set_crash_handler(ipCrashHandler) |
|
542 | 542 | |
|
543 | 543 | # and add any custom exception handlers the user may have specified |
|
544 | 544 | self.set_custom_exc(*custom_exceptions) |
|
545 | 545 | |
|
546 | 546 | # indentation management |
|
547 | 547 | self.autoindent = False |
|
548 | 548 | self.indent_current_nsp = 0 |
|
549 | 549 | |
|
550 | 550 | # Make some aliases automatically |
|
551 | 551 | # Prepare list of shell aliases to auto-define |
|
552 | 552 | if os.name == 'posix': |
|
553 | 553 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', |
|
554 | 554 | 'mv mv -i','rm rm -i','cp cp -i', |
|
555 | 555 | 'cat cat','less less','clear clear', |
|
556 | 556 | # a better ls |
|
557 | 557 | 'ls ls -F', |
|
558 | 558 | # long ls |
|
559 | 559 | 'll ls -lF') |
|
560 | 560 | # Extra ls aliases with color, which need special treatment on BSD |
|
561 | 561 | # variants |
|
562 | 562 | ls_extra = ( # color ls |
|
563 | 563 | 'lc ls -F -o --color', |
|
564 | 564 | # ls normal files only |
|
565 | 565 | 'lf ls -F -o --color %l | grep ^-', |
|
566 | 566 | # ls symbolic links |
|
567 | 567 | 'lk ls -F -o --color %l | grep ^l', |
|
568 | 568 | # directories or links to directories, |
|
569 | 569 | 'ldir ls -F -o --color %l | grep /$', |
|
570 | 570 | # things which are executable |
|
571 | 571 | 'lx ls -F -o --color %l | grep ^-..x', |
|
572 | 572 | ) |
|
573 | 573 | # The BSDs don't ship GNU ls, so they don't understand the |
|
574 | 574 | # --color switch out of the box |
|
575 | 575 | if 'bsd' in sys.platform: |
|
576 | 576 | ls_extra = ( # ls normal files only |
|
577 | 577 | 'lf ls -lF | grep ^-', |
|
578 | 578 | # ls symbolic links |
|
579 | 579 | 'lk ls -lF | grep ^l', |
|
580 | 580 | # directories or links to directories, |
|
581 | 581 | 'ldir ls -lF | grep /$', |
|
582 | 582 | # things which are executable |
|
583 | 583 | 'lx ls -lF | grep ^-..x', |
|
584 | 584 | ) |
|
585 | 585 | auto_alias = auto_alias + ls_extra |
|
586 | 586 | elif os.name in ['nt','dos']: |
|
587 | 587 | auto_alias = ('ls dir /on', |
|
588 | 588 | 'ddir dir /ad /on', 'ldir dir /ad /on', |
|
589 | 589 | 'mkdir mkdir','rmdir rmdir','echo echo', |
|
590 | 590 | 'ren ren','cls cls','copy copy') |
|
591 | 591 | else: |
|
592 | 592 | auto_alias = () |
|
593 | 593 | self.auto_alias = [s.split(None,1) for s in auto_alias] |
|
594 | 594 | |
|
595 | 595 | |
|
596 | 596 | # Produce a public API instance |
|
597 | 597 | self.api = IPython.ipapi.IPApi(self) |
|
598 | 598 | |
|
599 | 599 | # Call the actual (public) initializer |
|
600 | 600 | self.init_auto_alias() |
|
601 | 601 | |
|
602 | 602 | # track which builtins we add, so we can clean up later |
|
603 | 603 | self.builtins_added = {} |
|
604 | 604 | # This method will add the necessary builtins for operation, but |
|
605 | 605 | # tracking what it did via the builtins_added dict. |
|
606 | 606 | |
|
607 | 607 | #TODO: remove this, redundant |
|
608 | 608 | self.add_builtins() |
|
609 | 609 | |
|
610 | 610 | |
|
611 | 611 | |
|
612 | 612 | |
|
613 | 613 | # end __init__ |
|
614 | 614 | |
|
615 | 615 | def var_expand(self,cmd,depth=0): |
|
616 | 616 | """Expand python variables in a string. |
|
617 | 617 | |
|
618 | 618 | The depth argument indicates how many frames above the caller should |
|
619 | 619 | be walked to look for the local namespace where to expand variables. |
|
620 | 620 | |
|
621 | 621 | The global namespace for expansion is always the user's interactive |
|
622 | 622 | namespace. |
|
623 | 623 | """ |
|
624 | 624 | |
|
625 | 625 | return str(ItplNS(cmd, |
|
626 | 626 | self.user_ns, # globals |
|
627 | 627 | # Skip our own frame in searching for locals: |
|
628 | 628 | sys._getframe(depth+1).f_locals # locals |
|
629 | 629 | )) |
|
630 | 630 | |
|
631 | 631 | def pre_config_initialization(self): |
|
632 | 632 | """Pre-configuration init method |
|
633 | 633 | |
|
634 | 634 | This is called before the configuration files are processed to |
|
635 | 635 | prepare the services the config files might need. |
|
636 | 636 | |
|
637 | 637 | self.rc already has reasonable default values at this point. |
|
638 | 638 | """ |
|
639 | 639 | rc = self.rc |
|
640 | 640 | try: |
|
641 | 641 | self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db") |
|
642 | 642 | except exceptions.UnicodeDecodeError: |
|
643 | 643 | print "Your ipythondir can't be decoded to unicode!" |
|
644 | 644 | print "Please set HOME environment variable to something that" |
|
645 | 645 | print r"only has ASCII characters, e.g. c:\home" |
|
646 | 646 | print "Now it is",rc.ipythondir |
|
647 | 647 | sys.exit() |
|
648 | 648 | self.shadowhist = IPython.history.ShadowHist(self.db) |
|
649 | 649 | |
|
650 | 650 | |
|
651 | 651 | def post_config_initialization(self): |
|
652 | 652 | """Post configuration init method |
|
653 | 653 | |
|
654 | 654 | This is called after the configuration files have been processed to |
|
655 | 655 | 'finalize' the initialization.""" |
|
656 | 656 | |
|
657 | 657 | rc = self.rc |
|
658 | 658 | |
|
659 | 659 | # Object inspector |
|
660 | 660 | self.inspector = OInspect.Inspector(OInspect.InspectColors, |
|
661 | 661 | PyColorize.ANSICodeColors, |
|
662 | 662 | 'NoColor', |
|
663 | 663 | rc.object_info_string_level) |
|
664 | 664 | |
|
665 | 665 | self.rl_next_input = None |
|
666 | 666 | self.rl_do_indent = False |
|
667 | 667 | # Load readline proper |
|
668 | 668 | if rc.readline: |
|
669 | 669 | self.init_readline() |
|
670 | 670 | |
|
671 | 671 | |
|
672 | 672 | # local shortcut, this is used a LOT |
|
673 | 673 | self.log = self.logger.log |
|
674 | 674 | |
|
675 | 675 | # Initialize cache, set in/out prompts and printing system |
|
676 | 676 | self.outputcache = CachedOutput(self, |
|
677 | 677 | rc.cache_size, |
|
678 | 678 | rc.pprint, |
|
679 | 679 | input_sep = rc.separate_in, |
|
680 | 680 | output_sep = rc.separate_out, |
|
681 | 681 | output_sep2 = rc.separate_out2, |
|
682 | 682 | ps1 = rc.prompt_in1, |
|
683 | 683 | ps2 = rc.prompt_in2, |
|
684 | 684 | ps_out = rc.prompt_out, |
|
685 | 685 | pad_left = rc.prompts_pad_left) |
|
686 | 686 | |
|
687 | 687 | # user may have over-ridden the default print hook: |
|
688 | 688 | try: |
|
689 | 689 | self.outputcache.__class__.display = self.hooks.display |
|
690 | 690 | except AttributeError: |
|
691 | 691 | pass |
|
692 | 692 | |
|
693 | 693 | # I don't like assigning globally to sys, because it means when |
|
694 | 694 | # embedding instances, each embedded instance overrides the previous |
|
695 | 695 | # choice. But sys.displayhook seems to be called internally by exec, |
|
696 | 696 | # so I don't see a way around it. We first save the original and then |
|
697 | 697 | # overwrite it. |
|
698 | 698 | self.sys_displayhook = sys.displayhook |
|
699 | 699 | sys.displayhook = self.outputcache |
|
700 | 700 | |
|
701 | 701 | # Do a proper resetting of doctest, including the necessary displayhook |
|
702 | 702 | # monkeypatching |
|
703 | 703 | doctest_reload() |
|
704 | 704 | |
|
705 | 705 | # Set user colors (don't do it in the constructor above so that it |
|
706 | 706 | # doesn't crash if colors option is invalid) |
|
707 | 707 | self.magic_colors(rc.colors) |
|
708 | 708 | |
|
709 | 709 | # Set calling of pdb on exceptions |
|
710 | 710 | self.call_pdb = rc.pdb |
|
711 | 711 | |
|
712 | 712 | # Load user aliases |
|
713 | 713 | for alias in rc.alias: |
|
714 | 714 | self.magic_alias(alias) |
|
715 | 715 | |
|
716 | 716 | self.hooks.late_startup_hook() |
|
717 | 717 | |
|
718 | 718 | for cmd in self.rc.autoexec: |
|
719 | 719 | #print "autoexec>",cmd #dbg |
|
720 | 720 | self.api.runlines(cmd) |
|
721 | 721 | |
|
722 | 722 | batchrun = False |
|
723 | 723 | for batchfile in [path(arg) for arg in self.rc.args |
|
724 | 724 | if arg.lower().endswith('.ipy')]: |
|
725 | 725 | if not batchfile.isfile(): |
|
726 | 726 | print "No such batch file:", batchfile |
|
727 | 727 | continue |
|
728 | 728 | self.api.runlines(batchfile.text()) |
|
729 | 729 | batchrun = True |
|
730 | 730 | # without -i option, exit after running the batch file |
|
731 | 731 | if batchrun and not self.rc.interact: |
|
732 | 732 | self.exit_now = True |
|
733 | 733 | |
|
734 | 734 | def add_builtins(self): |
|
735 | 735 | """Store ipython references into the builtin namespace. |
|
736 | 736 | |
|
737 | 737 | Some parts of ipython operate via builtins injected here, which hold a |
|
738 | 738 | reference to IPython itself.""" |
|
739 | 739 | |
|
740 | 740 | # TODO: deprecate all of these, they are unsafe |
|
741 | 741 | builtins_new = dict(__IPYTHON__ = self, |
|
742 | 742 | ip_set_hook = self.set_hook, |
|
743 | 743 | jobs = self.jobs, |
|
744 | 744 | ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'), |
|
745 | 745 | ipalias = wrap_deprecated(self.ipalias), |
|
746 | 746 | ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'), |
|
747 | 747 | #_ip = self.api |
|
748 | 748 | ) |
|
749 | 749 | for biname,bival in builtins_new.items(): |
|
750 | 750 | try: |
|
751 | 751 | # store the orignal value so we can restore it |
|
752 | 752 | self.builtins_added[biname] = __builtin__.__dict__[biname] |
|
753 | 753 | except KeyError: |
|
754 | 754 | # or mark that it wasn't defined, and we'll just delete it at |
|
755 | 755 | # cleanup |
|
756 | 756 | self.builtins_added[biname] = Undefined |
|
757 | 757 | __builtin__.__dict__[biname] = bival |
|
758 | 758 | |
|
759 | 759 | # Keep in the builtins a flag for when IPython is active. We set it |
|
760 | 760 | # with setdefault so that multiple nested IPythons don't clobber one |
|
761 | 761 | # another. Each will increase its value by one upon being activated, |
|
762 | 762 | # which also gives us a way to determine the nesting level. |
|
763 | 763 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) |
|
764 | 764 | |
|
765 | 765 | def clean_builtins(self): |
|
766 | 766 | """Remove any builtins which might have been added by add_builtins, or |
|
767 | 767 | restore overwritten ones to their previous values.""" |
|
768 | 768 | for biname,bival in self.builtins_added.items(): |
|
769 | 769 | if bival is Undefined: |
|
770 | 770 | del __builtin__.__dict__[biname] |
|
771 | 771 | else: |
|
772 | 772 | __builtin__.__dict__[biname] = bival |
|
773 | 773 | self.builtins_added.clear() |
|
774 | 774 | |
|
775 | 775 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
776 | 776 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
777 | 777 | |
|
778 | 778 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
779 | 779 | adding your function to one of these hooks, you can modify IPython's |
|
780 | 780 | behavior to call at runtime your own routines.""" |
|
781 | 781 | |
|
782 | 782 | # At some point in the future, this should validate the hook before it |
|
783 | 783 | # accepts it. Probably at least check that the hook takes the number |
|
784 | 784 | # of args it's supposed to. |
|
785 | 785 | |
|
786 | 786 | f = new.instancemethod(hook,self,self.__class__) |
|
787 | 787 | |
|
788 | 788 | # check if the hook is for strdispatcher first |
|
789 | 789 | if str_key is not None: |
|
790 | 790 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
791 | 791 | sdp.add_s(str_key, f, priority ) |
|
792 | 792 | self.strdispatchers[name] = sdp |
|
793 | 793 | return |
|
794 | 794 | if re_key is not None: |
|
795 | 795 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
796 | 796 | sdp.add_re(re.compile(re_key), f, priority ) |
|
797 | 797 | self.strdispatchers[name] = sdp |
|
798 | 798 | return |
|
799 | 799 | |
|
800 | 800 | dp = getattr(self.hooks, name, None) |
|
801 | 801 | if name not in IPython.hooks.__all__: |
|
802 | 802 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ ) |
|
803 | 803 | if not dp: |
|
804 | 804 | dp = IPython.hooks.CommandChainDispatcher() |
|
805 | 805 | |
|
806 | 806 | try: |
|
807 | 807 | dp.add(f,priority) |
|
808 | 808 | except AttributeError: |
|
809 | 809 | # it was not commandchain, plain old func - replace |
|
810 | 810 | dp = f |
|
811 | 811 | |
|
812 | 812 | setattr(self.hooks,name, dp) |
|
813 | 813 | |
|
814 | 814 | |
|
815 | 815 | #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) |
|
816 | 816 | |
|
817 | 817 | def set_crash_handler(self,crashHandler): |
|
818 | 818 | """Set the IPython crash handler. |
|
819 | 819 | |
|
820 | 820 | This must be a callable with a signature suitable for use as |
|
821 | 821 | sys.excepthook.""" |
|
822 | 822 | |
|
823 | 823 | # Install the given crash handler as the Python exception hook |
|
824 | 824 | sys.excepthook = crashHandler |
|
825 | 825 | |
|
826 | 826 | # The instance will store a pointer to this, so that runtime code |
|
827 | 827 | # (such as magics) can access it. This is because during the |
|
828 | 828 | # read-eval loop, it gets temporarily overwritten (to deal with GUI |
|
829 | 829 | # frameworks). |
|
830 | 830 | self.sys_excepthook = sys.excepthook |
|
831 | 831 | |
|
832 | 832 | |
|
833 | 833 | def set_custom_exc(self,exc_tuple,handler): |
|
834 | 834 | """set_custom_exc(exc_tuple,handler) |
|
835 | 835 | |
|
836 | 836 | Set a custom exception handler, which will be called if any of the |
|
837 | 837 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
838 | 838 | runcode() method. |
|
839 | 839 | |
|
840 | 840 | Inputs: |
|
841 | 841 | |
|
842 | 842 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
843 | 843 | handler for. It is very important that you use a tuple, and NOT A |
|
844 | 844 | LIST here, because of the way Python's except statement works. If |
|
845 | 845 | you only want to trap a single exception, use a singleton tuple: |
|
846 | 846 | |
|
847 | 847 | exc_tuple == (MyCustomException,) |
|
848 | 848 | |
|
849 | 849 | - handler: this must be defined as a function with the following |
|
850 | 850 | basic interface: def my_handler(self,etype,value,tb). |
|
851 | 851 | |
|
852 | 852 | This will be made into an instance method (via new.instancemethod) |
|
853 | 853 | of IPython itself, and it will be called if any of the exceptions |
|
854 | 854 | listed in the exc_tuple are caught. If the handler is None, an |
|
855 | 855 | internal basic one is used, which just prints basic info. |
|
856 | 856 | |
|
857 | 857 | WARNING: by putting in your own exception handler into IPython's main |
|
858 | 858 | execution loop, you run a very good chance of nasty crashes. This |
|
859 | 859 | facility should only be used if you really know what you are doing.""" |
|
860 | 860 | |
|
861 | 861 | assert type(exc_tuple)==type(()) , \ |
|
862 | 862 | "The custom exceptions must be given AS A TUPLE." |
|
863 | 863 | |
|
864 | 864 | def dummy_handler(self,etype,value,tb): |
|
865 | 865 | print '*** Simple custom exception handler ***' |
|
866 | 866 | print 'Exception type :',etype |
|
867 | 867 | print 'Exception value:',value |
|
868 | 868 | print 'Traceback :',tb |
|
869 | 869 | print 'Source code :','\n'.join(self.buffer) |
|
870 | 870 | |
|
871 | 871 | if handler is None: handler = dummy_handler |
|
872 | 872 | |
|
873 | 873 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
874 | 874 | self.custom_exceptions = exc_tuple |
|
875 | 875 | |
|
876 | 876 | def set_custom_completer(self,completer,pos=0): |
|
877 | 877 | """set_custom_completer(completer,pos=0) |
|
878 | 878 | |
|
879 | 879 | Adds a new custom completer function. |
|
880 | 880 | |
|
881 | 881 | The position argument (defaults to 0) is the index in the completers |
|
882 | 882 | list where you want the completer to be inserted.""" |
|
883 | 883 | |
|
884 | 884 | newcomp = new.instancemethod(completer,self.Completer, |
|
885 | 885 | self.Completer.__class__) |
|
886 | 886 | self.Completer.matchers.insert(pos,newcomp) |
|
887 | 887 | |
|
888 | 888 | def set_completer(self): |
|
889 | 889 | """reset readline's completer to be our own.""" |
|
890 | 890 | self.readline.set_completer(self.Completer.complete) |
|
891 | 891 | |
|
892 | 892 | def _get_call_pdb(self): |
|
893 | 893 | return self._call_pdb |
|
894 | 894 | |
|
895 | 895 | def _set_call_pdb(self,val): |
|
896 | 896 | |
|
897 | 897 | if val not in (0,1,False,True): |
|
898 | 898 | raise ValueError,'new call_pdb value must be boolean' |
|
899 | 899 | |
|
900 | 900 | # store value in instance |
|
901 | 901 | self._call_pdb = val |
|
902 | 902 | |
|
903 | 903 | # notify the actual exception handlers |
|
904 | 904 | self.InteractiveTB.call_pdb = val |
|
905 | 905 | if self.isthreaded: |
|
906 | 906 | try: |
|
907 | 907 | self.sys_excepthook.call_pdb = val |
|
908 | 908 | except: |
|
909 | 909 | warn('Failed to activate pdb for threaded exception handler') |
|
910 | 910 | |
|
911 | 911 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
912 | 912 | 'Control auto-activation of pdb at exceptions') |
|
913 | 913 | |
|
914 | 914 | |
|
915 | 915 | # These special functions get installed in the builtin namespace, to |
|
916 | 916 | # provide programmatic (pure python) access to magics, aliases and system |
|
917 | 917 | # calls. This is important for logging, user scripting, and more. |
|
918 | 918 | |
|
919 | 919 | # We are basically exposing, via normal python functions, the three |
|
920 | 920 | # mechanisms in which ipython offers special call modes (magics for |
|
921 | 921 | # internal control, aliases for direct system access via pre-selected |
|
922 | 922 | # names, and !cmd for calling arbitrary system commands). |
|
923 | 923 | |
|
924 | 924 | def ipmagic(self,arg_s): |
|
925 | 925 | """Call a magic function by name. |
|
926 | 926 | |
|
927 | 927 | Input: a string containing the name of the magic function to call and any |
|
928 | 928 | additional arguments to be passed to the magic. |
|
929 | 929 | |
|
930 | 930 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython |
|
931 | 931 | prompt: |
|
932 | 932 | |
|
933 | 933 | In[1]: %name -opt foo bar |
|
934 | 934 | |
|
935 | 935 | To call a magic without arguments, simply use ipmagic('name'). |
|
936 | 936 | |
|
937 | 937 | This provides a proper Python function to call IPython's magics in any |
|
938 | 938 | valid Python code you can type at the interpreter, including loops and |
|
939 | 939 | compound statements. It is added by IPython to the Python builtin |
|
940 | 940 | namespace upon initialization.""" |
|
941 | 941 | |
|
942 | 942 | args = arg_s.split(' ',1) |
|
943 | 943 | magic_name = args[0] |
|
944 | 944 | magic_name = magic_name.lstrip(self.ESC_MAGIC) |
|
945 | 945 | |
|
946 | 946 | try: |
|
947 | 947 | magic_args = args[1] |
|
948 | 948 | except IndexError: |
|
949 | 949 | magic_args = '' |
|
950 | 950 | fn = getattr(self,'magic_'+magic_name,None) |
|
951 | 951 | if fn is None: |
|
952 | 952 | error("Magic function `%s` not found." % magic_name) |
|
953 | 953 | else: |
|
954 | 954 | magic_args = self.var_expand(magic_args,1) |
|
955 | 955 | return fn(magic_args) |
|
956 | 956 | |
|
957 | 957 | def ipalias(self,arg_s): |
|
958 | 958 | """Call an alias by name. |
|
959 | 959 | |
|
960 | 960 | Input: a string containing the name of the alias to call and any |
|
961 | 961 | additional arguments to be passed to the magic. |
|
962 | 962 | |
|
963 | 963 | ipalias('name -opt foo bar') is equivalent to typing at the ipython |
|
964 | 964 | prompt: |
|
965 | 965 | |
|
966 | 966 | In[1]: name -opt foo bar |
|
967 | 967 | |
|
968 | 968 | To call an alias without arguments, simply use ipalias('name'). |
|
969 | 969 | |
|
970 | 970 | This provides a proper Python function to call IPython's aliases in any |
|
971 | 971 | valid Python code you can type at the interpreter, including loops and |
|
972 | 972 | compound statements. It is added by IPython to the Python builtin |
|
973 | 973 | namespace upon initialization.""" |
|
974 | 974 | |
|
975 | 975 | args = arg_s.split(' ',1) |
|
976 | 976 | alias_name = args[0] |
|
977 | 977 | try: |
|
978 | 978 | alias_args = args[1] |
|
979 | 979 | except IndexError: |
|
980 | 980 | alias_args = '' |
|
981 | 981 | if alias_name in self.alias_table: |
|
982 | 982 | self.call_alias(alias_name,alias_args) |
|
983 | 983 | else: |
|
984 | 984 | error("Alias `%s` not found." % alias_name) |
|
985 | 985 | |
|
986 | 986 | def ipsystem(self,arg_s): |
|
987 | 987 | """Make a system call, using IPython.""" |
|
988 | 988 | |
|
989 | 989 | self.system(arg_s) |
|
990 | 990 | |
|
991 | 991 | def complete(self,text): |
|
992 | 992 | """Return a sorted list of all possible completions on text. |
|
993 | 993 | |
|
994 | 994 | Inputs: |
|
995 | 995 | |
|
996 | 996 | - text: a string of text to be completed on. |
|
997 | 997 | |
|
998 | 998 | This is a wrapper around the completion mechanism, similar to what |
|
999 | 999 | readline does at the command line when the TAB key is hit. By |
|
1000 | 1000 | exposing it as a method, it can be used by other non-readline |
|
1001 | 1001 | environments (such as GUIs) for text completion. |
|
1002 | 1002 | |
|
1003 | 1003 | Simple usage example: |
|
1004 | 1004 | |
|
1005 | 1005 | In [1]: x = 'hello' |
|
1006 | 1006 | |
|
1007 | 1007 | In [2]: __IP.complete('x.l') |
|
1008 | 1008 | Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']""" |
|
1009 | 1009 | |
|
1010 | 1010 | complete = self.Completer.complete |
|
1011 | 1011 | state = 0 |
|
1012 | 1012 | # use a dict so we get unique keys, since ipyhton's multiple |
|
1013 | 1013 | # completers can return duplicates. When we make 2.4 a requirement, |
|
1014 | 1014 | # start using sets instead, which are faster. |
|
1015 | 1015 | comps = {} |
|
1016 | 1016 | while True: |
|
1017 | 1017 | newcomp = complete(text,state,line_buffer=text) |
|
1018 | 1018 | if newcomp is None: |
|
1019 | 1019 | break |
|
1020 | 1020 | comps[newcomp] = 1 |
|
1021 | 1021 | state += 1 |
|
1022 | 1022 | outcomps = comps.keys() |
|
1023 | 1023 | outcomps.sort() |
|
1024 | 1024 | return outcomps |
|
1025 | 1025 | |
|
1026 | 1026 | def set_completer_frame(self, frame=None): |
|
1027 | 1027 | if frame: |
|
1028 | 1028 | self.Completer.namespace = frame.f_locals |
|
1029 | 1029 | self.Completer.global_namespace = frame.f_globals |
|
1030 | 1030 | else: |
|
1031 | 1031 | self.Completer.namespace = self.user_ns |
|
1032 | 1032 | self.Completer.global_namespace = self.user_global_ns |
|
1033 | 1033 | |
|
1034 | 1034 | def init_auto_alias(self): |
|
1035 | 1035 | """Define some aliases automatically. |
|
1036 | 1036 | |
|
1037 | 1037 | These are ALL parameter-less aliases""" |
|
1038 | 1038 | |
|
1039 | 1039 | for alias,cmd in self.auto_alias: |
|
1040 | 1040 | self.getapi().defalias(alias,cmd) |
|
1041 | 1041 | |
|
1042 | 1042 | |
|
1043 | 1043 | def alias_table_validate(self,verbose=0): |
|
1044 | 1044 | """Update information about the alias table. |
|
1045 | 1045 | |
|
1046 | 1046 | In particular, make sure no Python keywords/builtins are in it.""" |
|
1047 | 1047 | |
|
1048 | 1048 | no_alias = self.no_alias |
|
1049 | 1049 | for k in self.alias_table.keys(): |
|
1050 | 1050 | if k in no_alias: |
|
1051 | 1051 | del self.alias_table[k] |
|
1052 | 1052 | if verbose: |
|
1053 | 1053 | print ("Deleting alias <%s>, it's a Python " |
|
1054 | 1054 | "keyword or builtin." % k) |
|
1055 | 1055 | |
|
1056 | 1056 | def set_autoindent(self,value=None): |
|
1057 | 1057 | """Set the autoindent flag, checking for readline support. |
|
1058 | 1058 | |
|
1059 | 1059 | If called with no arguments, it acts as a toggle.""" |
|
1060 | 1060 | |
|
1061 | 1061 | if not self.has_readline: |
|
1062 | 1062 | if os.name == 'posix': |
|
1063 | 1063 | warn("The auto-indent feature requires the readline library") |
|
1064 | 1064 | self.autoindent = 0 |
|
1065 | 1065 | return |
|
1066 | 1066 | if value is None: |
|
1067 | 1067 | self.autoindent = not self.autoindent |
|
1068 | 1068 | else: |
|
1069 | 1069 | self.autoindent = value |
|
1070 | 1070 | |
|
1071 | 1071 | def rc_set_toggle(self,rc_field,value=None): |
|
1072 | 1072 | """Set or toggle a field in IPython's rc config. structure. |
|
1073 | 1073 | |
|
1074 | 1074 | If called with no arguments, it acts as a toggle. |
|
1075 | 1075 | |
|
1076 | 1076 | If called with a non-existent field, the resulting AttributeError |
|
1077 | 1077 | exception will propagate out.""" |
|
1078 | 1078 | |
|
1079 | 1079 | rc_val = getattr(self.rc,rc_field) |
|
1080 | 1080 | if value is None: |
|
1081 | 1081 | value = not rc_val |
|
1082 | 1082 | setattr(self.rc,rc_field,value) |
|
1083 | 1083 | |
|
1084 | 1084 | def user_setup(self,ipythondir,rc_suffix,mode='install'): |
|
1085 | 1085 | """Install the user configuration directory. |
|
1086 | 1086 | |
|
1087 | 1087 | Can be called when running for the first time or to upgrade the user's |
|
1088 | 1088 | .ipython/ directory with the mode parameter. Valid modes are 'install' |
|
1089 | 1089 | and 'upgrade'.""" |
|
1090 | 1090 | |
|
1091 | 1091 | def wait(): |
|
1092 | 1092 | try: |
|
1093 | 1093 | raw_input("Please press <RETURN> to start IPython.") |
|
1094 | 1094 | except EOFError: |
|
1095 | 1095 | print >> Term.cout |
|
1096 | 1096 | print '*'*70 |
|
1097 | 1097 | |
|
1098 | 1098 | cwd = os.getcwd() # remember where we started |
|
1099 | 1099 | glb = glob.glob |
|
1100 | 1100 | print '*'*70 |
|
1101 | 1101 | if mode == 'install': |
|
1102 | 1102 | print \ |
|
1103 | 1103 | """Welcome to IPython. I will try to create a personal configuration directory |
|
1104 | 1104 | where you can customize many aspects of IPython's functionality in:\n""" |
|
1105 | 1105 | else: |
|
1106 | 1106 | print 'I am going to upgrade your configuration in:' |
|
1107 | 1107 | |
|
1108 | 1108 | print ipythondir |
|
1109 | 1109 | |
|
1110 | 1110 | rcdirend = os.path.join('IPython','UserConfig') |
|
1111 | 1111 | cfg = lambda d: os.path.join(d,rcdirend) |
|
1112 | 1112 | try: |
|
1113 | 1113 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] |
|
1114 | 1114 | print "Initializing from configuration",rcdir |
|
1115 | 1115 | except IndexError: |
|
1116 | 1116 | warning = """ |
|
1117 | 1117 | Installation error. IPython's directory was not found. |
|
1118 | 1118 | |
|
1119 | 1119 | Check the following: |
|
1120 | 1120 | |
|
1121 | 1121 | The ipython/IPython directory should be in a directory belonging to your |
|
1122 | 1122 | PYTHONPATH environment variable (that is, it should be in a directory |
|
1123 | 1123 | belonging to sys.path). You can copy it explicitly there or just link to it. |
|
1124 | 1124 | |
|
1125 | 1125 | IPython will create a minimal default configuration for you. |
|
1126 | 1126 | |
|
1127 | 1127 | """ |
|
1128 | 1128 | warn(warning) |
|
1129 | 1129 | wait() |
|
1130 | 1130 | |
|
1131 | 1131 | if sys.platform =='win32': |
|
1132 | 1132 | inif = 'ipythonrc.ini' |
|
1133 | 1133 | else: |
|
1134 | 1134 | inif = 'ipythonrc' |
|
1135 | 1135 | minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', inif : '# intentionally left blank' } |
|
1136 | 1136 | os.makedirs(ipythondir, mode = 0777) |
|
1137 | 1137 | for f, cont in minimal_setup.items(): |
|
1138 | 1138 | open(ipythondir + '/' + f,'w').write(cont) |
|
1139 | 1139 | |
|
1140 | 1140 | return |
|
1141 | 1141 | |
|
1142 | 1142 | if mode == 'install': |
|
1143 | 1143 | try: |
|
1144 | 1144 | shutil.copytree(rcdir,ipythondir) |
|
1145 | 1145 | os.chdir(ipythondir) |
|
1146 | 1146 | rc_files = glb("ipythonrc*") |
|
1147 | 1147 | for rc_file in rc_files: |
|
1148 | 1148 | os.rename(rc_file,rc_file+rc_suffix) |
|
1149 | 1149 | except: |
|
1150 | 1150 | warning = """ |
|
1151 | 1151 | |
|
1152 | 1152 | There was a problem with the installation: |
|
1153 | 1153 | %s |
|
1154 | 1154 | Try to correct it or contact the developers if you think it's a bug. |
|
1155 | 1155 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] |
|
1156 | 1156 | warn(warning) |
|
1157 | 1157 | wait() |
|
1158 | 1158 | return |
|
1159 | 1159 | |
|
1160 | 1160 | elif mode == 'upgrade': |
|
1161 | 1161 | try: |
|
1162 | 1162 | os.chdir(ipythondir) |
|
1163 | 1163 | except: |
|
1164 | 1164 | print """ |
|
1165 | 1165 | Can not upgrade: changing to directory %s failed. Details: |
|
1166 | 1166 | %s |
|
1167 | 1167 | """ % (ipythondir,sys.exc_info()[1]) |
|
1168 | 1168 | wait() |
|
1169 | 1169 | return |
|
1170 | 1170 | else: |
|
1171 | 1171 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) |
|
1172 | 1172 | for new_full_path in sources: |
|
1173 | 1173 | new_filename = os.path.basename(new_full_path) |
|
1174 | 1174 | if new_filename.startswith('ipythonrc'): |
|
1175 | 1175 | new_filename = new_filename + rc_suffix |
|
1176 | 1176 | # The config directory should only contain files, skip any |
|
1177 | 1177 | # directories which may be there (like CVS) |
|
1178 | 1178 | if os.path.isdir(new_full_path): |
|
1179 | 1179 | continue |
|
1180 | 1180 | if os.path.exists(new_filename): |
|
1181 | 1181 | old_file = new_filename+'.old' |
|
1182 | 1182 | if os.path.exists(old_file): |
|
1183 | 1183 | os.remove(old_file) |
|
1184 | 1184 | os.rename(new_filename,old_file) |
|
1185 | 1185 | shutil.copy(new_full_path,new_filename) |
|
1186 | 1186 | else: |
|
1187 | 1187 | raise ValueError,'unrecognized mode for install:',`mode` |
|
1188 | 1188 | |
|
1189 | 1189 | # Fix line-endings to those native to each platform in the config |
|
1190 | 1190 | # directory. |
|
1191 | 1191 | try: |
|
1192 | 1192 | os.chdir(ipythondir) |
|
1193 | 1193 | except: |
|
1194 | 1194 | print """ |
|
1195 | 1195 | Problem: changing to directory %s failed. |
|
1196 | 1196 | Details: |
|
1197 | 1197 | %s |
|
1198 | 1198 | |
|
1199 | 1199 | Some configuration files may have incorrect line endings. This should not |
|
1200 | 1200 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) |
|
1201 | 1201 | wait() |
|
1202 | 1202 | else: |
|
1203 | 1203 | for fname in glb('ipythonrc*'): |
|
1204 | 1204 | try: |
|
1205 | 1205 | native_line_ends(fname,backup=0) |
|
1206 | 1206 | except IOError: |
|
1207 | 1207 | pass |
|
1208 | 1208 | |
|
1209 | 1209 | if mode == 'install': |
|
1210 | 1210 | print """ |
|
1211 | 1211 | Successful installation! |
|
1212 | 1212 | |
|
1213 | 1213 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the |
|
1214 | 1214 | IPython manual (there are both HTML and PDF versions supplied with the |
|
1215 | 1215 | distribution) to make sure that your system environment is properly configured |
|
1216 | 1216 | to take advantage of IPython's features. |
|
1217 | 1217 | |
|
1218 | 1218 | Important note: the configuration system has changed! The old system is |
|
1219 | 1219 | still in place, but its setting may be partly overridden by the settings in |
|
1220 | 1220 | "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file |
|
1221 | 1221 | if some of the new settings bother you. |
|
1222 | 1222 | |
|
1223 | 1223 | """ |
|
1224 | 1224 | else: |
|
1225 | 1225 | print """ |
|
1226 | 1226 | Successful upgrade! |
|
1227 | 1227 | |
|
1228 | 1228 | All files in your directory: |
|
1229 | 1229 | %(ipythondir)s |
|
1230 | 1230 | which would have been overwritten by the upgrade were backed up with a .old |
|
1231 | 1231 | extension. If you had made particular customizations in those files you may |
|
1232 | 1232 | want to merge them back into the new files.""" % locals() |
|
1233 | 1233 | wait() |
|
1234 | 1234 | os.chdir(cwd) |
|
1235 | 1235 | # end user_setup() |
|
1236 | 1236 | |
|
1237 | 1237 | def atexit_operations(self): |
|
1238 | 1238 | """This will be executed at the time of exit. |
|
1239 | 1239 | |
|
1240 | 1240 | Saving of persistent data should be performed here. """ |
|
1241 | 1241 | |
|
1242 | 1242 | #print '*** IPython exit cleanup ***' # dbg |
|
1243 | 1243 | # input history |
|
1244 | 1244 | self.savehist() |
|
1245 | 1245 | |
|
1246 | 1246 | # Cleanup all tempfiles left around |
|
1247 | 1247 | for tfile in self.tempfiles: |
|
1248 | 1248 | try: |
|
1249 | 1249 | os.unlink(tfile) |
|
1250 | 1250 | except OSError: |
|
1251 | 1251 | pass |
|
1252 | 1252 | |
|
1253 | 1253 | self.hooks.shutdown_hook() |
|
1254 | 1254 | |
|
1255 | 1255 | def savehist(self): |
|
1256 | 1256 | """Save input history to a file (via readline library).""" |
|
1257 | 1257 | |
|
1258 | 1258 | if not self.has_readline: |
|
1259 | 1259 | return |
|
1260 | 1260 | |
|
1261 | 1261 | try: |
|
1262 | 1262 | self.readline.write_history_file(self.histfile) |
|
1263 | 1263 | except: |
|
1264 | 1264 | print 'Unable to save IPython command history to file: ' + \ |
|
1265 | 1265 | `self.histfile` |
|
1266 | 1266 | |
|
1267 | 1267 | def reloadhist(self): |
|
1268 | 1268 | """Reload the input history from disk file.""" |
|
1269 | 1269 | |
|
1270 | 1270 | if self.has_readline: |
|
1271 | 1271 | try: |
|
1272 | 1272 | self.readline.clear_history() |
|
1273 | 1273 | self.readline.read_history_file(self.shell.histfile) |
|
1274 | 1274 | except AttributeError: |
|
1275 | 1275 | pass |
|
1276 | 1276 | |
|
1277 | 1277 | |
|
1278 | 1278 | def history_saving_wrapper(self, func): |
|
1279 | 1279 | """ Wrap func for readline history saving |
|
1280 | 1280 | |
|
1281 | 1281 | Convert func into callable that saves & restores |
|
1282 | 1282 | history around the call """ |
|
1283 | 1283 | |
|
1284 | 1284 | if not self.has_readline: |
|
1285 | 1285 | return func |
|
1286 | 1286 | |
|
1287 | 1287 | def wrapper(): |
|
1288 | 1288 | self.savehist() |
|
1289 | 1289 | try: |
|
1290 | 1290 | func() |
|
1291 | 1291 | finally: |
|
1292 | 1292 | readline.read_history_file(self.histfile) |
|
1293 | 1293 | return wrapper |
|
1294 | 1294 | |
|
1295 | 1295 | |
|
1296 | 1296 | def pre_readline(self): |
|
1297 | 1297 | """readline hook to be used at the start of each line. |
|
1298 | 1298 | |
|
1299 | 1299 | Currently it handles auto-indent only.""" |
|
1300 | 1300 | |
|
1301 | 1301 | #debugx('self.indent_current_nsp','pre_readline:') |
|
1302 | 1302 | |
|
1303 | 1303 | if self.rl_do_indent: |
|
1304 | 1304 | self.readline.insert_text(self.indent_current_str()) |
|
1305 | 1305 | if self.rl_next_input is not None: |
|
1306 | 1306 | self.readline.insert_text(self.rl_next_input) |
|
1307 | 1307 | self.rl_next_input = None |
|
1308 | 1308 | |
|
1309 | 1309 | def init_readline(self): |
|
1310 | 1310 | """Command history completion/saving/reloading.""" |
|
1311 | 1311 | |
|
1312 | 1312 | |
|
1313 | 1313 | import IPython.rlineimpl as readline |
|
1314 | 1314 | |
|
1315 | 1315 | if not readline.have_readline: |
|
1316 | 1316 | self.has_readline = 0 |
|
1317 | 1317 | self.readline = None |
|
1318 | 1318 | # no point in bugging windows users with this every time: |
|
1319 | 1319 | warn('Readline services not available on this platform.') |
|
1320 | 1320 | else: |
|
1321 | 1321 | sys.modules['readline'] = readline |
|
1322 | 1322 | import atexit |
|
1323 | 1323 | from IPython.completer import IPCompleter |
|
1324 | 1324 | self.Completer = IPCompleter(self, |
|
1325 | 1325 | self.user_ns, |
|
1326 | 1326 | self.user_global_ns, |
|
1327 | 1327 | self.rc.readline_omit__names, |
|
1328 | 1328 | self.alias_table) |
|
1329 | 1329 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1330 | 1330 | self.strdispatchers['complete_command'] = sdisp |
|
1331 | 1331 | self.Completer.custom_completers = sdisp |
|
1332 | 1332 | # Platform-specific configuration |
|
1333 | 1333 | if os.name == 'nt': |
|
1334 | 1334 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1335 | 1335 | else: |
|
1336 | 1336 | self.readline_startup_hook = readline.set_startup_hook |
|
1337 | 1337 | |
|
1338 | 1338 | # Load user's initrc file (readline config) |
|
1339 | 1339 | # Or if libedit is used, load editrc. |
|
1340 | 1340 | inputrc_name = os.environ.get('INPUTRC') |
|
1341 | 1341 | if inputrc_name is None: |
|
1342 | 1342 | home_dir = get_home_dir() |
|
1343 | 1343 | if home_dir is not None: |
|
1344 | 1344 | inputrc_name = '.inputrc' |
|
1345 | 1345 | if readline.uses_libedit: |
|
1346 | 1346 | inputrc_name = '.editrc' |
|
1347 | 1347 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1348 | 1348 | if os.path.isfile(inputrc_name): |
|
1349 | 1349 | try: |
|
1350 | 1350 | readline.read_init_file(inputrc_name) |
|
1351 | 1351 | except: |
|
1352 | 1352 | warn('Problems reading readline initialization file <%s>' |
|
1353 | 1353 | % inputrc_name) |
|
1354 | 1354 | |
|
1355 | 1355 | self.has_readline = 1 |
|
1356 | 1356 | self.readline = readline |
|
1357 | 1357 | # save this in sys so embedded copies can restore it properly |
|
1358 | 1358 | sys.ipcompleter = self.Completer.complete |
|
1359 | 1359 | self.set_completer() |
|
1360 | 1360 | |
|
1361 | 1361 | # Configure readline according to user's prefs |
|
1362 | 1362 | # This is only done if GNU readline is being used. If libedit |
|
1363 | 1363 | # is being used (as on Leopard) the readline config is |
|
1364 | 1364 | # not run as the syntax for libedit is different. |
|
1365 | 1365 | if not readline.uses_libedit: |
|
1366 | 1366 | for rlcommand in self.rc.readline_parse_and_bind: |
|
1367 | 1367 | readline.parse_and_bind(rlcommand) |
|
1368 | 1368 | |
|
1369 | 1369 | # remove some chars from the delimiters list |
|
1370 | 1370 | delims = readline.get_completer_delims() |
|
1371 | 1371 | delims = delims.translate(string._idmap, |
|
1372 | 1372 | self.rc.readline_remove_delims) |
|
1373 | 1373 | readline.set_completer_delims(delims) |
|
1374 | 1374 | # otherwise we end up with a monster history after a while: |
|
1375 | 1375 | readline.set_history_length(1000) |
|
1376 | 1376 | try: |
|
1377 | 1377 | #print '*** Reading readline history' # dbg |
|
1378 | 1378 | readline.read_history_file(self.histfile) |
|
1379 | 1379 | except IOError: |
|
1380 | 1380 | pass # It doesn't exist yet. |
|
1381 | 1381 | |
|
1382 | 1382 | atexit.register(self.atexit_operations) |
|
1383 | 1383 | del atexit |
|
1384 | 1384 | |
|
1385 | 1385 | # Configure auto-indent for all platforms |
|
1386 | 1386 | self.set_autoindent(self.rc.autoindent) |
|
1387 | 1387 | |
|
1388 | 1388 | def ask_yes_no(self,prompt,default=True): |
|
1389 | 1389 | if self.rc.quiet: |
|
1390 | 1390 | return True |
|
1391 | 1391 | return ask_yes_no(prompt,default) |
|
1392 | 1392 | |
|
1393 | 1393 | def _should_recompile(self,e): |
|
1394 | 1394 | """Utility routine for edit_syntax_error""" |
|
1395 | 1395 | |
|
1396 | 1396 | if e.filename in ('<ipython console>','<input>','<string>', |
|
1397 | 1397 | '<console>','<BackgroundJob compilation>', |
|
1398 | 1398 | None): |
|
1399 | 1399 | |
|
1400 | 1400 | return False |
|
1401 | 1401 | try: |
|
1402 | 1402 | if (self.rc.autoedit_syntax and |
|
1403 | 1403 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
1404 | 1404 | '[Y/n] ','y')): |
|
1405 | 1405 | return False |
|
1406 | 1406 | except EOFError: |
|
1407 | 1407 | return False |
|
1408 | 1408 | |
|
1409 | 1409 | def int0(x): |
|
1410 | 1410 | try: |
|
1411 | 1411 | return int(x) |
|
1412 | 1412 | except TypeError: |
|
1413 | 1413 | return 0 |
|
1414 | 1414 | # always pass integer line and offset values to editor hook |
|
1415 | 1415 | self.hooks.fix_error_editor(e.filename, |
|
1416 | 1416 | int0(e.lineno),int0(e.offset),e.msg) |
|
1417 | 1417 | return True |
|
1418 | 1418 | |
|
1419 | 1419 | def edit_syntax_error(self): |
|
1420 | 1420 | """The bottom half of the syntax error handler called in the main loop. |
|
1421 | 1421 | |
|
1422 | 1422 | Loop until syntax error is fixed or user cancels. |
|
1423 | 1423 | """ |
|
1424 | 1424 | |
|
1425 | 1425 | while self.SyntaxTB.last_syntax_error: |
|
1426 | 1426 | # copy and clear last_syntax_error |
|
1427 | 1427 | err = self.SyntaxTB.clear_err_state() |
|
1428 | 1428 | if not self._should_recompile(err): |
|
1429 | 1429 | return |
|
1430 | 1430 | try: |
|
1431 | 1431 | # may set last_syntax_error again if a SyntaxError is raised |
|
1432 | 1432 | self.safe_execfile(err.filename,self.user_ns) |
|
1433 | 1433 | except: |
|
1434 | 1434 | self.showtraceback() |
|
1435 | 1435 | else: |
|
1436 | 1436 | try: |
|
1437 | 1437 | f = file(err.filename) |
|
1438 | 1438 | try: |
|
1439 | 1439 | sys.displayhook(f.read()) |
|
1440 | 1440 | finally: |
|
1441 | 1441 | f.close() |
|
1442 | 1442 | except: |
|
1443 | 1443 | self.showtraceback() |
|
1444 | 1444 | |
|
1445 | 1445 | def showsyntaxerror(self, filename=None): |
|
1446 | 1446 | """Display the syntax error that just occurred. |
|
1447 | 1447 | |
|
1448 | 1448 | This doesn't display a stack trace because there isn't one. |
|
1449 | 1449 | |
|
1450 | 1450 | If a filename is given, it is stuffed in the exception instead |
|
1451 | 1451 | of what was there before (because Python's parser always uses |
|
1452 | 1452 | "<string>" when reading from a string). |
|
1453 | 1453 | """ |
|
1454 | 1454 | etype, value, last_traceback = sys.exc_info() |
|
1455 | 1455 | |
|
1456 | 1456 | # See note about these variables in showtraceback() below |
|
1457 | 1457 | sys.last_type = etype |
|
1458 | 1458 | sys.last_value = value |
|
1459 | 1459 | sys.last_traceback = last_traceback |
|
1460 | 1460 | |
|
1461 | 1461 | if filename and etype is SyntaxError: |
|
1462 | 1462 | # Work hard to stuff the correct filename in the exception |
|
1463 | 1463 | try: |
|
1464 | 1464 | msg, (dummy_filename, lineno, offset, line) = value |
|
1465 | 1465 | except: |
|
1466 | 1466 | # Not the format we expect; leave it alone |
|
1467 | 1467 | pass |
|
1468 | 1468 | else: |
|
1469 | 1469 | # Stuff in the right filename |
|
1470 | 1470 | try: |
|
1471 | 1471 | # Assume SyntaxError is a class exception |
|
1472 | 1472 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1473 | 1473 | except: |
|
1474 | 1474 | # If that failed, assume SyntaxError is a string |
|
1475 | 1475 | value = msg, (filename, lineno, offset, line) |
|
1476 | 1476 | self.SyntaxTB(etype,value,[]) |
|
1477 | 1477 | |
|
1478 | 1478 | def debugger(self,force=False): |
|
1479 | 1479 | """Call the pydb/pdb debugger. |
|
1480 | 1480 | |
|
1481 | 1481 | Keywords: |
|
1482 | 1482 | |
|
1483 | 1483 | - force(False): by default, this routine checks the instance call_pdb |
|
1484 | 1484 | flag and does not actually invoke the debugger if the flag is false. |
|
1485 | 1485 | The 'force' option forces the debugger to activate even if the flag |
|
1486 | 1486 | is false. |
|
1487 | 1487 | """ |
|
1488 | 1488 | |
|
1489 | 1489 | if not (force or self.call_pdb): |
|
1490 | 1490 | return |
|
1491 | 1491 | |
|
1492 | 1492 | if not hasattr(sys,'last_traceback'): |
|
1493 | 1493 | error('No traceback has been produced, nothing to debug.') |
|
1494 | 1494 | return |
|
1495 | 1495 | |
|
1496 | 1496 | # use pydb if available |
|
1497 | 1497 | if Debugger.has_pydb: |
|
1498 | 1498 | from pydb import pm |
|
1499 | 1499 | else: |
|
1500 | 1500 | # fallback to our internal debugger |
|
1501 | 1501 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
1502 | 1502 | self.history_saving_wrapper(pm)() |
|
1503 | 1503 | |
|
1504 | 1504 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): |
|
1505 | 1505 | """Display the exception that just occurred. |
|
1506 | 1506 | |
|
1507 | 1507 | If nothing is known about the exception, this is the method which |
|
1508 | 1508 | should be used throughout the code for presenting user tracebacks, |
|
1509 | 1509 | rather than directly invoking the InteractiveTB object. |
|
1510 | 1510 | |
|
1511 | 1511 | A specific showsyntaxerror() also exists, but this method can take |
|
1512 | 1512 | care of calling it if needed, so unless you are explicitly catching a |
|
1513 | 1513 | SyntaxError exception, don't try to analyze the stack manually and |
|
1514 | 1514 | simply call this method.""" |
|
1515 | 1515 | |
|
1516 | 1516 | |
|
1517 | 1517 | # Though this won't be called by syntax errors in the input line, |
|
1518 | 1518 | # there may be SyntaxError cases whith imported code. |
|
1519 | 1519 | |
|
1520 | 1520 | try: |
|
1521 | 1521 | if exc_tuple is None: |
|
1522 | 1522 | etype, value, tb = sys.exc_info() |
|
1523 | 1523 | else: |
|
1524 | 1524 | etype, value, tb = exc_tuple |
|
1525 | 1525 | |
|
1526 | 1526 | if etype is SyntaxError: |
|
1527 | 1527 | self.showsyntaxerror(filename) |
|
1528 | 1528 | elif etype is IPython.ipapi.UsageError: |
|
1529 | 1529 | print "UsageError:", value |
|
1530 | 1530 | else: |
|
1531 | 1531 | # WARNING: these variables are somewhat deprecated and not |
|
1532 | 1532 | # necessarily safe to use in a threaded environment, but tools |
|
1533 | 1533 | # like pdb depend on their existence, so let's set them. If we |
|
1534 | 1534 | # find problems in the field, we'll need to revisit their use. |
|
1535 | 1535 | sys.last_type = etype |
|
1536 | 1536 | sys.last_value = value |
|
1537 | 1537 | sys.last_traceback = tb |
|
1538 | 1538 | |
|
1539 | 1539 | if etype in self.custom_exceptions: |
|
1540 | 1540 | self.CustomTB(etype,value,tb) |
|
1541 | 1541 | else: |
|
1542 | 1542 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) |
|
1543 | 1543 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1544 | 1544 | # pdb mucks up readline, fix it back |
|
1545 | 1545 | self.set_completer() |
|
1546 | 1546 | except KeyboardInterrupt: |
|
1547 | 1547 | self.write("\nKeyboardInterrupt\n") |
|
1548 | 1548 | |
|
1549 | 1549 | |
|
1550 | 1550 | |
|
1551 | 1551 | def mainloop(self,banner=None): |
|
1552 | 1552 | """Creates the local namespace and starts the mainloop. |
|
1553 | 1553 | |
|
1554 | 1554 | If an optional banner argument is given, it will override the |
|
1555 | 1555 | internally created default banner.""" |
|
1556 | 1556 | |
|
1557 | 1557 | if self.rc.c: # Emulate Python's -c option |
|
1558 | 1558 | self.exec_init_cmd() |
|
1559 | 1559 | if banner is None: |
|
1560 | 1560 | if not self.rc.banner: |
|
1561 | 1561 | banner = '' |
|
1562 | 1562 | # banner is string? Use it directly! |
|
1563 | 1563 | elif isinstance(self.rc.banner,basestring): |
|
1564 | 1564 | banner = self.rc.banner |
|
1565 | 1565 | else: |
|
1566 | 1566 | banner = self.BANNER+self.banner2 |
|
1567 | 1567 | |
|
1568 | 1568 | while 1: |
|
1569 | 1569 | try: |
|
1570 | 1570 | self.interact(banner) |
|
1571 | 1571 | #self.interact_with_readline() |
|
1572 | 1572 | # XXX for testing of a readline-decoupled repl loop, call interact_with_readline above |
|
1573 | 1573 | |
|
1574 | 1574 | break |
|
1575 | 1575 | except KeyboardInterrupt: |
|
1576 | 1576 | # this should not be necessary, but KeyboardInterrupt |
|
1577 | 1577 | # handling seems rather unpredictable... |
|
1578 | 1578 | self.write("\nKeyboardInterrupt in interact()\n") |
|
1579 | 1579 | |
|
1580 | 1580 | def exec_init_cmd(self): |
|
1581 | 1581 | """Execute a command given at the command line. |
|
1582 | 1582 | |
|
1583 | 1583 | This emulates Python's -c option.""" |
|
1584 | 1584 | |
|
1585 | 1585 | #sys.argv = ['-c'] |
|
1586 | 1586 | self.push(self.prefilter(self.rc.c, False)) |
|
1587 | 1587 | if not self.rc.interact: |
|
1588 | 1588 | self.exit_now = True |
|
1589 | 1589 | |
|
1590 | 1590 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): |
|
1591 | 1591 | """Embeds IPython into a running python program. |
|
1592 | 1592 | |
|
1593 | 1593 | Input: |
|
1594 | 1594 | |
|
1595 | 1595 | - header: An optional header message can be specified. |
|
1596 | 1596 | |
|
1597 | 1597 | - local_ns, global_ns: working namespaces. If given as None, the |
|
1598 | 1598 | IPython-initialized one is updated with __main__.__dict__, so that |
|
1599 | 1599 | program variables become visible but user-specific configuration |
|
1600 | 1600 | remains possible. |
|
1601 | 1601 | |
|
1602 | 1602 | - stack_depth: specifies how many levels in the stack to go to |
|
1603 | 1603 | looking for namespaces (when local_ns and global_ns are None). This |
|
1604 | 1604 | allows an intermediate caller to make sure that this function gets |
|
1605 | 1605 | the namespace from the intended level in the stack. By default (0) |
|
1606 | 1606 | it will get its locals and globals from the immediate caller. |
|
1607 | 1607 | |
|
1608 | 1608 | Warning: it's possible to use this in a program which is being run by |
|
1609 | 1609 | IPython itself (via %run), but some funny things will happen (a few |
|
1610 | 1610 | globals get overwritten). In the future this will be cleaned up, as |
|
1611 | 1611 | there is no fundamental reason why it can't work perfectly.""" |
|
1612 | 1612 | |
|
1613 | 1613 | # Get locals and globals from caller |
|
1614 | 1614 | if local_ns is None or global_ns is None: |
|
1615 | 1615 | call_frame = sys._getframe(stack_depth).f_back |
|
1616 | 1616 | |
|
1617 | 1617 | if local_ns is None: |
|
1618 | 1618 | local_ns = call_frame.f_locals |
|
1619 | 1619 | if global_ns is None: |
|
1620 | 1620 | global_ns = call_frame.f_globals |
|
1621 | 1621 | |
|
1622 | 1622 | # Update namespaces and fire up interpreter |
|
1623 | 1623 | |
|
1624 | 1624 | # The global one is easy, we can just throw it in |
|
1625 | 1625 | self.user_global_ns = global_ns |
|
1626 | 1626 | |
|
1627 | 1627 | # but the user/local one is tricky: ipython needs it to store internal |
|
1628 | 1628 | # data, but we also need the locals. We'll copy locals in the user |
|
1629 | 1629 | # one, but will track what got copied so we can delete them at exit. |
|
1630 | 1630 | # This is so that a later embedded call doesn't see locals from a |
|
1631 | 1631 | # previous call (which most likely existed in a separate scope). |
|
1632 | 1632 | local_varnames = local_ns.keys() |
|
1633 | 1633 | self.user_ns.update(local_ns) |
|
1634 | 1634 | |
|
1635 | 1635 | # Patch for global embedding to make sure that things don't overwrite |
|
1636 | 1636 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> |
|
1637 | 1637 | # FIXME. Test this a bit more carefully (the if.. is new) |
|
1638 | 1638 | if local_ns is None and global_ns is None: |
|
1639 | 1639 | self.user_global_ns.update(__main__.__dict__) |
|
1640 | 1640 | |
|
1641 | 1641 | # make sure the tab-completer has the correct frame information, so it |
|
1642 | 1642 | # actually completes using the frame's locals/globals |
|
1643 | 1643 | self.set_completer_frame() |
|
1644 | 1644 | |
|
1645 | 1645 | # before activating the interactive mode, we need to make sure that |
|
1646 | 1646 | # all names in the builtin namespace needed by ipython point to |
|
1647 | 1647 | # ourselves, and not to other instances. |
|
1648 | 1648 | self.add_builtins() |
|
1649 | 1649 | |
|
1650 | 1650 | self.interact(header) |
|
1651 | 1651 | |
|
1652 | 1652 | # now, purge out the user namespace from anything we might have added |
|
1653 | 1653 | # from the caller's local namespace |
|
1654 | 1654 | delvar = self.user_ns.pop |
|
1655 | 1655 | for var in local_varnames: |
|
1656 | 1656 | delvar(var,None) |
|
1657 | 1657 | # and clean builtins we may have overridden |
|
1658 | 1658 | self.clean_builtins() |
|
1659 | 1659 | |
|
1660 | 1660 | def interact_prompt(self): |
|
1661 | 1661 | """ Print the prompt (in read-eval-print loop) |
|
1662 | 1662 | |
|
1663 | 1663 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1664 | 1664 | used in standard IPython flow. |
|
1665 | 1665 | """ |
|
1666 | 1666 | if self.more: |
|
1667 | 1667 | try: |
|
1668 | 1668 | prompt = self.hooks.generate_prompt(True) |
|
1669 | 1669 | except: |
|
1670 | 1670 | self.showtraceback() |
|
1671 | 1671 | if self.autoindent: |
|
1672 | 1672 | self.rl_do_indent = True |
|
1673 | 1673 | |
|
1674 | 1674 | else: |
|
1675 | 1675 | try: |
|
1676 | 1676 | prompt = self.hooks.generate_prompt(False) |
|
1677 | 1677 | except: |
|
1678 | 1678 | self.showtraceback() |
|
1679 | 1679 | self.write(prompt) |
|
1680 | 1680 | |
|
1681 | 1681 | def interact_handle_input(self,line): |
|
1682 | 1682 | """ Handle the input line (in read-eval-print loop) |
|
1683 | 1683 | |
|
1684 | 1684 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1685 | 1685 | used in standard IPython flow. |
|
1686 | 1686 | """ |
|
1687 | 1687 | if line.lstrip() == line: |
|
1688 | 1688 | self.shadowhist.add(line.strip()) |
|
1689 | 1689 | lineout = self.prefilter(line,self.more) |
|
1690 | 1690 | |
|
1691 | 1691 | if line.strip(): |
|
1692 | 1692 | if self.more: |
|
1693 | 1693 | self.input_hist_raw[-1] += '%s\n' % line |
|
1694 | 1694 | else: |
|
1695 | 1695 | self.input_hist_raw.append('%s\n' % line) |
|
1696 | 1696 | |
|
1697 | 1697 | |
|
1698 | 1698 | self.more = self.push(lineout) |
|
1699 | 1699 | if (self.SyntaxTB.last_syntax_error and |
|
1700 | 1700 | self.rc.autoedit_syntax): |
|
1701 | 1701 | self.edit_syntax_error() |
|
1702 | 1702 | |
|
1703 | 1703 | def interact_with_readline(self): |
|
1704 | 1704 | """ Demo of using interact_handle_input, interact_prompt |
|
1705 | 1705 | |
|
1706 | 1706 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), |
|
1707 | 1707 | it should work like this. |
|
1708 | 1708 | """ |
|
1709 | 1709 | self.readline_startup_hook(self.pre_readline) |
|
1710 | 1710 | while not self.exit_now: |
|
1711 | 1711 | self.interact_prompt() |
|
1712 | 1712 | if self.more: |
|
1713 | 1713 | self.rl_do_indent = True |
|
1714 | 1714 | else: |
|
1715 | 1715 | self.rl_do_indent = False |
|
1716 | 1716 | line = raw_input_original().decode(self.stdin_encoding) |
|
1717 | 1717 | self.interact_handle_input(line) |
|
1718 | 1718 | |
|
1719 | 1719 | |
|
1720 | 1720 | def interact(self, banner=None): |
|
1721 | 1721 | """Closely emulate the interactive Python console. |
|
1722 | 1722 | |
|
1723 | 1723 | The optional banner argument specify the banner to print |
|
1724 | 1724 | before the first interaction; by default it prints a banner |
|
1725 | 1725 | similar to the one printed by the real Python interpreter, |
|
1726 | 1726 | followed by the current class name in parentheses (so as not |
|
1727 | 1727 | to confuse this with the real interpreter -- since it's so |
|
1728 | 1728 | close!). |
|
1729 | 1729 | |
|
1730 | 1730 | """ |
|
1731 | 1731 | |
|
1732 | 1732 | if self.exit_now: |
|
1733 | 1733 | # batch run -> do not interact |
|
1734 | 1734 | return |
|
1735 | 1735 | cprt = 'Type "copyright", "credits" or "license" for more information.' |
|
1736 | 1736 | if banner is None: |
|
1737 | 1737 | self.write("Python %s on %s\n%s\n(%s)\n" % |
|
1738 | 1738 | (sys.version, sys.platform, cprt, |
|
1739 | 1739 | self.__class__.__name__)) |
|
1740 | 1740 | else: |
|
1741 | 1741 | self.write(banner) |
|
1742 | 1742 | |
|
1743 | 1743 | more = 0 |
|
1744 | 1744 | |
|
1745 | 1745 | # Mark activity in the builtins |
|
1746 | 1746 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1747 | 1747 | |
|
1748 | 1748 | if self.has_readline: |
|
1749 | 1749 | self.readline_startup_hook(self.pre_readline) |
|
1750 | 1750 | # exit_now is set by a call to %Exit or %Quit |
|
1751 | 1751 | |
|
1752 | 1752 | while not self.exit_now: |
|
1753 | 1753 | self.hooks.pre_prompt_hook() |
|
1754 | 1754 | if more: |
|
1755 | 1755 | try: |
|
1756 | 1756 | prompt = self.hooks.generate_prompt(True) |
|
1757 | 1757 | except: |
|
1758 | 1758 | self.showtraceback() |
|
1759 | 1759 | if self.autoindent: |
|
1760 | 1760 | self.rl_do_indent = True |
|
1761 | 1761 | |
|
1762 | 1762 | else: |
|
1763 | 1763 | try: |
|
1764 | 1764 | prompt = self.hooks.generate_prompt(False) |
|
1765 | 1765 | except: |
|
1766 | 1766 | self.showtraceback() |
|
1767 | 1767 | try: |
|
1768 | 1768 | line = self.raw_input(prompt,more) |
|
1769 | 1769 | if self.exit_now: |
|
1770 | 1770 | # quick exit on sys.std[in|out] close |
|
1771 | 1771 | break |
|
1772 | 1772 | if self.autoindent: |
|
1773 | 1773 | self.rl_do_indent = False |
|
1774 | 1774 | |
|
1775 | 1775 | except KeyboardInterrupt: |
|
1776 | 1776 | #double-guard against keyboardinterrupts during kbdint handling |
|
1777 | 1777 | try: |
|
1778 | 1778 | self.write('\nKeyboardInterrupt\n') |
|
1779 | 1779 | self.resetbuffer() |
|
1780 | 1780 | # keep cache in sync with the prompt counter: |
|
1781 | 1781 | self.outputcache.prompt_count -= 1 |
|
1782 | 1782 | |
|
1783 | 1783 | if self.autoindent: |
|
1784 | 1784 | self.indent_current_nsp = 0 |
|
1785 | 1785 | more = 0 |
|
1786 | 1786 | except KeyboardInterrupt: |
|
1787 | 1787 | pass |
|
1788 | 1788 | except EOFError: |
|
1789 | 1789 | if self.autoindent: |
|
1790 | 1790 | self.rl_do_indent = False |
|
1791 | 1791 | self.readline_startup_hook(None) |
|
1792 | 1792 | self.write('\n') |
|
1793 | 1793 | self.exit() |
|
1794 | 1794 | except bdb.BdbQuit: |
|
1795 | 1795 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
1796 | 1796 | 'Because of how pdb handles the stack, it is impossible\n' |
|
1797 | 1797 | 'for IPython to properly format this particular exception.\n' |
|
1798 | 1798 | 'IPython will resume normal operation.') |
|
1799 | 1799 | except: |
|
1800 | 1800 | # exceptions here are VERY RARE, but they can be triggered |
|
1801 | 1801 | # asynchronously by signal handlers, for example. |
|
1802 | 1802 | self.showtraceback() |
|
1803 | 1803 | else: |
|
1804 | 1804 | more = self.push(line) |
|
1805 | 1805 | if (self.SyntaxTB.last_syntax_error and |
|
1806 | 1806 | self.rc.autoedit_syntax): |
|
1807 | 1807 | self.edit_syntax_error() |
|
1808 | 1808 | |
|
1809 | 1809 | # We are off again... |
|
1810 | 1810 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
1811 | 1811 | |
|
1812 | 1812 | def excepthook(self, etype, value, tb): |
|
1813 | 1813 | """One more defense for GUI apps that call sys.excepthook. |
|
1814 | 1814 | |
|
1815 | 1815 | GUI frameworks like wxPython trap exceptions and call |
|
1816 | 1816 | sys.excepthook themselves. I guess this is a feature that |
|
1817 | 1817 | enables them to keep running after exceptions that would |
|
1818 | 1818 | otherwise kill their mainloop. This is a bother for IPython |
|
1819 | 1819 | which excepts to catch all of the program exceptions with a try: |
|
1820 | 1820 | except: statement. |
|
1821 | 1821 | |
|
1822 | 1822 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1823 | 1823 | any app directly invokes sys.excepthook, it will look to the user like |
|
1824 | 1824 | IPython crashed. In order to work around this, we can disable the |
|
1825 | 1825 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1826 | 1826 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1827 | 1827 | call sys.excepthook will generate a regular-looking exception from |
|
1828 | 1828 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1829 | 1829 | crashes. |
|
1830 | 1830 | |
|
1831 | 1831 | This hook should be used sparingly, only in places which are not likely |
|
1832 | 1832 | to be true IPython errors. |
|
1833 | 1833 | """ |
|
1834 | 1834 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1835 | 1835 | |
|
1836 | 1836 | def expand_aliases(self,fn,rest): |
|
1837 | 1837 | """ Expand multiple levels of aliases: |
|
1838 | 1838 | |
|
1839 | 1839 | if: |
|
1840 | 1840 | |
|
1841 | 1841 | alias foo bar /tmp |
|
1842 | 1842 | alias baz foo |
|
1843 | 1843 | |
|
1844 | 1844 | then: |
|
1845 | 1845 | |
|
1846 | 1846 | baz huhhahhei -> bar /tmp huhhahhei |
|
1847 | 1847 | |
|
1848 | 1848 | """ |
|
1849 | 1849 | line = fn + " " + rest |
|
1850 | 1850 | |
|
1851 | 1851 | done = Set() |
|
1852 | 1852 | while 1: |
|
1853 | 1853 | pre,fn,rest = prefilter.splitUserInput(line, |
|
1854 | 1854 | prefilter.shell_line_split) |
|
1855 | 1855 | if fn in self.alias_table: |
|
1856 | 1856 | if fn in done: |
|
1857 | 1857 | warn("Cyclic alias definition, repeated '%s'" % fn) |
|
1858 | 1858 | return "" |
|
1859 | 1859 | done.add(fn) |
|
1860 | 1860 | |
|
1861 | 1861 | l2 = self.transform_alias(fn,rest) |
|
1862 | 1862 | # dir -> dir |
|
1863 | 1863 | # print "alias",line, "->",l2 #dbg |
|
1864 | 1864 | if l2 == line: |
|
1865 | 1865 | break |
|
1866 | 1866 | # ls -> ls -F should not recurse forever |
|
1867 | 1867 | if l2.split(None,1)[0] == line.split(None,1)[0]: |
|
1868 | 1868 | line = l2 |
|
1869 | 1869 | break |
|
1870 | 1870 | |
|
1871 | 1871 | line=l2 |
|
1872 | 1872 | |
|
1873 | 1873 | |
|
1874 | 1874 | # print "al expand to",line #dbg |
|
1875 | 1875 | else: |
|
1876 | 1876 | break |
|
1877 | 1877 | |
|
1878 | 1878 | return line |
|
1879 | 1879 | |
|
1880 | 1880 | def transform_alias(self, alias,rest=''): |
|
1881 | 1881 | """ Transform alias to system command string. |
|
1882 | 1882 | """ |
|
1883 | 1883 | trg = self.alias_table[alias] |
|
1884 | 1884 | |
|
1885 | 1885 | nargs,cmd = trg |
|
1886 | 1886 | # print trg #dbg |
|
1887 | 1887 | if ' ' in cmd and os.path.isfile(cmd): |
|
1888 | 1888 | cmd = '"%s"' % cmd |
|
1889 | 1889 | |
|
1890 | 1890 | # Expand the %l special to be the user's input line |
|
1891 | 1891 | if cmd.find('%l') >= 0: |
|
1892 | 1892 | cmd = cmd.replace('%l',rest) |
|
1893 | 1893 | rest = '' |
|
1894 | 1894 | if nargs==0: |
|
1895 | 1895 | # Simple, argument-less aliases |
|
1896 | 1896 | cmd = '%s %s' % (cmd,rest) |
|
1897 | 1897 | else: |
|
1898 | 1898 | # Handle aliases with positional arguments |
|
1899 | 1899 | args = rest.split(None,nargs) |
|
1900 | 1900 | if len(args)< nargs: |
|
1901 | 1901 | error('Alias <%s> requires %s arguments, %s given.' % |
|
1902 | 1902 | (alias,nargs,len(args))) |
|
1903 | 1903 | return None |
|
1904 | 1904 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) |
|
1905 | 1905 | # Now call the macro, evaluating in the user's namespace |
|
1906 | 1906 | #print 'new command: <%r>' % cmd # dbg |
|
1907 | 1907 | return cmd |
|
1908 | 1908 | |
|
1909 | 1909 | def call_alias(self,alias,rest=''): |
|
1910 | 1910 | """Call an alias given its name and the rest of the line. |
|
1911 | 1911 | |
|
1912 | 1912 | This is only used to provide backwards compatibility for users of |
|
1913 | 1913 | ipalias(), use of which is not recommended for anymore.""" |
|
1914 | 1914 | |
|
1915 | 1915 | # Now call the macro, evaluating in the user's namespace |
|
1916 | 1916 | cmd = self.transform_alias(alias, rest) |
|
1917 | 1917 | try: |
|
1918 | 1918 | self.system(cmd) |
|
1919 | 1919 | except: |
|
1920 | 1920 | self.showtraceback() |
|
1921 | 1921 | |
|
1922 | 1922 | def indent_current_str(self): |
|
1923 | 1923 | """return the current level of indentation as a string""" |
|
1924 | 1924 | return self.indent_current_nsp * ' ' |
|
1925 | 1925 | |
|
1926 | 1926 | def autoindent_update(self,line): |
|
1927 | 1927 | """Keep track of the indent level.""" |
|
1928 | 1928 | |
|
1929 | 1929 | #debugx('line') |
|
1930 | 1930 | #debugx('self.indent_current_nsp') |
|
1931 | 1931 | if self.autoindent: |
|
1932 | 1932 | if line: |
|
1933 | 1933 | inisp = num_ini_spaces(line) |
|
1934 | 1934 | if inisp < self.indent_current_nsp: |
|
1935 | 1935 | self.indent_current_nsp = inisp |
|
1936 | 1936 | |
|
1937 | 1937 | if line[-1] == ':': |
|
1938 | 1938 | self.indent_current_nsp += 4 |
|
1939 | 1939 | elif dedent_re.match(line): |
|
1940 | 1940 | self.indent_current_nsp -= 4 |
|
1941 | 1941 | else: |
|
1942 | 1942 | self.indent_current_nsp = 0 |
|
1943 | 1943 | |
|
1944 | 1944 | def runlines(self,lines): |
|
1945 | 1945 | """Run a string of one or more lines of source. |
|
1946 | 1946 | |
|
1947 | 1947 | This method is capable of running a string containing multiple source |
|
1948 | 1948 | lines, as if they had been entered at the IPython prompt. Since it |
|
1949 | 1949 | exposes IPython's processing machinery, the given strings can contain |
|
1950 | 1950 | magic calls (%magic), special shell access (!cmd), etc.""" |
|
1951 | 1951 | |
|
1952 | 1952 | # We must start with a clean buffer, in case this is run from an |
|
1953 | 1953 | # interactive IPython session (via a magic, for example). |
|
1954 | 1954 | self.resetbuffer() |
|
1955 | 1955 | lines = lines.split('\n') |
|
1956 | 1956 | more = 0 |
|
1957 | 1957 | |
|
1958 | 1958 | for line in lines: |
|
1959 | 1959 | # skip blank lines so we don't mess up the prompt counter, but do |
|
1960 | 1960 | # NOT skip even a blank line if we are in a code block (more is |
|
1961 | 1961 | # true) |
|
1962 | 1962 | |
|
1963 | 1963 | |
|
1964 | 1964 | if line or more: |
|
1965 | 1965 | # push to raw history, so hist line numbers stay in sync |
|
1966 | 1966 | self.input_hist_raw.append("# " + line + "\n") |
|
1967 | 1967 | more = self.push(self.prefilter(line,more)) |
|
1968 | 1968 | # IPython's runsource returns None if there was an error |
|
1969 | 1969 | # compiling the code. This allows us to stop processing right |
|
1970 | 1970 | # away, so the user gets the error message at the right place. |
|
1971 | 1971 | if more is None: |
|
1972 | 1972 | break |
|
1973 | 1973 | else: |
|
1974 | 1974 | self.input_hist_raw.append("\n") |
|
1975 | 1975 | # final newline in case the input didn't have it, so that the code |
|
1976 | 1976 | # actually does get executed |
|
1977 | 1977 | if more: |
|
1978 | 1978 | self.push('\n') |
|
1979 | 1979 | |
|
1980 | 1980 | def runsource(self, source, filename='<input>', symbol='single'): |
|
1981 | 1981 | """Compile and run some source in the interpreter. |
|
1982 | 1982 | |
|
1983 | 1983 | Arguments are as for compile_command(). |
|
1984 | 1984 | |
|
1985 | 1985 | One several things can happen: |
|
1986 | 1986 | |
|
1987 | 1987 | 1) The input is incorrect; compile_command() raised an |
|
1988 | 1988 | exception (SyntaxError or OverflowError). A syntax traceback |
|
1989 | 1989 | will be printed by calling the showsyntaxerror() method. |
|
1990 | 1990 | |
|
1991 | 1991 | 2) The input is incomplete, and more input is required; |
|
1992 | 1992 | compile_command() returned None. Nothing happens. |
|
1993 | 1993 | |
|
1994 | 1994 | 3) The input is complete; compile_command() returned a code |
|
1995 | 1995 | object. The code is executed by calling self.runcode() (which |
|
1996 | 1996 | also handles run-time exceptions, except for SystemExit). |
|
1997 | 1997 | |
|
1998 | 1998 | The return value is: |
|
1999 | 1999 | |
|
2000 | 2000 | - True in case 2 |
|
2001 | 2001 | |
|
2002 | 2002 | - False in the other cases, unless an exception is raised, where |
|
2003 | 2003 | None is returned instead. This can be used by external callers to |
|
2004 | 2004 | know whether to continue feeding input or not. |
|
2005 | 2005 | |
|
2006 | 2006 | The return value can be used to decide whether to use sys.ps1 or |
|
2007 | 2007 | sys.ps2 to prompt the next line.""" |
|
2008 | 2008 | |
|
2009 | 2009 | # if the source code has leading blanks, add 'if 1:\n' to it |
|
2010 | 2010 | # this allows execution of indented pasted code. It is tempting |
|
2011 | 2011 | # to add '\n' at the end of source to run commands like ' a=1' |
|
2012 | 2012 | # directly, but this fails for more complicated scenarios |
|
2013 | 2013 | source=source.encode(self.stdin_encoding) |
|
2014 | 2014 | if source[:1] in [' ', '\t']: |
|
2015 | 2015 | source = 'if 1:\n%s' % source |
|
2016 | 2016 | |
|
2017 | 2017 | try: |
|
2018 | 2018 | code = self.compile(source,filename,symbol) |
|
2019 | except (OverflowError, SyntaxError, ValueError): | |
|
2019 | except (OverflowError, SyntaxError, ValueError, TypeError): | |
|
2020 | 2020 | # Case 1 |
|
2021 | 2021 | self.showsyntaxerror(filename) |
|
2022 | 2022 | return None |
|
2023 | 2023 | |
|
2024 | 2024 | if code is None: |
|
2025 | 2025 | # Case 2 |
|
2026 | 2026 | return True |
|
2027 | 2027 | |
|
2028 | 2028 | # Case 3 |
|
2029 | 2029 | # We store the code object so that threaded shells and |
|
2030 | 2030 | # custom exception handlers can access all this info if needed. |
|
2031 | 2031 | # The source corresponding to this can be obtained from the |
|
2032 | 2032 | # buffer attribute as '\n'.join(self.buffer). |
|
2033 | 2033 | self.code_to_run = code |
|
2034 | 2034 | # now actually execute the code object |
|
2035 | 2035 | if self.runcode(code) == 0: |
|
2036 | 2036 | return False |
|
2037 | 2037 | else: |
|
2038 | 2038 | return None |
|
2039 | 2039 | |
|
2040 | 2040 | def runcode(self,code_obj): |
|
2041 | 2041 | """Execute a code object. |
|
2042 | 2042 | |
|
2043 | 2043 | When an exception occurs, self.showtraceback() is called to display a |
|
2044 | 2044 | traceback. |
|
2045 | 2045 | |
|
2046 | 2046 | Return value: a flag indicating whether the code to be run completed |
|
2047 | 2047 | successfully: |
|
2048 | 2048 | |
|
2049 | 2049 | - 0: successful execution. |
|
2050 | 2050 | - 1: an error occurred. |
|
2051 | 2051 | """ |
|
2052 | 2052 | |
|
2053 | 2053 | # Set our own excepthook in case the user code tries to call it |
|
2054 | 2054 | # directly, so that the IPython crash handler doesn't get triggered |
|
2055 | 2055 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2056 | 2056 | |
|
2057 | 2057 | # we save the original sys.excepthook in the instance, in case config |
|
2058 | 2058 | # code (such as magics) needs access to it. |
|
2059 | 2059 | self.sys_excepthook = old_excepthook |
|
2060 | 2060 | outflag = 1 # happens in more places, so it's easier as default |
|
2061 | 2061 | try: |
|
2062 | 2062 | try: |
|
2063 | 2063 | self.hooks.pre_runcode_hook() |
|
2064 | 2064 | # Embedded instances require separate global/local namespaces |
|
2065 | 2065 | # so they can see both the surrounding (local) namespace and |
|
2066 | 2066 | # the module-level globals when called inside another function. |
|
2067 | 2067 | if self.embedded: |
|
2068 | 2068 | exec code_obj in self.user_global_ns, self.user_ns |
|
2069 | 2069 | # Normal (non-embedded) instances should only have a single |
|
2070 | 2070 | # namespace for user code execution, otherwise functions won't |
|
2071 | 2071 | # see interactive top-level globals. |
|
2072 | 2072 | else: |
|
2073 | 2073 | exec code_obj in self.user_ns |
|
2074 | 2074 | finally: |
|
2075 | 2075 | # Reset our crash handler in place |
|
2076 | 2076 | sys.excepthook = old_excepthook |
|
2077 | 2077 | except SystemExit: |
|
2078 | 2078 | self.resetbuffer() |
|
2079 | 2079 | self.showtraceback() |
|
2080 | 2080 | warn("Type %exit or %quit to exit IPython " |
|
2081 | 2081 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
2082 | 2082 | except self.custom_exceptions: |
|
2083 | 2083 | etype,value,tb = sys.exc_info() |
|
2084 | 2084 | self.CustomTB(etype,value,tb) |
|
2085 | 2085 | except: |
|
2086 | 2086 | self.showtraceback() |
|
2087 | 2087 | else: |
|
2088 | 2088 | outflag = 0 |
|
2089 | 2089 | if softspace(sys.stdout, 0): |
|
2090 | 2090 | |
|
2091 | 2091 | # Flush out code object which has been run (and source) |
|
2092 | 2092 | self.code_to_run = None |
|
2093 | 2093 | return outflag |
|
2094 | 2094 | |
|
2095 | 2095 | def push(self, line): |
|
2096 | 2096 | """Push a line to the interpreter. |
|
2097 | 2097 | |
|
2098 | 2098 | The line should not have a trailing newline; it may have |
|
2099 | 2099 | internal newlines. The line is appended to a buffer and the |
|
2100 | 2100 | interpreter's runsource() method is called with the |
|
2101 | 2101 | concatenated contents of the buffer as source. If this |
|
2102 | 2102 | indicates that the command was executed or invalid, the buffer |
|
2103 | 2103 | is reset; otherwise, the command is incomplete, and the buffer |
|
2104 | 2104 | is left as it was after the line was appended. The return |
|
2105 | 2105 | value is 1 if more input is required, 0 if the line was dealt |
|
2106 | 2106 | with in some way (this is the same as runsource()). |
|
2107 | 2107 | """ |
|
2108 | 2108 | |
|
2109 | 2109 | # autoindent management should be done here, and not in the |
|
2110 | 2110 | # interactive loop, since that one is only seen by keyboard input. We |
|
2111 | 2111 | # need this done correctly even for code run via runlines (which uses |
|
2112 | 2112 | # push). |
|
2113 | 2113 | |
|
2114 | 2114 | #print 'push line: <%s>' % line # dbg |
|
2115 | 2115 | for subline in line.splitlines(): |
|
2116 | 2116 | self.autoindent_update(subline) |
|
2117 | 2117 | self.buffer.append(line) |
|
2118 | 2118 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
2119 | 2119 | if not more: |
|
2120 | 2120 | self.resetbuffer() |
|
2121 | 2121 | return more |
|
2122 | 2122 | |
|
2123 | 2123 | def split_user_input(self, line): |
|
2124 | 2124 | # This is really a hold-over to support ipapi and some extensions |
|
2125 | 2125 | return prefilter.splitUserInput(line) |
|
2126 | 2126 | |
|
2127 | 2127 | def resetbuffer(self): |
|
2128 | 2128 | """Reset the input buffer.""" |
|
2129 | 2129 | self.buffer[:] = [] |
|
2130 | 2130 | |
|
2131 | 2131 | def raw_input(self,prompt='',continue_prompt=False): |
|
2132 | 2132 | """Write a prompt and read a line. |
|
2133 | 2133 | |
|
2134 | 2134 | The returned line does not include the trailing newline. |
|
2135 | 2135 | When the user enters the EOF key sequence, EOFError is raised. |
|
2136 | 2136 | |
|
2137 | 2137 | Optional inputs: |
|
2138 | 2138 | |
|
2139 | 2139 | - prompt(''): a string to be printed to prompt the user. |
|
2140 | 2140 | |
|
2141 | 2141 | - continue_prompt(False): whether this line is the first one or a |
|
2142 | 2142 | continuation in a sequence of inputs. |
|
2143 | 2143 | """ |
|
2144 | 2144 | |
|
2145 | 2145 | # Code run by the user may have modified the readline completer state. |
|
2146 | 2146 | # We must ensure that our completer is back in place. |
|
2147 | 2147 | if self.has_readline: |
|
2148 | 2148 | self.set_completer() |
|
2149 | 2149 | |
|
2150 | 2150 | try: |
|
2151 | 2151 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
2152 | 2152 | except ValueError: |
|
2153 | 2153 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
2154 | 2154 | " or sys.stdout.close()!\nExiting IPython!") |
|
2155 | 2155 | self.exit_now = True |
|
2156 | 2156 | return "" |
|
2157 | 2157 | |
|
2158 | 2158 | # Try to be reasonably smart about not re-indenting pasted input more |
|
2159 | 2159 | # than necessary. We do this by trimming out the auto-indent initial |
|
2160 | 2160 | # spaces, if the user's actual input started itself with whitespace. |
|
2161 | 2161 | #debugx('self.buffer[-1]') |
|
2162 | 2162 | |
|
2163 | 2163 | if self.autoindent: |
|
2164 | 2164 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
2165 | 2165 | line = line[self.indent_current_nsp:] |
|
2166 | 2166 | self.indent_current_nsp = 0 |
|
2167 | 2167 | |
|
2168 | 2168 | # store the unfiltered input before the user has any chance to modify |
|
2169 | 2169 | # it. |
|
2170 | 2170 | if line.strip(): |
|
2171 | 2171 | if continue_prompt: |
|
2172 | 2172 | self.input_hist_raw[-1] += '%s\n' % line |
|
2173 | 2173 | if self.has_readline: # and some config option is set? |
|
2174 | 2174 | try: |
|
2175 | 2175 | histlen = self.readline.get_current_history_length() |
|
2176 | 2176 | if histlen > 1: |
|
2177 | 2177 | newhist = self.input_hist_raw[-1].rstrip() |
|
2178 | 2178 | self.readline.remove_history_item(histlen-1) |
|
2179 | 2179 | self.readline.replace_history_item(histlen-2, |
|
2180 | 2180 | newhist.encode(self.stdin_encoding)) |
|
2181 | 2181 | except AttributeError: |
|
2182 | 2182 | pass # re{move,place}_history_item are new in 2.4. |
|
2183 | 2183 | else: |
|
2184 | 2184 | self.input_hist_raw.append('%s\n' % line) |
|
2185 | 2185 | # only entries starting at first column go to shadow history |
|
2186 | 2186 | if line.lstrip() == line: |
|
2187 | 2187 | self.shadowhist.add(line.strip()) |
|
2188 | 2188 | elif not continue_prompt: |
|
2189 | 2189 | self.input_hist_raw.append('\n') |
|
2190 | 2190 | try: |
|
2191 | 2191 | lineout = self.prefilter(line,continue_prompt) |
|
2192 | 2192 | except: |
|
2193 | 2193 | # blanket except, in case a user-defined prefilter crashes, so it |
|
2194 | 2194 | # can't take all of ipython with it. |
|
2195 | 2195 | self.showtraceback() |
|
2196 | 2196 | return '' |
|
2197 | 2197 | else: |
|
2198 | 2198 | return lineout |
|
2199 | 2199 | |
|
2200 | 2200 | def _prefilter(self, line, continue_prompt): |
|
2201 | 2201 | """Calls different preprocessors, depending on the form of line.""" |
|
2202 | 2202 | |
|
2203 | 2203 | # All handlers *must* return a value, even if it's blank (''). |
|
2204 | 2204 | |
|
2205 | 2205 | # Lines are NOT logged here. Handlers should process the line as |
|
2206 | 2206 | # needed, update the cache AND log it (so that the input cache array |
|
2207 | 2207 | # stays synced). |
|
2208 | 2208 | |
|
2209 | 2209 | #..................................................................... |
|
2210 | 2210 | # Code begins |
|
2211 | 2211 | |
|
2212 | 2212 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg |
|
2213 | 2213 | |
|
2214 | 2214 | # save the line away in case we crash, so the post-mortem handler can |
|
2215 | 2215 | # record it |
|
2216 | 2216 | self._last_input_line = line |
|
2217 | 2217 | |
|
2218 | 2218 | #print '***line: <%s>' % line # dbg |
|
2219 | 2219 | |
|
2220 | 2220 | if not line: |
|
2221 | 2221 | # Return immediately on purely empty lines, so that if the user |
|
2222 | 2222 | # previously typed some whitespace that started a continuation |
|
2223 | 2223 | # prompt, he can break out of that loop with just an empty line. |
|
2224 | 2224 | # This is how the default python prompt works. |
|
2225 | 2225 | |
|
2226 | 2226 | # Only return if the accumulated input buffer was just whitespace! |
|
2227 | 2227 | if ''.join(self.buffer).isspace(): |
|
2228 | 2228 | self.buffer[:] = [] |
|
2229 | 2229 | return '' |
|
2230 | 2230 | |
|
2231 | 2231 | line_info = prefilter.LineInfo(line, continue_prompt) |
|
2232 | 2232 | |
|
2233 | 2233 | # the input history needs to track even empty lines |
|
2234 | 2234 | stripped = line.strip() |
|
2235 | 2235 | |
|
2236 | 2236 | if not stripped: |
|
2237 | 2237 | if not continue_prompt: |
|
2238 | 2238 | self.outputcache.prompt_count -= 1 |
|
2239 | 2239 | return self.handle_normal(line_info) |
|
2240 | 2240 | |
|
2241 | 2241 | # print '***cont',continue_prompt # dbg |
|
2242 | 2242 | # special handlers are only allowed for single line statements |
|
2243 | 2243 | if continue_prompt and not self.rc.multi_line_specials: |
|
2244 | 2244 | return self.handle_normal(line_info) |
|
2245 | 2245 | |
|
2246 | 2246 | |
|
2247 | 2247 | # See whether any pre-existing handler can take care of it |
|
2248 | 2248 | rewritten = self.hooks.input_prefilter(stripped) |
|
2249 | 2249 | if rewritten != stripped: # ok, some prefilter did something |
|
2250 | 2250 | rewritten = line_info.pre + rewritten # add indentation |
|
2251 | 2251 | return self.handle_normal(prefilter.LineInfo(rewritten, |
|
2252 | 2252 | continue_prompt)) |
|
2253 | 2253 | |
|
2254 | 2254 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2255 | 2255 | |
|
2256 | 2256 | return prefilter.prefilter(line_info, self) |
|
2257 | 2257 | |
|
2258 | 2258 | |
|
2259 | 2259 | def _prefilter_dumb(self, line, continue_prompt): |
|
2260 | 2260 | """simple prefilter function, for debugging""" |
|
2261 | 2261 | return self.handle_normal(line,continue_prompt) |
|
2262 | 2262 | |
|
2263 | 2263 | |
|
2264 | 2264 | def multiline_prefilter(self, line, continue_prompt): |
|
2265 | 2265 | """ Run _prefilter for each line of input |
|
2266 | 2266 | |
|
2267 | 2267 | Covers cases where there are multiple lines in the user entry, |
|
2268 | 2268 | which is the case when the user goes back to a multiline history |
|
2269 | 2269 | entry and presses enter. |
|
2270 | 2270 | |
|
2271 | 2271 | """ |
|
2272 | 2272 | out = [] |
|
2273 | 2273 | for l in line.rstrip('\n').split('\n'): |
|
2274 | 2274 | out.append(self._prefilter(l, continue_prompt)) |
|
2275 | 2275 | return '\n'.join(out) |
|
2276 | 2276 | |
|
2277 | 2277 | # Set the default prefilter() function (this can be user-overridden) |
|
2278 | 2278 | prefilter = multiline_prefilter |
|
2279 | 2279 | |
|
2280 | 2280 | def handle_normal(self,line_info): |
|
2281 | 2281 | """Handle normal input lines. Use as a template for handlers.""" |
|
2282 | 2282 | |
|
2283 | 2283 | # With autoindent on, we need some way to exit the input loop, and I |
|
2284 | 2284 | # don't want to force the user to have to backspace all the way to |
|
2285 | 2285 | # clear the line. The rule will be in this case, that either two |
|
2286 | 2286 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
2287 | 2287 | # of a size different to the indent level, will exit the input loop. |
|
2288 | 2288 | line = line_info.line |
|
2289 | 2289 | continue_prompt = line_info.continue_prompt |
|
2290 | 2290 | |
|
2291 | 2291 | if (continue_prompt and self.autoindent and line.isspace() and |
|
2292 | 2292 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or |
|
2293 | 2293 | (self.buffer[-1]).isspace() )): |
|
2294 | 2294 | line = '' |
|
2295 | 2295 | |
|
2296 | 2296 | self.log(line,line,continue_prompt) |
|
2297 | 2297 | return line |
|
2298 | 2298 | |
|
2299 | 2299 | def handle_alias(self,line_info): |
|
2300 | 2300 | """Handle alias input lines. """ |
|
2301 | 2301 | tgt = self.alias_table[line_info.iFun] |
|
2302 | 2302 | # print "=>",tgt #dbg |
|
2303 | 2303 | if callable(tgt): |
|
2304 | 2304 | if '$' in line_info.line: |
|
2305 | 2305 | call_meth = '(_ip, _ip.itpl(%s))' |
|
2306 | 2306 | else: |
|
2307 | 2307 | call_meth = '(_ip,%s)' |
|
2308 | 2308 | line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace, |
|
2309 | 2309 | line_info.iFun, |
|
2310 | 2310 | make_quoted_expr(line_info.line)) |
|
2311 | 2311 | else: |
|
2312 | 2312 | transformed = self.expand_aliases(line_info.iFun,line_info.theRest) |
|
2313 | 2313 | |
|
2314 | 2314 | # pre is needed, because it carries the leading whitespace. Otherwise |
|
2315 | 2315 | # aliases won't work in indented sections. |
|
2316 | 2316 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2317 | 2317 | make_quoted_expr( transformed )) |
|
2318 | 2318 | |
|
2319 | 2319 | self.log(line_info.line,line_out,line_info.continue_prompt) |
|
2320 | 2320 | #print 'line out:',line_out # dbg |
|
2321 | 2321 | return line_out |
|
2322 | 2322 | |
|
2323 | 2323 | def handle_shell_escape(self, line_info): |
|
2324 | 2324 | """Execute the line in a shell, empty return value""" |
|
2325 | 2325 | #print 'line in :', `line` # dbg |
|
2326 | 2326 | line = line_info.line |
|
2327 | 2327 | if line.lstrip().startswith('!!'): |
|
2328 | 2328 | # rewrite LineInfo's line, iFun and theRest to properly hold the |
|
2329 | 2329 | # call to %sx and the actual command to be executed, so |
|
2330 | 2330 | # handle_magic can work correctly. Note that this works even if |
|
2331 | 2331 | # the line is indented, so it handles multi_line_specials |
|
2332 | 2332 | # properly. |
|
2333 | 2333 | new_rest = line.lstrip()[2:] |
|
2334 | 2334 | line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest) |
|
2335 | 2335 | line_info.iFun = 'sx' |
|
2336 | 2336 | line_info.theRest = new_rest |
|
2337 | 2337 | return self.handle_magic(line_info) |
|
2338 | 2338 | else: |
|
2339 | 2339 | cmd = line.lstrip().lstrip('!') |
|
2340 | 2340 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2341 | 2341 | make_quoted_expr(cmd)) |
|
2342 | 2342 | # update cache/log and return |
|
2343 | 2343 | self.log(line,line_out,line_info.continue_prompt) |
|
2344 | 2344 | return line_out |
|
2345 | 2345 | |
|
2346 | 2346 | def handle_magic(self, line_info): |
|
2347 | 2347 | """Execute magic functions.""" |
|
2348 | 2348 | iFun = line_info.iFun |
|
2349 | 2349 | theRest = line_info.theRest |
|
2350 | 2350 | cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace, |
|
2351 | 2351 | make_quoted_expr(iFun + " " + theRest)) |
|
2352 | 2352 | self.log(line_info.line,cmd,line_info.continue_prompt) |
|
2353 | 2353 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg |
|
2354 | 2354 | return cmd |
|
2355 | 2355 | |
|
2356 | 2356 | def handle_auto(self, line_info): |
|
2357 | 2357 | """Hande lines which can be auto-executed, quoting if requested.""" |
|
2358 | 2358 | |
|
2359 | 2359 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2360 | 2360 | line = line_info.line |
|
2361 | 2361 | iFun = line_info.iFun |
|
2362 | 2362 | theRest = line_info.theRest |
|
2363 | 2363 | pre = line_info.pre |
|
2364 | 2364 | continue_prompt = line_info.continue_prompt |
|
2365 | 2365 | obj = line_info.ofind(self)['obj'] |
|
2366 | 2366 | |
|
2367 | 2367 | # This should only be active for single-line input! |
|
2368 | 2368 | if continue_prompt: |
|
2369 | 2369 | self.log(line,line,continue_prompt) |
|
2370 | 2370 | return line |
|
2371 | 2371 | |
|
2372 | 2372 | force_auto = isinstance(obj, IPython.ipapi.IPyAutocall) |
|
2373 | 2373 | auto_rewrite = True |
|
2374 | 2374 | |
|
2375 | 2375 | if pre == self.ESC_QUOTE: |
|
2376 | 2376 | # Auto-quote splitting on whitespace |
|
2377 | 2377 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) |
|
2378 | 2378 | elif pre == self.ESC_QUOTE2: |
|
2379 | 2379 | # Auto-quote whole string |
|
2380 | 2380 | newcmd = '%s("%s")' % (iFun,theRest) |
|
2381 | 2381 | elif pre == self.ESC_PAREN: |
|
2382 | 2382 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) |
|
2383 | 2383 | else: |
|
2384 | 2384 | # Auto-paren. |
|
2385 | 2385 | # We only apply it to argument-less calls if the autocall |
|
2386 | 2386 | # parameter is set to 2. We only need to check that autocall is < |
|
2387 | 2387 | # 2, since this function isn't called unless it's at least 1. |
|
2388 | 2388 | if not theRest and (self.rc.autocall < 2) and not force_auto: |
|
2389 | 2389 | newcmd = '%s %s' % (iFun,theRest) |
|
2390 | 2390 | auto_rewrite = False |
|
2391 | 2391 | else: |
|
2392 | 2392 | if not force_auto and theRest.startswith('['): |
|
2393 | 2393 | if hasattr(obj,'__getitem__'): |
|
2394 | 2394 | # Don't autocall in this case: item access for an object |
|
2395 | 2395 | # which is BOTH callable and implements __getitem__. |
|
2396 | 2396 | newcmd = '%s %s' % (iFun,theRest) |
|
2397 | 2397 | auto_rewrite = False |
|
2398 | 2398 | else: |
|
2399 | 2399 | # if the object doesn't support [] access, go ahead and |
|
2400 | 2400 | # autocall |
|
2401 | 2401 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) |
|
2402 | 2402 | elif theRest.endswith(';'): |
|
2403 | 2403 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) |
|
2404 | 2404 | else: |
|
2405 | 2405 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) |
|
2406 | 2406 | |
|
2407 | 2407 | if auto_rewrite: |
|
2408 | 2408 | rw = self.outputcache.prompt1.auto_rewrite() + newcmd |
|
2409 | 2409 | |
|
2410 | 2410 | try: |
|
2411 | 2411 | # plain ascii works better w/ pyreadline, on some machines, so |
|
2412 | 2412 | # we use it and only print uncolored rewrite if we have unicode |
|
2413 | 2413 | rw = str(rw) |
|
2414 | 2414 | print >>Term.cout, rw |
|
2415 | 2415 | except UnicodeEncodeError: |
|
2416 | 2416 | print "-------------->" + newcmd |
|
2417 | 2417 | |
|
2418 | 2418 | # log what is now valid Python, not the actual user input (without the |
|
2419 | 2419 | # final newline) |
|
2420 | 2420 | self.log(line,newcmd,continue_prompt) |
|
2421 | 2421 | return newcmd |
|
2422 | 2422 | |
|
2423 | 2423 | def handle_help(self, line_info): |
|
2424 | 2424 | """Try to get some help for the object. |
|
2425 | 2425 | |
|
2426 | 2426 | obj? or ?obj -> basic information. |
|
2427 | 2427 | obj?? or ??obj -> more details. |
|
2428 | 2428 | """ |
|
2429 | 2429 | |
|
2430 | 2430 | line = line_info.line |
|
2431 | 2431 | # We need to make sure that we don't process lines which would be |
|
2432 | 2432 | # otherwise valid python, such as "x=1 # what?" |
|
2433 | 2433 | try: |
|
2434 | 2434 | codeop.compile_command(line) |
|
2435 | 2435 | except SyntaxError: |
|
2436 | 2436 | # We should only handle as help stuff which is NOT valid syntax |
|
2437 | 2437 | if line[0]==self.ESC_HELP: |
|
2438 | 2438 | line = line[1:] |
|
2439 | 2439 | elif line[-1]==self.ESC_HELP: |
|
2440 | 2440 | line = line[:-1] |
|
2441 | 2441 | self.log(line,'#?'+line,line_info.continue_prompt) |
|
2442 | 2442 | if line: |
|
2443 | 2443 | #print 'line:<%r>' % line # dbg |
|
2444 | 2444 | self.magic_pinfo(line) |
|
2445 | 2445 | else: |
|
2446 | 2446 | page(self.usage,screen_lines=self.rc.screen_length) |
|
2447 | 2447 | return '' # Empty string is needed here! |
|
2448 | 2448 | except: |
|
2449 | 2449 | # Pass any other exceptions through to the normal handler |
|
2450 | 2450 | return self.handle_normal(line_info) |
|
2451 | 2451 | else: |
|
2452 | 2452 | # If the code compiles ok, we should handle it normally |
|
2453 | 2453 | return self.handle_normal(line_info) |
|
2454 | 2454 | |
|
2455 | 2455 | def getapi(self): |
|
2456 | 2456 | """ Get an IPApi object for this shell instance |
|
2457 | 2457 | |
|
2458 | 2458 | Getting an IPApi object is always preferable to accessing the shell |
|
2459 | 2459 | directly, but this holds true especially for extensions. |
|
2460 | 2460 | |
|
2461 | 2461 | It should always be possible to implement an extension with IPApi |
|
2462 | 2462 | alone. If not, contact maintainer to request an addition. |
|
2463 | 2463 | |
|
2464 | 2464 | """ |
|
2465 | 2465 | return self.api |
|
2466 | 2466 | |
|
2467 | 2467 | def handle_emacs(self, line_info): |
|
2468 | 2468 | """Handle input lines marked by python-mode.""" |
|
2469 | 2469 | |
|
2470 | 2470 | # Currently, nothing is done. Later more functionality can be added |
|
2471 | 2471 | # here if needed. |
|
2472 | 2472 | |
|
2473 | 2473 | # The input cache shouldn't be updated |
|
2474 | 2474 | return line_info.line |
|
2475 | 2475 | |
|
2476 | 2476 | |
|
2477 | 2477 | def mktempfile(self,data=None): |
|
2478 | 2478 | """Make a new tempfile and return its filename. |
|
2479 | 2479 | |
|
2480 | 2480 | This makes a call to tempfile.mktemp, but it registers the created |
|
2481 | 2481 | filename internally so ipython cleans it up at exit time. |
|
2482 | 2482 | |
|
2483 | 2483 | Optional inputs: |
|
2484 | 2484 | |
|
2485 | 2485 | - data(None): if data is given, it gets written out to the temp file |
|
2486 | 2486 | immediately, and the file is closed again.""" |
|
2487 | 2487 | |
|
2488 | 2488 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2489 | 2489 | self.tempfiles.append(filename) |
|
2490 | 2490 | |
|
2491 | 2491 | if data: |
|
2492 | 2492 | tmp_file = open(filename,'w') |
|
2493 | 2493 | tmp_file.write(data) |
|
2494 | 2494 | tmp_file.close() |
|
2495 | 2495 | return filename |
|
2496 | 2496 | |
|
2497 | 2497 | def write(self,data): |
|
2498 | 2498 | """Write a string to the default output""" |
|
2499 | 2499 | Term.cout.write(data) |
|
2500 | 2500 | |
|
2501 | 2501 | def write_err(self,data): |
|
2502 | 2502 | """Write a string to the default error output""" |
|
2503 | 2503 | Term.cerr.write(data) |
|
2504 | 2504 | |
|
2505 | 2505 | def exit(self): |
|
2506 | 2506 | """Handle interactive exit. |
|
2507 | 2507 | |
|
2508 | 2508 | This method sets the exit_now attribute.""" |
|
2509 | 2509 | |
|
2510 | 2510 | if self.rc.confirm_exit: |
|
2511 | 2511 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
2512 | 2512 | self.exit_now = True |
|
2513 | 2513 | else: |
|
2514 | 2514 | self.exit_now = True |
|
2515 | 2515 | |
|
2516 | 2516 | def safe_execfile(self,fname,*where,**kw): |
|
2517 | 2517 | """A safe version of the builtin execfile(). |
|
2518 | 2518 | |
|
2519 | 2519 | This version will never throw an exception, and knows how to handle |
|
2520 | 2520 | ipython logs as well. |
|
2521 | 2521 | |
|
2522 | 2522 | :Parameters: |
|
2523 | 2523 | fname : string |
|
2524 | 2524 | Name of the file to be executed. |
|
2525 | 2525 | |
|
2526 | 2526 | where : tuple |
|
2527 | 2527 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2528 | 2528 | If only one is given, it is passed as both. |
|
2529 | 2529 | |
|
2530 | 2530 | :Keywords: |
|
2531 | 2531 | islog : boolean (False) |
|
2532 | 2532 | |
|
2533 | 2533 | quiet : boolean (True) |
|
2534 | 2534 | |
|
2535 | 2535 | exit_ignore : boolean (False) |
|
2536 | 2536 | """ |
|
2537 | 2537 | |
|
2538 | 2538 | def syspath_cleanup(): |
|
2539 | 2539 | """Internal cleanup routine for sys.path.""" |
|
2540 | 2540 | if add_dname: |
|
2541 | 2541 | try: |
|
2542 | 2542 | sys.path.remove(dname) |
|
2543 | 2543 | except ValueError: |
|
2544 | 2544 | # For some reason the user has already removed it, ignore. |
|
2545 | 2545 | pass |
|
2546 | 2546 | |
|
2547 | 2547 | fname = os.path.expanduser(fname) |
|
2548 | 2548 | |
|
2549 | 2549 | # Find things also in current directory. This is needed to mimic the |
|
2550 | 2550 | # behavior of running a script from the system command line, where |
|
2551 | 2551 | # Python inserts the script's directory into sys.path |
|
2552 | 2552 | dname = os.path.dirname(os.path.abspath(fname)) |
|
2553 | 2553 | add_dname = False |
|
2554 | 2554 | if dname not in sys.path: |
|
2555 | 2555 | sys.path.insert(0,dname) |
|
2556 | 2556 | add_dname = True |
|
2557 | 2557 | |
|
2558 | 2558 | try: |
|
2559 | 2559 | xfile = open(fname) |
|
2560 | 2560 | except: |
|
2561 | 2561 | print >> Term.cerr, \ |
|
2562 | 2562 | 'Could not open file <%s> for safe execution.' % fname |
|
2563 | 2563 | syspath_cleanup() |
|
2564 | 2564 | return None |
|
2565 | 2565 | |
|
2566 | 2566 | kw.setdefault('islog',0) |
|
2567 | 2567 | kw.setdefault('quiet',1) |
|
2568 | 2568 | kw.setdefault('exit_ignore',0) |
|
2569 | 2569 | |
|
2570 | 2570 | first = xfile.readline() |
|
2571 | 2571 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() |
|
2572 | 2572 | xfile.close() |
|
2573 | 2573 | # line by line execution |
|
2574 | 2574 | if first.startswith(loghead) or kw['islog']: |
|
2575 | 2575 | print 'Loading log file <%s> one line at a time...' % fname |
|
2576 | 2576 | if kw['quiet']: |
|
2577 | 2577 | stdout_save = sys.stdout |
|
2578 | 2578 | sys.stdout = StringIO.StringIO() |
|
2579 | 2579 | try: |
|
2580 | 2580 | globs,locs = where[0:2] |
|
2581 | 2581 | except: |
|
2582 | 2582 | try: |
|
2583 | 2583 | globs = locs = where[0] |
|
2584 | 2584 | except: |
|
2585 | 2585 | globs = locs = globals() |
|
2586 | 2586 | badblocks = [] |
|
2587 | 2587 | |
|
2588 | 2588 | # we also need to identify indented blocks of code when replaying |
|
2589 | 2589 | # logs and put them together before passing them to an exec |
|
2590 | 2590 | # statement. This takes a bit of regexp and look-ahead work in the |
|
2591 | 2591 | # file. It's easiest if we swallow the whole thing in memory |
|
2592 | 2592 | # first, and manually walk through the lines list moving the |
|
2593 | 2593 | # counter ourselves. |
|
2594 | 2594 | indent_re = re.compile('\s+\S') |
|
2595 | 2595 | xfile = open(fname) |
|
2596 | 2596 | filelines = xfile.readlines() |
|
2597 | 2597 | xfile.close() |
|
2598 | 2598 | nlines = len(filelines) |
|
2599 | 2599 | lnum = 0 |
|
2600 | 2600 | while lnum < nlines: |
|
2601 | 2601 | line = filelines[lnum] |
|
2602 | 2602 | lnum += 1 |
|
2603 | 2603 | # don't re-insert logger status info into cache |
|
2604 | 2604 | if line.startswith('#log#'): |
|
2605 | 2605 | continue |
|
2606 | 2606 | else: |
|
2607 | 2607 | # build a block of code (maybe a single line) for execution |
|
2608 | 2608 | block = line |
|
2609 | 2609 | try: |
|
2610 | 2610 | next = filelines[lnum] # lnum has already incremented |
|
2611 | 2611 | except: |
|
2612 | 2612 | next = None |
|
2613 | 2613 | while next and indent_re.match(next): |
|
2614 | 2614 | block += next |
|
2615 | 2615 | lnum += 1 |
|
2616 | 2616 | try: |
|
2617 | 2617 | next = filelines[lnum] |
|
2618 | 2618 | except: |
|
2619 | 2619 | next = None |
|
2620 | 2620 | # now execute the block of one or more lines |
|
2621 | 2621 | try: |
|
2622 | 2622 | exec block in globs,locs |
|
2623 | 2623 | except SystemExit: |
|
2624 | 2624 | pass |
|
2625 | 2625 | except: |
|
2626 | 2626 | badblocks.append(block.rstrip()) |
|
2627 | 2627 | if kw['quiet']: # restore stdout |
|
2628 | 2628 | sys.stdout.close() |
|
2629 | 2629 | sys.stdout = stdout_save |
|
2630 | 2630 | print 'Finished replaying log file <%s>' % fname |
|
2631 | 2631 | if badblocks: |
|
2632 | 2632 | print >> sys.stderr, ('\nThe following lines/blocks in file ' |
|
2633 | 2633 | '<%s> reported errors:' % fname) |
|
2634 | 2634 | |
|
2635 | 2635 | for badline in badblocks: |
|
2636 | 2636 | print >> sys.stderr, badline |
|
2637 | 2637 | else: # regular file execution |
|
2638 | 2638 | try: |
|
2639 | 2639 | if sys.platform == 'win32' and sys.version_info < (2,5,1): |
|
2640 | 2640 | # Work around a bug in Python for Windows. The bug was |
|
2641 | 2641 | # fixed in in Python 2.5 r54159 and 54158, but that's still |
|
2642 | 2642 | # SVN Python as of March/07. For details, see: |
|
2643 | 2643 | # http://projects.scipy.org/ipython/ipython/ticket/123 |
|
2644 | 2644 | try: |
|
2645 | 2645 | globs,locs = where[0:2] |
|
2646 | 2646 | except: |
|
2647 | 2647 | try: |
|
2648 | 2648 | globs = locs = where[0] |
|
2649 | 2649 | except: |
|
2650 | 2650 | globs = locs = globals() |
|
2651 | 2651 | exec file(fname) in globs,locs |
|
2652 | 2652 | else: |
|
2653 | 2653 | execfile(fname,*where) |
|
2654 | 2654 | except SyntaxError: |
|
2655 | 2655 | self.showsyntaxerror() |
|
2656 | 2656 | warn('Failure executing file: <%s>' % fname) |
|
2657 | 2657 | except SystemExit,status: |
|
2658 | 2658 | # Code that correctly sets the exit status flag to success (0) |
|
2659 | 2659 | # shouldn't be bothered with a traceback. Note that a plain |
|
2660 | 2660 | # sys.exit() does NOT set the message to 0 (it's empty) so that |
|
2661 | 2661 | # will still get a traceback. Note that the structure of the |
|
2662 | 2662 | # SystemExit exception changed between Python 2.4 and 2.5, so |
|
2663 | 2663 | # the checks must be done in a version-dependent way. |
|
2664 | 2664 | show = False |
|
2665 | 2665 | |
|
2666 | 2666 | if sys.version_info[:2] > (2,5): |
|
2667 | 2667 | if status.message!=0 and not kw['exit_ignore']: |
|
2668 | 2668 | show = True |
|
2669 | 2669 | else: |
|
2670 | 2670 | if status.code and not kw['exit_ignore']: |
|
2671 | 2671 | show = True |
|
2672 | 2672 | if show: |
|
2673 | 2673 | self.showtraceback() |
|
2674 | 2674 | warn('Failure executing file: <%s>' % fname) |
|
2675 | 2675 | except: |
|
2676 | 2676 | self.showtraceback() |
|
2677 | 2677 | warn('Failure executing file: <%s>' % fname) |
|
2678 | 2678 | |
|
2679 | 2679 | syspath_cleanup() |
|
2680 | 2680 | |
|
2681 | 2681 | #************************* end of file <iplib.py> ***************************** |
@@ -1,278 +1,278 b'' | |||
|
1 | 1 | import sys |
|
2 | 2 | |
|
3 | 3 | from twisted.internet import reactor, threads |
|
4 | 4 | |
|
5 | 5 | from IPython.ipmaker import make_IPython |
|
6 | 6 | from IPython.iplib import InteractiveShell |
|
7 | 7 | from IPython.ipstruct import Struct |
|
8 | 8 | import Queue,thread,threading,signal |
|
9 | 9 | from signal import signal, SIGINT |
|
10 | 10 | from IPython.genutils import Term,warn,error,flag_calls, ask_yes_no |
|
11 | 11 | import shellglobals |
|
12 | 12 | |
|
13 | 13 | def install_gtk2(): |
|
14 | 14 | """ Install gtk2 reactor, needs to be called bef """ |
|
15 | 15 | from twisted.internet import gtk2reactor |
|
16 | 16 | gtk2reactor.install() |
|
17 | 17 | |
|
18 | 18 | |
|
19 | 19 | def hijack_reactor(): |
|
20 | 20 | """Modifies Twisted's reactor with a dummy so user code does |
|
21 | 21 | not block IPython. This function returns the original |
|
22 | 22 | 'twisted.internet.reactor' that has been hijacked. |
|
23 | 23 | |
|
24 | 24 | NOTE: Make sure you call this *AFTER* you've installed |
|
25 | 25 | the reactor of your choice. |
|
26 | 26 | """ |
|
27 | 27 | from twisted import internet |
|
28 | 28 | orig_reactor = internet.reactor |
|
29 | 29 | |
|
30 | 30 | class DummyReactor(object): |
|
31 | 31 | def run(self): |
|
32 | 32 | pass |
|
33 | 33 | def __getattr__(self, name): |
|
34 | 34 | return getattr(orig_reactor, name) |
|
35 | 35 | def __setattr__(self, name, value): |
|
36 | 36 | return setattr(orig_reactor, name, value) |
|
37 | 37 | |
|
38 | 38 | internet.reactor = DummyReactor() |
|
39 | 39 | return orig_reactor |
|
40 | 40 | |
|
41 | 41 | class TwistedInteractiveShell(InteractiveShell): |
|
42 | 42 | """Simple multi-threaded shell.""" |
|
43 | 43 | |
|
44 | 44 | # Threading strategy taken from: |
|
45 | 45 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian |
|
46 | 46 | # McErlean and John Finlay. Modified with corrections by Antoon Pardon, |
|
47 | 47 | # from the pygtk mailing list, to avoid lockups with system calls. |
|
48 | 48 | |
|
49 | 49 | # class attribute to indicate whether the class supports threads or not. |
|
50 | 50 | # Subclasses with thread support should override this as needed. |
|
51 | 51 | isthreaded = True |
|
52 | 52 | |
|
53 | 53 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
54 | 54 | user_ns=None,user_global_ns=None,banner2='',**kw): |
|
55 | 55 | """Similar to the normal InteractiveShell, but with threading control""" |
|
56 | 56 | |
|
57 | 57 | InteractiveShell.__init__(self,name,usage,rc,user_ns, |
|
58 | 58 | user_global_ns,banner2) |
|
59 | 59 | |
|
60 | 60 | |
|
61 | 61 | # A queue to hold the code to be executed. |
|
62 | 62 | self.code_queue = Queue.Queue() |
|
63 | 63 | |
|
64 | 64 | # Stuff to do at closing time |
|
65 | 65 | self._kill = None |
|
66 | 66 | on_kill = kw.get('on_kill', []) |
|
67 | 67 | # Check that all things to kill are callable: |
|
68 | 68 | for t in on_kill: |
|
69 | 69 | if not callable(t): |
|
70 | 70 | raise TypeError,'on_kill must be a list of callables' |
|
71 | 71 | self.on_kill = on_kill |
|
72 | 72 | # thread identity of the "worker thread" (that may execute code directly) |
|
73 | 73 | self.worker_ident = None |
|
74 | 74 | self.reactor_started = False |
|
75 | 75 | self.first_run = True |
|
76 | 76 | |
|
77 | 77 | def runsource(self, source, filename="<input>", symbol="single"): |
|
78 | 78 | """Compile and run some source in the interpreter. |
|
79 | 79 | |
|
80 | 80 | Modified version of code.py's runsource(), to handle threading issues. |
|
81 | 81 | See the original for full docstring details.""" |
|
82 | 82 | |
|
83 | 83 | # If Ctrl-C was typed, we reset the flag and return right away |
|
84 | 84 | if shellglobals.KBINT: |
|
85 | 85 | shellglobals.KBINT = False |
|
86 | 86 | return False |
|
87 | 87 | |
|
88 | 88 | if self._kill: |
|
89 | 89 | # can't queue new code if we are being killed |
|
90 | 90 | return True |
|
91 | 91 | |
|
92 | 92 | try: |
|
93 | 93 | code = self.compile(source, filename, symbol) |
|
94 | 94 | except (OverflowError, SyntaxError, ValueError): |
|
95 | 95 | # Case 1 |
|
96 | 96 | self.showsyntaxerror(filename) |
|
97 | 97 | return False |
|
98 | 98 | |
|
99 | 99 | if code is None: |
|
100 | 100 | # Case 2 |
|
101 | 101 | return True |
|
102 | 102 | |
|
103 | 103 | # shortcut - if we are in worker thread, or the worker thread is not running, |
|
104 | 104 | # execute directly (to allow recursion and prevent deadlock if code is run early |
|
105 | 105 | # in IPython construction) |
|
106 | 106 | |
|
107 | 107 | if (not self.reactor_started or (self.worker_ident is None and not self.first_run) |
|
108 | 108 | or self.worker_ident == thread.get_ident() or shellglobals.run_in_frontend(source)): |
|
109 | 109 | InteractiveShell.runcode(self,code) |
|
110 | 110 | return |
|
111 | 111 | |
|
112 | 112 | # Case 3 |
|
113 | 113 | # Store code in queue, so the execution thread can handle it. |
|
114 | 114 | |
|
115 | 115 | self.first_run = False |
|
116 | 116 | completed_ev, received_ev = threading.Event(), threading.Event() |
|
117 | 117 | |
|
118 | 118 | self.code_queue.put((code,completed_ev, received_ev)) |
|
119 | 119 | |
|
120 | 120 | reactor.callLater(0.0,self.runcode) |
|
121 | 121 | received_ev.wait(5) |
|
122 | 122 | if not received_ev.isSet(): |
|
123 | 123 | # the mainloop is dead, start executing code directly |
|
124 | 124 | print "Warning: Timeout for mainloop thread exceeded" |
|
125 | 125 | print "switching to nonthreaded mode (until mainloop wakes up again)" |
|
126 | 126 | self.worker_ident = None |
|
127 | 127 | else: |
|
128 | 128 | completed_ev.wait() |
|
129 | 129 | |
|
130 | 130 | return False |
|
131 | 131 | |
|
132 | 132 | def runcode(self): |
|
133 | 133 | """Execute a code object. |
|
134 | 134 | |
|
135 | 135 | Multithreaded wrapper around IPython's runcode().""" |
|
136 | 136 | |
|
137 | 137 | |
|
138 | 138 | # we are in worker thread, stash out the id for runsource() |
|
139 | 139 | self.worker_ident = thread.get_ident() |
|
140 | 140 | |
|
141 | 141 | if self._kill: |
|
142 | 142 | print >>Term.cout, 'Closing threads...', |
|
143 | 143 | Term.cout.flush() |
|
144 | 144 | for tokill in self.on_kill: |
|
145 | 145 | tokill() |
|
146 | 146 | print >>Term.cout, 'Done.' |
|
147 | 147 | # allow kill() to return |
|
148 | 148 | self._kill.set() |
|
149 | 149 | return True |
|
150 | 150 | |
|
151 | 151 | # Install SIGINT handler. We do it every time to ensure that if user |
|
152 | 152 | # code modifies it, we restore our own handling. |
|
153 | 153 | try: |
|
154 | 154 | pass |
|
155 | 155 | signal(SIGINT,shellglobals.sigint_handler) |
|
156 | 156 | except SystemError: |
|
157 | 157 | # This happens under Windows, which seems to have all sorts |
|
158 | 158 | # of problems with signal handling. Oh well... |
|
159 | 159 | pass |
|
160 | 160 | |
|
161 | 161 | # Flush queue of pending code by calling the run methood of the parent |
|
162 | 162 | # class with all items which may be in the queue. |
|
163 | 163 | code_to_run = None |
|
164 | 164 | while 1: |
|
165 | 165 | try: |
|
166 | 166 | code_to_run, completed_ev, received_ev = self.code_queue.get_nowait() |
|
167 | 167 | except Queue.Empty: |
|
168 | 168 | break |
|
169 | 169 | received_ev.set() |
|
170 | 170 | |
|
171 | 171 | |
|
172 | 172 | # Exceptions need to be raised differently depending on which |
|
173 | 173 | # thread is active. This convoluted try/except is only there to |
|
174 | 174 | # protect against asynchronous exceptions, to ensure that a shellglobals.KBINT |
|
175 | 175 | # at the wrong time doesn't deadlock everything. The global |
|
176 | 176 | # CODE_TO_RUN is set to true/false as close as possible to the |
|
177 | 177 | # runcode() call, so that the KBINT handler is correctly informed. |
|
178 | 178 | try: |
|
179 | 179 | try: |
|
180 | 180 | shellglobals.CODE_RUN = True |
|
181 | 181 | InteractiveShell.runcode(self,code_to_run) |
|
182 | 182 | except KeyboardInterrupt: |
|
183 | 183 | print "Keyboard interrupted in mainloop" |
|
184 | 184 | while not self.code_queue.empty(): |
|
185 | 185 | code = self.code_queue.get_nowait() |
|
186 | 186 | break |
|
187 | 187 | finally: |
|
188 | 188 | shellglobals.CODE_RUN = False |
|
189 | 189 | # allow runsource() return from wait |
|
190 | 190 | completed_ev.set() |
|
191 | 191 | |
|
192 | 192 | # This MUST return true for gtk threading to work |
|
193 | 193 | return True |
|
194 | 194 | |
|
195 | 195 | def kill(self): |
|
196 | 196 | """Kill the thread, returning when it has been shut down.""" |
|
197 | 197 | self._kill = threading.Event() |
|
198 | 198 | reactor.callLater(0.0,self.runcode) |
|
199 | 199 | self._kill.wait() |
|
200 | 200 | |
|
201 | 201 | |
|
202 | 202 | |
|
203 |
class IPShellTwisted |
|
|
203 | class IPShellTwisted: | |
|
204 | 204 | """Run a Twisted reactor while in an IPython session. |
|
205 | 205 | |
|
206 | 206 | Python commands can be passed to the thread where they will be |
|
207 | 207 | executed. This is implemented by periodically checking for |
|
208 | 208 | passed code using a Twisted reactor callback. |
|
209 | 209 | """ |
|
210 | 210 | |
|
211 | 211 | TIMEOUT = 0.01 # Millisecond interval between reactor runs. |
|
212 | 212 | |
|
213 | 213 | def __init__(self, argv=None, user_ns=None, debug=1, |
|
214 | 214 | shell_class=TwistedInteractiveShell): |
|
215 | 215 | |
|
216 | 216 | from twisted.internet import reactor |
|
217 | 217 | self.reactor = hijack_reactor() |
|
218 | 218 | |
|
219 | 219 | mainquit = self.reactor.stop |
|
220 | 220 | |
|
221 | 221 | # Make sure IPython keeps going after reactor stop. |
|
222 | 222 | def reactorstop(): |
|
223 | 223 | pass |
|
224 | 224 | self.reactor.stop = reactorstop |
|
225 | 225 | reactorrun_orig = self.reactor.run |
|
226 | 226 | self.quitting = False |
|
227 | 227 | def reactorrun(): |
|
228 | 228 | while True and not self.quitting: |
|
229 | 229 | reactorrun_orig() |
|
230 | 230 | self.reactor.run = reactorrun |
|
231 | 231 | |
|
232 | 232 | self.IP = make_IPython(argv, user_ns=user_ns, debug=debug, |
|
233 | 233 | shell_class=shell_class, |
|
234 | 234 | on_kill=[mainquit]) |
|
235 | 235 | |
|
236 | 236 | # threading.Thread.__init__(self) |
|
237 | 237 | |
|
238 | 238 | def run(self): |
|
239 | 239 | self.IP.mainloop() |
|
240 | 240 | self.quitting = True |
|
241 | 241 | self.IP.kill() |
|
242 | 242 | |
|
243 | 243 | def mainloop(self): |
|
244 | 244 | def mainLoopThreadDeath(r): |
|
245 | 245 | print "mainLoopThreadDeath: ", str(r) |
|
246 | 246 | def spawnMainloopThread(): |
|
247 | 247 | d=threads.deferToThread(self.run) |
|
248 | 248 | d.addBoth(mainLoopThreadDeath) |
|
249 | 249 | reactor.callWhenRunning(spawnMainloopThread) |
|
250 | 250 | self.IP.reactor_started = True |
|
251 | 251 | self.reactor.run() |
|
252 | 252 | print "mainloop ending...." |
|
253 | 253 | |
|
254 | 254 | exists = True |
|
255 | 255 | |
|
256 | 256 | |
|
257 | 257 | if __name__ == '__main__': |
|
258 | 258 | # Sample usage. |
|
259 | 259 | |
|
260 | 260 | # Create the shell object. This steals twisted.internet.reactor |
|
261 | 261 | # for its own purposes, to make sure you've already installed a |
|
262 | 262 | # reactor of your choice. |
|
263 | 263 | shell = IPShellTwisted( |
|
264 | 264 | argv=[], |
|
265 | 265 | user_ns={'__name__': '__example__', |
|
266 | 266 | 'hello': 'world', |
|
267 | 267 | }, |
|
268 | 268 | ) |
|
269 | 269 | |
|
270 | 270 | # Run the mainloop. This runs the actual reactor.run() method. |
|
271 | 271 | # The twisted.internet.reactor object at this point is a dummy |
|
272 | 272 | # object that passes through to the actual reactor, but prevents |
|
273 | 273 | # run() from being called on it again. |
|
274 | 274 | shell.mainloop() |
|
275 | 275 | |
|
276 | 276 | # You must exit IPython to terminate your program. |
|
277 | 277 | print 'Goodbye!' |
|
278 | 278 |
@@ -1,70 +1,392 b'' | |||
|
1 | ipython (0.8.1-2) unstable; urgency=low | |
|
2 | ||
|
3 | [ Piotr Ożarowski ] | |
|
4 | * Homepage field added | |
|
5 | * Rename XS-Vcs-* fields to Vcs-* (dpkg supports them now) | |
|
6 | * Add 04_remove_shebang patch | |
|
7 | * Removing lintian overrides, adding proper patches instead. | |
|
8 | ||
|
9 | [ Bernd Zeimetz ] | |
|
10 | * Replacing Recommends by Suggests to stop ipython from installing ~500MB | |
|
11 | of dependencies. Thanks to Marcela Tiznado (Closes: #451887). | |
|
12 | ||
|
13 | -- Bernd Zeimetz <bernd@bzed.de> Mon, 19 Nov 2007 19:10:14 +0100 | |
|
14 | ||
|
15 | ipython (0.8.1-1) unstable; urgency=low | |
|
16 | ||
|
17 | [ Bernd Zeimetz ] | |
|
18 | * debian/control: | |
|
19 | - adding python-matplotlib to Recommends because | |
|
20 | it is needed to run ipython -pylab | |
|
21 | ||
|
22 | [ Norbert Tretkowski ] | |
|
23 | * New upstream release. (closes: #428398) | |
|
24 | ||
|
25 | [ Reinhard Tartler ] | |
|
26 | * Install ipython.el properly. | |
|
27 | ||
|
28 | -- Norbert Tretkowski <nobse@debian.org> Mon, 11 Jun 2007 20:05:30 +0200 | |
|
29 | ||
|
30 | ipython (0.8.0-2) unstable; urgency=low | |
|
31 | ||
|
32 | * debian/changelog: | |
|
33 | - adding missing colons to Closes entries to fix two | |
|
34 | lintian warnings | |
|
35 | * debian/compat: | |
|
36 | - bumping compat level to 5 | |
|
37 | * debian/control: | |
|
38 | - adding XS-Vcs-Browser | |
|
39 | - remove no longer needed X*-Python-Version fields | |
|
40 | - moving python-pexpect from Recommends to Depends because | |
|
41 | /usr/bin/irunner is not useable without it | |
|
42 | - moving debhelper and dpatch from Build-Depends-Indep to | |
|
43 | Build-Depends, fixing the following lintian errors: | |
|
44 | - clean-should-be-satisfied-by-build-depends debhelper | |
|
45 | - clean-should-be-satisfied-by-build-depends dpatch | |
|
46 | - removing unnecessary Build-Depends-Indep on python-all-dev, | |
|
47 | adding python to Build-Depends instead | |
|
48 | - replacing python-central by python-support to be able to | |
|
49 | fix #420134 without hassle | |
|
50 | - adding ${misc:Depends} | |
|
51 | - adding the missing identation for Homepage: | |
|
52 | - adding cdbs as Build-Depends | |
|
53 | - adding myself to Uploaders | |
|
54 | - removing the short description from the long description | |
|
55 | * debian/patches/03_ipy_gnuglobal.dpatch: | |
|
56 | - fix the location of the global binary - we're not on windows | |
|
57 | * debian/rules: | |
|
58 | - removing old crust, using cdbs to make things clear again | |
|
59 | - using python-support instead of python-central to make | |
|
60 | modules for 2.5 avaiable now. (Closes: #420134) | |
|
61 | - making sure the bogus /usr/IPython directory is not | |
|
62 | included in the package again | |
|
63 | - do not remove docs/ipython.el (Closes: #198505, #415427) | |
|
64 | * adding lintian ovverrides for several scripts included in the | |
|
65 | IPython/Extensions directory. | |
|
66 | * adding a manpage for /usr/bin/irunner | |
|
67 | ||
|
68 | -- Bernd Zeimetz <bernd@bzed.de> Tue, 24 Apr 2007 02:47:26 +0200 | |
|
69 | ||
|
70 | ipython (0.8.0-1) unstable; urgency=low | |
|
71 | ||
|
72 | * New upstream release. (closes: #419716) | |
|
73 | * Removed patches merged upstream. | |
|
74 | ||
|
75 | -- Norbert Tretkowski <nobse@debian.org> Tue, 17 Apr 2007 20:26:43 +0200 | |
|
76 | ||
|
77 | ipython (0.7.3-2) unstable; urgency=low | |
|
78 | ||
|
79 | * Added a new patch from svn to fix jobctrl to work properly on posix. | |
|
80 | ||
|
81 | -- Norbert Tretkowski <nobse@debian.org> Thu, 21 Dec 2006 20:13:57 +0100 | |
|
82 | ||
|
83 | ipython (0.7.3-1) unstable; urgency=low | |
|
84 | ||
|
85 | * New upstream release. | |
|
86 | ||
|
87 | -- Norbert Tretkowski <nobse@debian.org> Mon, 18 Dec 2006 22:23:55 +0100 | |
|
88 | ||
|
89 | ipython (0.7.3~rc2-1) experimental; urgency=low | |
|
90 | ||
|
91 | * New upstream release candidate. | |
|
92 | ||
|
93 | -- Norbert Tretkowski <nobse@debian.org> Sat, 16 Dec 2006 02:20:13 +0100 | |
|
94 | ||
|
95 | ipython (0.7.3~beta2-1) experimental; urgency=low | |
|
96 | ||
|
97 | * New upstream beta release. | |
|
98 | ||
|
99 | -- Norbert Tretkowski <nobse@debian.org> Fri, 8 Dec 2006 08:02:16 +0100 | |
|
100 | ||
|
101 | ipython (0.7.3~beta1-1) experimental; urgency=low | |
|
102 | ||
|
103 | * New upstream beta release. | |
|
104 | * Removed backported patch added in 0.7.2-5 to workaround bugs in python | |
|
105 | 2.3's inspect module. | |
|
106 | ||
|
107 | -- Norbert Tretkowski <nobse@debian.org> Wed, 29 Nov 2006 12:35:22 +0100 | |
|
108 | ||
|
109 | ipython (0.7.2-6) UNRELEASED; urgency=low | |
|
110 | ||
|
111 | * Added XS-Vcs-Svn field. | |
|
112 | ||
|
113 | -- Piotr Ozarowski <ozarow@gmail.com> Thu, 23 Nov 2006 14:44:43 +0100 | |
|
114 | ||
|
115 | ipython (0.7.2-5) unstable; urgency=low | |
|
116 | ||
|
117 | * Added a new patch from svn to workaround bugs in python 2.3's inspect | |
|
118 | module. (closes: #374625) | |
|
119 | ||
|
120 | -- Norbert Tretkowski <nobse@debian.org> Thu, 10 Aug 2006 18:36:12 +0200 | |
|
121 | ||
|
122 | ipython (0.7.2-4) unstable; urgency=low | |
|
123 | ||
|
124 | * Fixed spelling error in description. (closes: #363976) | |
|
125 | * Ack NMU 0.7.2-3.1, thanks Matthias. (closes: #377787) | |
|
126 | ||
|
127 | -- Norbert Tretkowski <nobse@debian.org> Tue, 1 Aug 2006 22:45:11 +0200 | |
|
128 | ||
|
129 | ipython (0.7.2-3.1) unstable; urgency=medium | |
|
130 | ||
|
131 | * NMU. | |
|
132 | * Convert to updated Python policy. (closes: #377787) | |
|
133 | ||
|
134 | -- Matthias Klose <doko@debian.org> Thu, 13 Jul 2006 17:42:06 +0000 | |
|
135 | ||
|
136 | ipython (0.7.2-3ubuntu1) edgy; urgency=low | |
|
137 | ||
|
138 | * Synchronize with Debian unstable. | |
|
139 | * Convert to updated Python policy. Collapse all packages into one | |
|
140 | ipython package, don't handle ipython using alternatives. | |
|
141 | ||
|
142 | -- Matthias Klose <doko@ubuntu.com> Tue, 11 Jul 2006 09:47:37 +0000 | |
|
143 | ||
|
144 | ipython (0.7.2-3) unstable; urgency=low | |
|
145 | ||
|
146 | * Removed alternative for irunner manpage. | |
|
147 | ||
|
148 | -- Norbert Tretkowski <nobse@debian.org> Sat, 17 Jun 2006 09:49:10 +0200 | |
|
149 | ||
|
150 | ipython (0.7.2-2) unstable; urgency=medium | |
|
151 | ||
|
152 | * Fixed conflict in irunner. (closes: #373874) | |
|
153 | * Added recommendation for python-pexpect. (closes: #373794) | |
|
154 | ||
|
155 | -- Norbert Tretkowski <nobse@debian.org> Fri, 16 Jun 2006 10:43:45 +0200 | |
|
156 | ||
|
157 | ipython (0.7.2-1) unstable; urgency=low | |
|
158 | ||
|
159 | [ Piotr Ozarowski ] | |
|
160 | * Added watch file. | |
|
161 | ||
|
162 | [ Norbert Tretkowski ] | |
|
163 | * New upstream release. | |
|
164 | ||
|
165 | -- Norbert Tretkowski <nobse@debian.org> Thu, 8 Jun 2006 23:36:03 +0200 | |
|
166 | ||
|
167 | ipython (0.7.1.fix1+0.7.2.rc1-1) experimental; urgency=low | |
|
168 | ||
|
169 | * New upstream release candidate. | |
|
170 | * Updated Standards-Version to 3.7.2.0, no changes required. | |
|
171 | ||
|
172 | -- Norbert Tretkowski <nobse@debian.org> Sat, 27 May 2006 14:49:24 +0200 | |
|
173 | ||
|
174 | ipython (0.7.1.fix1-2) unstable; urgency=low | |
|
175 | ||
|
176 | * Set maintainer to Debian Python modules team and added myself to | |
|
177 | uploaders. | |
|
178 | ||
|
179 | -- Norbert Tretkowski <nobse@debian.org> Sun, 16 Apr 2006 15:53:43 +0200 | |
|
180 | ||
|
181 | ipython (0.7.1.fix1-1) unstable; urgency=low | |
|
182 | ||
|
183 | * New upstream bugfix release. | |
|
184 | * Removed backported patch which was added in 0.7.1-3 to catch | |
|
185 | KeyboardInterrupt exceptions properly, it's part of this release. | |
|
186 | * Fixed names of pdfs in doc-base file to shut up linda. | |
|
187 | ||
|
188 | -- Norbert Tretkowski <nobse@debian.org> Tue, 14 Feb 2006 23:51:17 +0100 | |
|
189 | ||
|
190 | ipython (0.7.1-3) unstable; urgency=low | |
|
191 | ||
|
192 | * Added a new patch from upstream to catch KeyboardInterrupt exceptions | |
|
193 | properly. | |
|
194 | ||
|
195 | -- Norbert Tretkowski <nobse@debian.org> Mon, 30 Jan 2006 19:42:31 +0100 | |
|
196 | ||
|
197 | ipython (0.7.1-2) unstable; urgency=low | |
|
198 | ||
|
199 | * Really remove alternatives on purge, thanks Lars Wirzenius for finding | |
|
200 | the problem. (closes: #317269) | |
|
201 | ||
|
202 | -- Norbert Tretkowski <nobse@debian.org> Sun, 29 Jan 2006 23:11:28 +0100 | |
|
203 | ||
|
204 | ipython (0.7.1-1) unstable; urgency=low | |
|
205 | ||
|
206 | * New upstream release. | |
|
207 | ||
|
208 | -- Norbert Tretkowski <nobse@debian.org> Tue, 24 Jan 2006 21:42:33 +0100 | |
|
209 | ||
|
210 | ipython (0.7.0-2) unstable; urgency=low | |
|
211 | ||
|
212 | * Fixed circular dependencies (closes: #341980) | |
|
213 | * Added version to dependency on ipython dummy package. (closes: #320235) | |
|
214 | * Removed python2.2 package, ipython now depends on python >= 2.3. | |
|
215 | * Bumped up standards-version, no changes needed. | |
|
216 | ||
|
217 | -- Norbert Tretkowski <nobse@debian.org> Sat, 21 Jan 2006 23:27:53 +0100 | |
|
218 | ||
|
219 | ipython (0.7.0-1) unstable; urgency=low | |
|
220 | ||
|
221 | * New upstream release. | |
|
222 | * Updated 01_docdir-base.dpatch and 02_profiler-message.dpatch. | |
|
223 | ||
|
224 | -- Norbert Tretkowski <nobse@debian.org> Sat, 21 Jan 2006 20:08:23 +0100 | |
|
225 | ||
|
226 | ipython (0.6.15-2) unstable; urgency=low | |
|
227 | ||
|
228 | * New maintainer, thanks Jack for your work. | |
|
229 | ||
|
230 | -- Norbert Tretkowski <nobse@debian.org> Sun, 28 Aug 2005 19:57:09 +0200 | |
|
231 | ||
|
232 | ipython (0.6.15-1) unstable; urgency=low | |
|
233 | ||
|
234 | * New upstream release. | |
|
235 | ||
|
236 | -- Norbert Tretkowski <nobse@debian.org> Thu, 2 Jun 2005 23:51:45 +0200 | |
|
237 | ||
|
238 | ipython (0.6.14-1) unstable; urgency=low | |
|
239 | ||
|
240 | * New upstream release. | |
|
241 | ||
|
242 | -- Norbert Tretkowski <nobse@debian.org> Tue, 31 May 2005 22:53:25 +0200 | |
|
243 | ||
|
244 | ipython (0.6.13-1) unstable; urgency=low | |
|
245 | ||
|
246 | * New upstream release. | |
|
247 | * Removed backported patch which was added in 0.6.12-3 to fix misleading | |
|
248 | prompt, it's part of this release. | |
|
249 | ||
|
250 | -- Norbert Tretkowski <nobse@debian.org> Fri, 15 Apr 2005 09:42:35 +0200 | |
|
251 | ||
|
252 | ipython (0.6.12-4) unstable; urgency=medium | |
|
253 | ||
|
254 | * Re-added python build-dependency, it got lost in 0.6.12-2. | |
|
255 | (closes: #301636) | |
|
256 | ||
|
257 | -- Norbert Tretkowski <nobse@debian.org> Sun, 27 Mar 2005 14:28:26 +0200 | |
|
258 | ||
|
259 | ipython (0.6.12-3) unstable; urgency=low | |
|
260 | ||
|
261 | * Added a new patch from cvs to fix misleading prompt2. (closes: #300847) | |
|
262 | ||
|
263 | -- Norbert Tretkowski <nobse@debian.org> Sun, 27 Mar 2005 00:05:26 +0100 | |
|
264 | ||
|
265 | ipython (0.6.12-2) unstable; urgency=low | |
|
266 | ||
|
267 | * Added packages for python2.2 and python2.4, ipython package is now a dummy | |
|
268 | package depending on ipython built for Debians default python. | |
|
269 | (closes: #292537) | |
|
270 | * Split out generic files into separate ipython-common package. | |
|
271 | * Enhanced package descriptions. | |
|
272 | * Removed CFLAGS settings from debian/rules, not required. | |
|
273 | * Tweaked message displayed when profiler support is missing. | |
|
274 | * Suggest the python-profiler package. | |
|
275 | ||
|
276 | -- Norbert Tretkowski <nobse@debian.org> Fri, 25 Mar 2005 20:24:36 +0100 | |
|
277 | ||
|
278 | ipython (0.6.12-1) unstable; urgency=low | |
|
279 | ||
|
280 | * New upstream release. | |
|
281 | * Removed patch which was added in 0.6.5-1.1 to make profiling support | |
|
282 | optional, it was merged upstream. | |
|
283 | ||
|
284 | -- Norbert Tretkowski <nobse@debian.org> Wed, 2 Mar 2005 12:15:09 +0100 | |
|
285 | ||
|
286 | ipython (0.6.11-1) unstable; urgency=low | |
|
287 | ||
|
288 | * New upstream release. | |
|
289 | + Fixed broken profiling support unless -D is specified. (closes: #295779) | |
|
290 | * Acknowledged NMUs. (closes: #206653, #294500, #294861, #280505) | |
|
291 | * New co-maintainer, added myself to uploaders. | |
|
292 | ||
|
293 | -- Norbert Tretkowski <nobse@debian.org> Tue, 1 Mar 2005 12:40:33 +0100 | |
|
294 | ||
|
295 | ipython (0.6.5-1.2) unstable; urgency=low | |
|
296 | ||
|
297 | * Non-maintainer upload. | |
|
298 | * Rebuild with a python version that is actually in Debian. | |
|
299 | ||
|
300 | -- Wichert Akkerman <wichert@wiggy.net> Thu, 17 Feb 2005 23:08:52 +0100 | |
|
301 | ||
|
302 | ipython (0.6.5-1.1) unstable; urgency=low | |
|
303 | ||
|
304 | * NMU to apply patch making profiling support optional (provided by | |
|
305 | Torsten Marek). (closes: #294500) | |
|
306 | ||
|
307 | -- Steven R. Baker <srbaker@debian.org> Thu, 17 Feb 2005 05:02:55 -0400 | |
|
308 | ||
|
309 | ipython (0.6.5-1) unstable; urgency=low | |
|
310 | ||
|
311 | * New upstream release | |
|
312 | ||
|
313 | -- Jack Moffitt <jack@xiph.org> Thu, 2 Dec 2004 15:49:27 -0700 | |
|
314 | ||
|
315 | ipython (0.6.4-1.1) unstable; urgency=low | |
|
316 | ||
|
317 | * NMU from BSP Frankfurt: | |
|
318 | - Added Build-Depends on dpatch (Closes: #280505) | |
|
319 | ||
|
320 | -- Joerg Jaspert <joerg@debian.org> Sat, 27 Nov 2004 18:28:17 +0100 | |
|
321 | ||
|
1 | 322 | ipython (0.6.4-1) unstable; urgency=low |
|
2 | 323 | |
|
3 | * Fix dpatch dependency (Closes: #280505) | |
|
324 | * New upstream release | |
|
325 | * Updated debian/rules to use dpatch and added debian/patches/* | |
|
4 | 326 | |
|
5 | -- Fernando Perez <fperez@colorado.edu> Wed Nov 17 22:54:23 MST 2004 | |
|
327 | -- Jack Moffitt <jack@xiph.org> Tue, 9 Nov 2004 10:38:51 -0700 | |
|
6 | 328 | |
|
7 | 329 | ipython (0.6.3-1) unstable; urgency=low |
|
8 | 330 | |
|
9 | 331 | * New upstream release (Closes: #262244, #252525) |
|
10 | 332 | |
|
11 | 333 | -- Jack Moffitt <jack@xiph.org> Wed, 22 Sep 2004 21:39:38 -0600 |
|
12 | 334 | |
|
13 | 335 | ipython (0.6.0-1) unstable; urgency=low |
|
14 | 336 | |
|
15 | 337 | * New upstream release |
|
16 | 338 | |
|
17 | 339 | -- Jack Moffitt <jack@xiph.org> Sun, 9 May 2004 17:38:00 +0200 |
|
18 | 340 | |
|
19 | 341 | ipython (0.4.0-1.1) unstable; urgency=low |
|
20 | 342 | |
|
21 | 343 | * Non maintainer upload with maintainer consensus. |
|
22 | 344 | * Updated buil-dep to depend on python-2.3 (Closes: #206653) |
|
23 | 345 | * Included encoding comment string in modules under IPython to |
|
24 | 346 | avoid python2.3 Warnigs (upstream noticed). |
|
25 | 347 | |
|
26 | 348 | -- Marco Presi (Zufus) <zufus@debian.org> Mon, 25 Aug 2003 19:02:20 +0200 |
|
27 | 349 | |
|
28 | 350 | ipython (0.4.0-1) unstable; urgency=low |
|
29 | 351 | |
|
30 | * New upstream release (Closes #195215) | |
|
31 | * Updated Build-Depends (Closes #200021) | |
|
352 | * New upstream release (Closes: #195215) | |
|
353 | * Updated Build-Depends (Closes: #200021) | |
|
32 | 354 | |
|
33 | 355 | -- Jack Moffitt <jack@xiph.org> Fri, 25 Jul 2003 10:16:12 -0600 |
|
34 | 356 | |
|
35 | 357 | ipython (0.2.15pre3-4) unstable; urgency=low |
|
36 | 358 | |
|
37 | 359 | * Add python-dev Build-Depends (Closes: #189901) |
|
38 | 360 | |
|
39 | 361 | -- Jack Moffitt <jack@babyjesus.cantcode.com> Mon, 12 May 2003 23:33:43 -0600 |
|
40 | 362 | |
|
41 | 363 | ipython (0.2.15pre3-3) unstable; urgency=low |
|
42 | 364 | |
|
43 | 365 | * Fix for accidently converting home directory files' line ends |
|
44 | 366 | instead of just the appropriate ipython configuration files |
|
45 | 367 | (Closes: #189042) |
|
46 | 368 | |
|
47 | 369 | -- Jack Moffitt <jack@xiph.org> Mon, 14 Apr 2003 21:18:18 -0600 |
|
48 | 370 | |
|
49 | 371 | ipython (0.2.15pre3-2) unstable; urgency=low |
|
50 | 372 | |
|
51 | 373 | * Added text of the PSF license to debian/copyright. |
|
52 | 374 | |
|
53 | 375 | -- Jack Moffitt <jack@xiph.org> Sat, 5 Apr 2003 11:41:31 -0700 |
|
54 | 376 | |
|
55 | 377 | ipython (0.2.15pre3-1) unstable; urgency=low |
|
56 | 378 | |
|
57 | 379 | * Updated documentation to point to the new homepage - |
|
58 | 380 | http://ipython.scipy.org |
|
59 | 381 | * Removed doc/COPYING and doc/GNU-LGPL to fix lintian warnings |
|
60 | 382 | * Public release ready (Closes: #185789) |
|
61 | 383 | |
|
62 | 384 | -- Jack Moffitt <jack@xiph.org> Tue, 1 Apr 2003 20:53:31 -0700 |
|
63 | 385 | |
|
64 | 386 | ipython (0.2.15pre3-0a) unstable; urgency=low |
|
65 | 387 | |
|
66 | 388 | * Initial Release. |
|
67 | 389 | * This is my first Debian package |
|
68 | 390 | |
|
69 | 391 | -- Jack Moffitt <jack@xiph.org> Wed, 12 Mar 2003 21:04:22 -0700 |
|
70 | 392 |
@@ -1,21 +1,26 b'' | |||
|
1 | 1 | Source: ipython |
|
2 |
Section: |
|
|
2 | Section: python | |
|
3 | 3 | Priority: optional |
|
4 | Maintainer: Jack Moffitt <jack@xiph.org> | |
|
5 | Build-Depends-Indep: debhelper (>> 4.1.65), dpatch, python-dev | |
|
6 | Standards-Version: 3.6.1 | |
|
4 | Maintainer: Debian Python Modules Team <python-modules-team@lists.alioth.debian.org> | |
|
5 | Uploaders: Norbert Tretkowski <nobse@debian.org>, Bernd Zeimetz <bernd@bzed.de> | |
|
6 | Build-Depends: debhelper (>= 5.0.37.2), dpatch (>= 2.0.10), cdbs (>= 0.4.43), python, python-support (>= 0.4) | |
|
7 | Homepage: http://ipython.scipy.org/ | |
|
8 | Vcs-Svn: svn://svn.debian.org/python-modules/packages/ipython/trunk/ | |
|
9 | Vcs-Browser: http://svn.debian.org/wsvn/python-modules/packages/ipython/trunk/ | |
|
10 | Standards-Version: 3.7.2.2 | |
|
7 | 11 | |
|
8 | 12 | Package: ipython |
|
9 | 13 | Architecture: all |
|
10 | Depends: ${python:Depends} | |
|
11 | Recommends: python-numeric, python-numeric-ext | |
|
12 | Description: An enhanced interactive Python shell | |
|
13 | IPython is an enhanced interactive Python shell. It can be used as a | |
|
14 | replacement for the standard Python shell, or it can be used as a | |
|
15 | complete working environment for scientific computing (like Matlab or | |
|
16 | Mathematica) when paired with the standard Python scientific and | |
|
17 | numerical tools. It supports dynamic object introspections, numbered | |
|
18 | input/output prompts, a macro system, session logging, session | |
|
19 | restoring, complete system shell access, verbose and colored | |
|
20 | traceback reports, auto-parentheses, auto-quoting, and is | |
|
21 | embeddedable in other Python programs. | |
|
14 | Depends: ${python:Depends}, ${misc:Depends}, python-pexpect | |
|
15 | Conflicts: python2.3-ipython, python2.4-ipython, ipython-common | |
|
16 | Replaces: python2.3-ipython, python2.4-ipython, ipython-common | |
|
17 | Suggests: python-profiler, python-numeric, python-numeric-ext, python-matplotlib | |
|
18 | Description: enhanced interactive Python shell | |
|
19 | IPython can be used as a replacement for the standard Python shell, | |
|
20 | or it can be used as a complete working environment for scientific | |
|
21 | computing (like Matlab or Mathematica) when paired with the standard | |
|
22 | Python scientific and numerical tools. It supports dynamic object | |
|
23 | introspections, numbered input/output prompts, a macro system, | |
|
24 | session logging, session restoring, complete system shell access, | |
|
25 | verbose and colored traceback reports, auto-parentheses, auto-quoting, | |
|
26 | and is embeddable in other Python programs. |
@@ -1,204 +1,168 b'' | |||
|
1 | 1 | This package was debianized by Jack Moffitt <jack@xiph.org> on |
|
2 | 2 | Wed, 12 Mar 2003 20:38:14 -0700. |
|
3 | 3 | |
|
4 | 4 | It was downloaded from http://ipython.scipy.org/ |
|
5 | 5 | |
|
6 | 6 | Upstream Author: Fernando Perez <fperez@colorado.edu>, |
|
7 |
Janko Hauser <jhauser@ |
|
|
7 | Janko Hauser <jhauser@ifm.uni-kiel.de>, | |
|
8 | 8 | Nathaniel Gray <n8gray@caltech.edu> |
|
9 | 9 | |
|
10 | 10 | Copyright: |
|
11 | 11 | |
|
12 |
Most IPython code is copyright (C) 2001 |
|
|
13 |
and Nathaniel Gray. All code is licensed under |
|
|
14 | explicitly mentioned below. The full IPython license is: | |
|
15 | ||
|
16 | IPython is released under a BSD-type license. | |
|
17 | ||
|
18 | Copyright (c) 2001, 2002, 2003, 2004 Fernando Perez <fperez@colorado.edu>. | |
|
19 | ||
|
20 | Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and Nathaniel Gray | |
|
21 | <n8gray@caltech.edu>. | |
|
22 | ||
|
23 | All rights reserved. | |
|
24 | ||
|
25 | Redistribution and use in source and binary forms, with or without | |
|
26 | modification, are permitted provided that the following conditions are met: | |
|
27 | ||
|
28 | a. Redistributions of source code must retain the above copyright notice, | |
|
29 | this list of conditions and the following disclaimer. | |
|
30 | ||
|
31 | b. Redistributions in binary form must reproduce the above copyright | |
|
32 | notice, this list of conditions and the following disclaimer in the | |
|
33 | documentation and/or other materials provided with the distribution. | |
|
34 | ||
|
35 | c. Neither the name of the copyright holders nor the names of any | |
|
36 | contributors to this software may be used to endorse or promote products | |
|
37 | derived from this software without specific prior written permission. | |
|
38 | ||
|
39 | ||
|
40 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | |
|
41 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |
|
42 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | |
|
43 | ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR | |
|
44 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | |
|
45 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | |
|
46 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | |
|
47 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT | |
|
48 | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY | |
|
49 | OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH | |
|
50 | DAMAGE. | |
|
51 | ||
|
12 | Most IPython code is copyright (C) 2001 by Fernando Perez, Janko | |
|
13 | Hauser, and Nathaniel Gray. All code is licensed under the GNU Lesser | |
|
14 | General Public License (LGPL) except as explicitly mentioned below. | |
|
15 | Its full text is included in the file /usr/share/common-licenses/LGPL. | |
|
52 | 16 | |
|
53 | 17 | DPyGetOpt.py is copyright (C) 2001 by Bill Bumgarner <bbum@friday.com> |
|
54 | 18 | and is licensed under the MIT license, reproduced below: |
|
55 | 19 | |
|
56 | 20 | Permission is hereby granted, free of charge, to any person obtaining a copy |
|
57 | 21 | of this software and associated documentation files (the "Software"), to |
|
58 | 22 | deal in the Software without restriction, including without limitation the |
|
59 | 23 | rights to use, copy, modify, merge, publish, distribute, sublicense, and/or |
|
60 | 24 | sell copies of the Software, and to permit persons to whom the Software is |
|
61 | 25 | furnished to do so, subject to the following conditions: |
|
62 | 26 | |
|
63 | 27 | The above copyright notice and this permission notice shall be included in |
|
64 | 28 | all copies or substantial portions of the Software. |
|
65 | 29 | |
|
66 | 30 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
|
67 | 31 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
|
68 | 32 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
|
69 | 33 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
|
70 | 34 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING |
|
71 | 35 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS |
|
72 | 36 | IN THE SOFTWARE. |
|
73 | 37 | |
|
74 | 38 | FlexCompleter.py is copyright (C) 2001 by the Python Software |
|
75 | 39 | Foundation and licensed under the terms of the Python Software |
|
76 | 40 | Foundation License, reproduced below: |
|
77 | 41 | |
|
78 | 42 | A. HISTORY OF THE SOFTWARE |
|
79 | 43 | ========================== |
|
80 | 44 | |
|
81 | 45 | Python was created in the early 1990s by Guido van Rossum at Stichting |
|
82 | 46 | Mathematisch Centrum (CWI) in the Netherlands as a successor of a |
|
83 | 47 | language called ABC. Guido is Python's principal author, although it |
|
84 | 48 | includes many contributions from others. The last version released |
|
85 | 49 | from CWI was Python 1.2. In 1995, Guido continued his work on Python |
|
86 | 50 | at the Corporation for National Research Initiatives (CNRI) in Reston, |
|
87 | 51 | Virginia where he released several versions of the software. Python |
|
88 | 52 | 1.6 was the last of the versions released by CNRI. In 2000, Guido and |
|
89 | 53 | the Python core development team moved to BeOpen.com to form the |
|
90 | 54 | BeOpen PythonLabs team. Python 2.0 was the first and only release |
|
91 | 55 | from BeOpen.com. |
|
92 | 56 | |
|
93 | 57 | Following the release of Python 1.6, and after Guido van Rossum left |
|
94 | 58 | CNRI to work with commercial software developers, it became clear that |
|
95 | 59 | the ability to use Python with software available under the GNU Public |
|
96 | 60 | License (GPL) was very desirable. CNRI and the Free Software |
|
97 | 61 | Foundation (FSF) interacted to develop enabling wording changes to the |
|
98 | 62 | Python license. Python 1.6.1 is essentially the same as Python 1.6, |
|
99 | 63 | with a few minor bug fixes, and with a different license that enables |
|
100 | 64 | later versions to be GPL-compatible. Python 2.1 is a derivative work |
|
101 | 65 | of Python 1.6.1, as well as of Python 2.0. |
|
102 | 66 | |
|
103 | 67 | After Python 2.0 was released by BeOpen.com, Guido van Rossum and the |
|
104 | 68 | other PythonLabs developers joined Digital Creations. All |
|
105 | 69 | intellectual property added from this point on, starting with Python |
|
106 | 70 | 2.1 and its alpha and beta releases, is owned by the Python Software |
|
107 | 71 | Foundation (PSF), a non-profit modeled after the Apache Software |
|
108 | 72 | Foundation. See http://www.python.org/psf/ for more information about |
|
109 | 73 | the PSF. |
|
110 | 74 | |
|
111 | 75 | Thanks to the many outside volunteers who have worked under Guido's |
|
112 | 76 | direction to make these releases possible. |
|
113 | 77 | |
|
114 | 78 | |
|
115 | 79 | B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON |
|
116 | 80 | =============================================================== |
|
117 | 81 | |
|
118 | 82 | PSF LICENSE AGREEMENT |
|
119 | 83 | --------------------- |
|
120 | 84 | |
|
121 | 85 | 1. This LICENSE AGREEMENT is between the Python Software Foundation |
|
122 | 86 | ("PSF"), and the Individual or Organization ("Licensee") accessing and |
|
123 | 87 | otherwise using Python 2.1 software in source or binary form and its |
|
124 | 88 | associated documentation. |
|
125 | 89 | |
|
126 | 90 | 2. Subject to the terms and conditions of this License Agreement, PSF |
|
127 | 91 | hereby grants Licensee a nonexclusive, royalty-free, world-wide |
|
128 | 92 | license to reproduce, analyze, test, perform and/or display publicly, |
|
129 | 93 | prepare derivative works, distribute, and otherwise use Python 2.1 |
|
130 | 94 | alone or in any derivative version, provided, however, that PSF's |
|
131 | 95 | License Agreement and PSF's notice of copyright, i.e., "Copyright (c) |
|
132 | 96 | 2001 Python Software Foundation; All Rights Reserved" are retained in |
|
133 | 97 | Python 2.1 alone or in any derivative version prepared by Licensee. |
|
134 | 98 | |
|
135 | 99 | 3. In the event Licensee prepares a derivative work that is based on |
|
136 | 100 | or incorporates Python 2.1 or any part thereof, and wants to make |
|
137 | 101 | the derivative work available to others as provided herein, then |
|
138 | 102 | Licensee hereby agrees to include in any such work a brief summary of |
|
139 | 103 | the changes made to Python 2.1. |
|
140 | 104 | |
|
141 | 105 | 4. PSF is making Python 2.1 available to Licensee on an "AS IS" |
|
142 | 106 | basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR |
|
143 | 107 | IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND |
|
144 | 108 | DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS |
|
145 | 109 | FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.1 WILL NOT |
|
146 | 110 | INFRINGE ANY THIRD PARTY RIGHTS. |
|
147 | 111 | |
|
148 | 112 | 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON |
|
149 | 113 | 2.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A |
|
150 | 114 | RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 2.1, OR |
|
151 | 115 | ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. |
|
152 | 116 | |
|
153 | 117 | 6. This License Agreement will automatically terminate upon a material |
|
154 | 118 | breach of its terms and conditions. |
|
155 | 119 | |
|
156 | 120 | 7. This License Agreement shall be governed by the federal |
|
157 | 121 | intellectual property law of the United States, including without |
|
158 | 122 | limitation the federal copyright law, and, to the extent such |
|
159 | 123 | U.S. federal law does not apply, by the law of the Commonwealth of |
|
160 | 124 | Virginia, excluding Virginia's conflict of law provisions. |
|
161 | 125 | Notwithstanding the foregoing, with regard to derivative works based |
|
162 | 126 | on Python 1.6.1 that incorporate non-separable material that was |
|
163 | 127 | previously distributed under the GNU General Public License (GPL), the |
|
164 | 128 | law of the Commonwealth of Virginia shall govern this License |
|
165 | 129 | Agreement only as to issues arising under or with respect to |
|
166 | 130 | Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this |
|
167 | 131 | License Agreement shall be deemed to create any relationship of |
|
168 | 132 | agency, partnership, or joint venture between CNRI and Licensee. This |
|
169 | 133 | License Agreement does not grant permission to use CNRI trademarks or |
|
170 | 134 | trade name in a trademark sense to endorse or promote products or |
|
171 | 135 | services of Licensee, or any third party. |
|
172 | 136 | |
|
173 | 137 | 8. By clicking on the "ACCEPT" button where indicated, or by copying, |
|
174 | 138 | installing or otherwise using Python 1.6.1, Licensee agrees to be |
|
175 | 139 | bound by the terms and conditions of this License Agreement. |
|
176 | 140 | |
|
177 | 141 | ACCEPT |
|
178 | 142 | |
|
179 | 143 | |
|
180 | 144 | CWI PERMISSIONS STATEMENT AND DISCLAIMER |
|
181 | 145 | ---------------------------------------- |
|
182 | 146 | |
|
183 | 147 | Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, |
|
184 | 148 | The Netherlands. All rights reserved. |
|
185 | 149 | |
|
186 | 150 | Permission to use, copy, modify, and distribute this software and its |
|
187 | 151 | documentation for any purpose and without fee is hereby granted, |
|
188 | 152 | provided that the above copyright notice appear in all copies and that |
|
189 | 153 | both that copyright notice and this permission notice appear in |
|
190 | 154 | supporting documentation, and that the name of Stichting Mathematisch |
|
191 | 155 | Centrum or CWI not be used in advertising or publicity pertaining to |
|
192 | 156 | distribution of the software without specific, written prior |
|
193 | 157 | permission. |
|
194 | 158 | |
|
195 | 159 | STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO |
|
196 | 160 | THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND |
|
197 | 161 | FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE |
|
198 | 162 | FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |
|
199 | 163 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |
|
200 | 164 | ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT |
|
201 | 165 | OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |
|
202 | 166 | |
|
203 | 167 | Itpl.py is copyright (C) 2001 Ka-Ping Yee <ping@lfw.org> and licensed |
|
204 | 168 | under the MIT license reproduced above. |
@@ -1,98 +1,25 b'' | |||
|
1 | 1 | #!/usr/bin/make -f |
|
2 | # Sample debian/rules that uses debhelper. | |
|
3 | # GNU copyright 1997 to 1999 by Joey Hess. | |
|
4 | ||
|
5 | # Uncomment this to turn on verbose mode. | |
|
6 | #export DH_VERBOSE=1 | |
|
7 | ||
|
8 | ||
|
9 | ||
|
10 | ||
|
11 | CFLAGS = -Wall -g | |
|
12 | ||
|
13 | ifneq (,$(findstring noopt,$(DEB_BUILD_OPTIONS))) | |
|
14 | CFLAGS += -O0 | |
|
15 | else | |
|
16 | CFLAGS += -O2 | |
|
17 | endif | |
|
18 | ifeq (,$(findstring nostrip,$(DEB_BUILD_OPTIONS))) | |
|
19 | INSTALL_PROGRAM += -s | |
|
20 | endif | |
|
21 | ||
|
22 | configure: configure-stamp | |
|
23 | configure-stamp: | |
|
24 | dh_testdir | |
|
25 | ||
|
26 | python setup.py config | |
|
27 | ||
|
28 | touch configure-stamp | |
|
29 | ||
|
30 | ||
|
31 | build: build-stamp | |
|
32 | ||
|
33 | build-stamp: configure-stamp | |
|
34 | dh_testdir | |
|
35 | ||
|
36 | python setup.py build | |
|
37 | ||
|
38 | touch build-stamp | |
|
39 | ||
|
40 | clean: | |
|
41 | dh_testdir | |
|
42 | dh_testroot | |
|
43 | rm -f build-stamp configure-stamp | |
|
44 | ||
|
45 | -python setup.py clean --all | |
|
46 | rm -f setupext/*.pyc | |
|
47 | ||
|
48 | dh_clean | |
|
49 | ||
|
50 | install: build | |
|
51 | dh_testdir | |
|
52 | dh_testroot | |
|
53 | dh_clean -k | |
|
54 | dh_installdirs | |
|
55 | ||
|
56 | python setup.py install --prefix $(CURDIR)/debian/ipython/usr | |
|
57 | ||
|
58 | # remove extra license docs that get installed | |
|
59 | rm -f $(CURDIR)/debian/ipython/usr/share/doc/ipython/COPYING | |
|
60 | #rm -f $(CURDIR)/debian/ipython/usr/share/doc/ipython/GNU-LGPL | |
|
61 | ||
|
2 | # ipython debian/rules file | |
|
3 | DEB_PYTHON_SYSTEM=pysupport | |
|
4 | include /usr/share/cdbs/1/rules/debhelper.mk | |
|
5 | include /usr/share/cdbs/1/class/python-distutils.mk | |
|
6 | include /usr/share/cdbs/1/rules/dpatch.mk | |
|
7 | ||
|
8 | install/ipython:: | |
|
9 | # remove documentation | |
|
10 | rm $(CURDIR)/debian/ipython/usr/share/doc/ipython/COPYING | |
|
11 | rm $(CURDIR)/debian/ipython/usr/share/doc/ipython/ChangeLog | |
|
12 | rm $(CURDIR)/debian/ipython/usr/share/doc/ipython/README_Windows.txt | |
|
13 | rm $(CURDIR)/debian/ipython/usr/share/doc/ipython/pycon.ico | |
|
14 | ||
|
62 | 15 | # change permission on scripts |
|
63 |
chmod |
|
|
64 | chmod 755 $(CURDIR)/debian/ipython/usr/share/doc/ipython/examples/example-gnuplot.py | |
|
65 | ||
|
66 | binary-indep: build install | |
|
67 | dh_testdir | |
|
68 | dh_testroot | |
|
69 | dh_installchangelogs doc/ChangeLog | |
|
70 | dh_installdocs | |
|
71 | # dh_installexamples | |
|
72 | dh_install | |
|
73 | # dh_installmenu | |
|
74 | # dh_installdebconf | |
|
75 | # dh_installlogrotate | |
|
76 | # dh_installemacsen | |
|
77 | # dh_installpam | |
|
78 | # dh_installmime | |
|
79 | # dh_installinit | |
|
80 | # dh_installcron | |
|
81 | # dh_installinfo | |
|
82 | dh_installman doc/ipython.1.gz doc/pycolor.1.gz | |
|
83 | dh_compress | |
|
84 | dh_fixperms | |
|
85 | dh_python | |
|
86 | # dh_makeshlibs | |
|
87 | dh_installdeb | |
|
88 | # dh_shlibdeps | |
|
89 | dh_gencontrol | |
|
90 | dh_md5sums | |
|
91 | dh_builddeb | |
|
92 | ||
|
93 | # Build architecture-dependent files here. | |
|
94 | binary-arch: build install | |
|
95 | # We have nothing to do by default. | |
|
96 | ||
|
97 | binary: binary-indep binary-arch | |
|
98 | .PHONY: build clean binary-indep binary-arch binary install configure | |
|
16 | chmod a-x $(CURDIR)/debian/ipython/usr/share/doc/ipython/examples/* | |
|
17 | ||
|
18 | # removing bogus usr/IPython directory | |
|
19 | rm -rf $(CURDIR)/debian/ipython/usr/IPython | |
|
20 | ||
|
21 | binary-fixup/ipython:: | |
|
22 | # fix lintian warnings (see also patches/04_remove_shebang.dpatch) | |
|
23 | chmod +x $(CURDIR)/debian/ipython/usr/share/python-support/ipython/IPython/upgrade_dir.py | |
|
24 | chmod +x $(CURDIR)/debian/ipython/usr/share/python-support/ipython/IPython/Extensions/pickleshare.py | |
|
25 | chmod +x $(CURDIR)/debian/ipython/usr/share/python-support/ipython/IPython/irunner.py |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | 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