Show More
The requested changes are too big and content was truncated. Show full diff
@@ -1,364 +1,386 b'' | |||||
1 |
|
1 | |||
2 | """ Implementations for various useful completers |
|
2 | """ Implementations for various useful completers | |
3 |
|
3 | |||
4 | See Extensions/ipy_stock_completers.py on examples of how to enable a completer, |
|
4 | See Extensions/ipy_stock_completers.py on examples of how to enable a completer, | |
5 | but the basic idea is to do: |
|
5 | but the basic idea is to do: | |
6 |
|
6 | |||
7 | ip.set_hook('complete_command', svn_completer, str_key = 'svn') |
|
7 | ip.set_hook('complete_command', svn_completer, str_key = 'svn') | |
8 |
|
8 | |||
9 | """ |
|
9 | """ | |
10 | import IPython.ipapi |
|
10 | import IPython.ipapi | |
11 | import glob,os,shlex,sys |
|
11 | import glob,os,shlex,sys | |
12 | import inspect |
|
12 | import inspect | |
13 | from time import time |
|
13 | from time import time | |
14 | from zipimport import zipimporter |
|
14 | from zipimport import zipimporter | |
15 | ip = IPython.ipapi.get() |
|
15 | ip = IPython.ipapi.get() | |
16 |
|
16 | |||
17 | try: |
|
17 | try: | |
18 | set |
|
18 | set | |
19 | except: |
|
19 | except: | |
20 | from sets import Set as set |
|
20 | from sets import Set as set | |
21 |
|
21 | |||
22 | TIMEOUT_STORAGE = 3 #Time in seconds after which the rootmodules will be stored |
|
22 | TIMEOUT_STORAGE = 3 #Time in seconds after which the rootmodules will be stored | |
23 | TIMEOUT_GIVEUP = 20 #Time in seconds after which we give up |
|
23 | TIMEOUT_GIVEUP = 20 #Time in seconds after which we give up | |
24 |
|
24 | |||
25 | def quick_completer(cmd, completions): |
|
25 | def quick_completer(cmd, completions): | |
26 | """ Easily create a trivial completer for a command. |
|
26 | """ Easily create a trivial completer for a command. | |
27 |
|
27 | |||
28 | Takes either a list of completions, or all completions in string |
|
28 | Takes either a list of completions, or all completions in string | |
29 | (that will be split on whitespace) |
|
29 | (that will be split on whitespace) | |
30 |
|
30 | |||
31 | Example:: |
|
31 | Example:: | |
32 |
|
32 | |||
33 | [d:\ipython]|1> import ipy_completers |
|
33 | [d:\ipython]|1> import ipy_completers | |
34 | [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz']) |
|
34 | [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz']) | |
35 | [d:\ipython]|3> foo b<TAB> |
|
35 | [d:\ipython]|3> foo b<TAB> | |
36 | bar baz |
|
36 | bar baz | |
37 | [d:\ipython]|3> foo ba |
|
37 | [d:\ipython]|3> foo ba | |
38 | """ |
|
38 | """ | |
39 | if isinstance(completions, basestring): |
|
39 | if isinstance(completions, basestring): | |
40 |
|
40 | |||
41 | completions = completions.split() |
|
41 | completions = completions.split() | |
42 | def do_complete(self,event): |
|
42 | def do_complete(self,event): | |
43 | return completions |
|
43 | return completions | |
44 |
|
44 | |||
45 | ip.set_hook('complete_command',do_complete, str_key = cmd) |
|
45 | ip.set_hook('complete_command',do_complete, str_key = cmd) | |
46 |
|
46 | |||
47 | def getRootModules(): |
|
47 | def getRootModules(): | |
48 | """ |
|
48 | """ | |
49 | Returns a list containing the names of all the modules available in the |
|
49 | Returns a list containing the names of all the modules available in the | |
50 | folders of the pythonpath. |
|
50 | folders of the pythonpath. | |
51 | """ |
|
51 | """ | |
52 | modules = [] |
|
52 | modules = [] | |
53 | if ip.db.has_key('rootmodules'): |
|
53 | if ip.db.has_key('rootmodules'): | |
54 | return ip.db['rootmodules'] |
|
54 | return ip.db['rootmodules'] | |
55 | t = time() |
|
55 | t = time() | |
56 | store = False |
|
56 | store = False | |
57 | for path in sys.path: |
|
57 | for path in sys.path: | |
58 | modules += moduleList(path) |
|
58 | modules += moduleList(path) | |
59 | if time() - t >= TIMEOUT_STORAGE and not store: |
|
59 | if time() - t >= TIMEOUT_STORAGE and not store: | |
60 | store = True |
|
60 | store = True | |
61 | print "\nCaching the list of root modules, please wait!" |
|
61 | print "\nCaching the list of root modules, please wait!" | |
62 | print "(This will only be done once - type '%rehashx' to " + \ |
|
62 | print "(This will only be done once - type '%rehashx' to " + \ | |
63 | "reset cache!)" |
|
63 | "reset cache!)" | |
64 |
|
64 | |||
65 | if time() - t > TIMEOUT_GIVEUP: |
|
65 | if time() - t > TIMEOUT_GIVEUP: | |
66 | print "This is taking too long, we give up." |
|
66 | print "This is taking too long, we give up." | |
67 |
|
67 | |||
68 | ip.db['rootmodules'] = [] |
|
68 | ip.db['rootmodules'] = [] | |
69 | return [] |
|
69 | return [] | |
70 |
|
70 | |||
71 | modules += sys.builtin_module_names |
|
71 | modules += sys.builtin_module_names | |
72 |
|
72 | |||
73 | modules = list(set(modules)) |
|
73 | modules = list(set(modules)) | |
74 | if '__init__' in modules: |
|
74 | if '__init__' in modules: | |
75 | modules.remove('__init__') |
|
75 | modules.remove('__init__') | |
76 | modules = list(set(modules)) |
|
76 | modules = list(set(modules)) | |
77 | if store: |
|
77 | if store: | |
78 | ip.db['rootmodules'] = modules |
|
78 | ip.db['rootmodules'] = modules | |
79 | return modules |
|
79 | return modules | |
80 |
|
80 | |||
81 | def moduleList(path): |
|
81 | def moduleList(path): | |
82 | """ |
|
82 | """ | |
83 | Return the list containing the names of the modules available in the given |
|
83 | Return the list containing the names of the modules available in the given | |
84 | folder. |
|
84 | folder. | |
85 | """ |
|
85 | """ | |
86 |
|
86 | |||
87 | if os.path.isdir(path): |
|
87 | if os.path.isdir(path): | |
88 | folder_list = os.listdir(path) |
|
88 | folder_list = os.listdir(path) | |
89 | elif path.endswith('.egg'): |
|
89 | elif path.endswith('.egg'): | |
90 | try: |
|
90 | try: | |
91 | folder_list = [f for f in zipimporter(path)._files] |
|
91 | folder_list = [f for f in zipimporter(path)._files] | |
92 | except: |
|
92 | except: | |
93 | folder_list = [] |
|
93 | folder_list = [] | |
94 | else: |
|
94 | else: | |
95 | folder_list = [] |
|
95 | folder_list = [] | |
96 | #folder_list = glob.glob(os.path.join(path,'*')) |
|
96 | #folder_list = glob.glob(os.path.join(path,'*')) | |
97 | folder_list = [p for p in folder_list \ |
|
97 | folder_list = [p for p in folder_list \ | |
98 | if os.path.exists(os.path.join(path, p,'__init__.py'))\ |
|
98 | if os.path.exists(os.path.join(path, p,'__init__.py'))\ | |
99 | or p[-3:] in ('.py','.so')\ |
|
99 | or p[-3:] in ('.py','.so')\ | |
100 | or p[-4:] in ('.pyc','.pyo','.pyd')] |
|
100 | or p[-4:] in ('.pyc','.pyo','.pyd')] | |
101 |
|
101 | |||
102 | folder_list = [os.path.basename(p).split('.')[0] for p in folder_list] |
|
102 | folder_list = [os.path.basename(p).split('.')[0] for p in folder_list] | |
103 | return folder_list |
|
103 | return folder_list | |
104 |
|
104 | |||
105 | def moduleCompletion(line): |
|
105 | def moduleCompletion(line): | |
106 | """ |
|
106 | """ | |
107 | Returns a list containing the completion possibilities for an import line. |
|
107 | Returns a list containing the completion possibilities for an import line. | |
108 | The line looks like this : |
|
108 | The line looks like this : | |
109 | 'import xml.d' |
|
109 | 'import xml.d' | |
110 | 'from xml.dom import' |
|
110 | 'from xml.dom import' | |
111 | """ |
|
111 | """ | |
112 | def tryImport(mod, only_modules=False): |
|
112 | def tryImport(mod, only_modules=False): | |
113 | def isImportable(module, attr): |
|
113 | def isImportable(module, attr): | |
114 | if only_modules: |
|
114 | if only_modules: | |
115 | return inspect.ismodule(getattr(module, attr)) |
|
115 | return inspect.ismodule(getattr(module, attr)) | |
116 | else: |
|
116 | else: | |
117 | return not(attr[:2] == '__' and attr[-2:] == '__') |
|
117 | return not(attr[:2] == '__' and attr[-2:] == '__') | |
118 | try: |
|
118 | try: | |
119 | m = __import__(mod) |
|
119 | m = __import__(mod) | |
120 | except: |
|
120 | except: | |
121 | return [] |
|
121 | return [] | |
122 | mods = mod.split('.') |
|
122 | mods = mod.split('.') | |
123 | for module in mods[1:]: |
|
123 | for module in mods[1:]: | |
124 | m = getattr(m,module) |
|
124 | m = getattr(m,module) | |
125 | if (not hasattr(m, '__file__')) or (not only_modules) or\ |
|
125 | if (not hasattr(m, '__file__')) or (not only_modules) or\ | |
126 | (hasattr(m, '__file__') and '__init__' in m.__file__): |
|
126 | (hasattr(m, '__file__') and '__init__' in m.__file__): | |
127 | completion_list = [attr for attr in dir(m) if isImportable(m, attr)] |
|
127 | completion_list = [attr for attr in dir(m) if isImportable(m, attr)] | |
128 | completion_list.extend(getattr(m,'__all__',[])) |
|
128 | completion_list.extend(getattr(m,'__all__',[])) | |
129 | if hasattr(m, '__file__') and '__init__' in m.__file__: |
|
129 | if hasattr(m, '__file__') and '__init__' in m.__file__: | |
130 | completion_list.extend(moduleList(os.path.dirname(m.__file__))) |
|
130 | completion_list.extend(moduleList(os.path.dirname(m.__file__))) | |
131 | completion_list = list(set(completion_list)) |
|
131 | completion_list = list(set(completion_list)) | |
132 | if '__init__' in completion_list: |
|
132 | if '__init__' in completion_list: | |
133 | completion_list.remove('__init__') |
|
133 | completion_list.remove('__init__') | |
134 | return completion_list |
|
134 | return completion_list | |
135 |
|
135 | |||
136 | words = line.split(' ') |
|
136 | words = line.split(' ') | |
137 | if len(words) == 3 and words[0] == 'from': |
|
137 | if len(words) == 3 and words[0] == 'from': | |
138 | return ['import '] |
|
138 | return ['import '] | |
139 | if len(words) < 3 and (words[0] in ['import','from']) : |
|
139 | if len(words) < 3 and (words[0] in ['import','from']) : | |
140 | if len(words) == 1: |
|
140 | if len(words) == 1: | |
141 | return getRootModules() |
|
141 | return getRootModules() | |
142 | mod = words[1].split('.') |
|
142 | mod = words[1].split('.') | |
143 | if len(mod) < 2: |
|
143 | if len(mod) < 2: | |
144 | return getRootModules() |
|
144 | return getRootModules() | |
145 | completion_list = tryImport('.'.join(mod[:-1]), True) |
|
145 | completion_list = tryImport('.'.join(mod[:-1]), True) | |
146 | completion_list = ['.'.join(mod[:-1] + [el]) for el in completion_list] |
|
146 | completion_list = ['.'.join(mod[:-1] + [el]) for el in completion_list] | |
147 | return completion_list |
|
147 | return completion_list | |
148 | if len(words) >= 3 and words[0] == 'from': |
|
148 | if len(words) >= 3 and words[0] == 'from': | |
149 | mod = words[1] |
|
149 | mod = words[1] | |
150 | return tryImport(mod) |
|
150 | return tryImport(mod) | |
151 |
|
151 | |||
152 | def vcs_completer(commands, event): |
|
152 | def vcs_completer(commands, event): | |
153 | """ utility to make writing typical version control app completers easier |
|
153 | """ utility to make writing typical version control app completers easier | |
154 |
|
154 | |||
155 | VCS command line apps typically have the format: |
|
155 | VCS command line apps typically have the format: | |
156 |
|
156 | |||
157 | [sudo ]PROGNAME [help] [command] file file... |
|
157 | [sudo ]PROGNAME [help] [command] file file... | |
158 |
|
158 | |||
159 | """ |
|
159 | """ | |
160 |
|
160 | |||
161 |
|
161 | |||
162 | cmd_param = event.line.split() |
|
162 | cmd_param = event.line.split() | |
163 | if event.line.endswith(' '): |
|
163 | if event.line.endswith(' '): | |
164 | cmd_param.append('') |
|
164 | cmd_param.append('') | |
165 |
|
165 | |||
166 | if cmd_param[0] == 'sudo': |
|
166 | if cmd_param[0] == 'sudo': | |
167 | cmd_param = cmd_param[1:] |
|
167 | cmd_param = cmd_param[1:] | |
168 |
|
168 | |||
169 | if len(cmd_param) == 2 or 'help' in cmd_param: |
|
169 | if len(cmd_param) == 2 or 'help' in cmd_param: | |
170 | return commands.split() |
|
170 | return commands.split() | |
171 |
|
171 | |||
172 | return ip.IP.Completer.file_matches(event.symbol) |
|
172 | return ip.IP.Completer.file_matches(event.symbol) | |
173 |
|
173 | |||
174 |
|
174 | |||
175 | pkg_cache = None |
|
175 | pkg_cache = None | |
176 |
|
176 | |||
177 | def module_completer(self,event): |
|
177 | def module_completer(self,event): | |
178 | """ Give completions after user has typed 'import ...' or 'from ...'""" |
|
178 | """ Give completions after user has typed 'import ...' or 'from ...'""" | |
179 |
|
179 | |||
180 | # This works in all versions of python. While 2.5 has |
|
180 | # This works in all versions of python. While 2.5 has | |
181 | # pkgutil.walk_packages(), that particular routine is fairly dangerous, |
|
181 | # pkgutil.walk_packages(), that particular routine is fairly dangerous, | |
182 | # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full |
|
182 | # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full | |
183 | # of possibly problematic side effects. |
|
183 | # of possibly problematic side effects. | |
184 | # This search the folders in the sys.path for available modules. |
|
184 | # This search the folders in the sys.path for available modules. | |
185 |
|
185 | |||
186 | return moduleCompletion(event.line) |
|
186 | return moduleCompletion(event.line) | |
187 |
|
187 | |||
188 |
|
188 | |||
189 | svn_commands = """\ |
|
189 | svn_commands = """\ | |
190 | add blame praise annotate ann cat checkout co cleanup commit ci copy |
|
190 | add blame praise annotate ann cat checkout co cleanup commit ci copy | |
191 | cp delete del remove rm diff di export help ? h import info list ls |
|
191 | cp delete del remove rm diff di export help ? h import info list ls | |
192 | lock log merge mkdir move mv rename ren propdel pdel pd propedit pedit |
|
192 | lock log merge mkdir move mv rename ren propdel pdel pd propedit pedit | |
193 | pe propget pget pg proplist plist pl propset pset ps resolved revert |
|
193 | pe propget pget pg proplist plist pl propset pset ps resolved revert | |
194 | status stat st switch sw unlock update |
|
194 | status stat st switch sw unlock update | |
195 | """ |
|
195 | """ | |
196 |
|
196 | |||
197 | def svn_completer(self,event): |
|
197 | def svn_completer(self,event): | |
198 | return vcs_completer(svn_commands, event) |
|
198 | return vcs_completer(svn_commands, event) | |
199 |
|
199 | |||
200 |
|
200 | |||
201 | hg_commands = """ |
|
201 | hg_commands = """ | |
202 | add addremove annotate archive backout branch branches bundle cat |
|
202 | add addremove annotate archive backout branch branches bundle cat | |
203 | clone commit copy diff export grep heads help identify import incoming |
|
203 | clone commit copy diff export grep heads help identify import incoming | |
204 | init locate log manifest merge outgoing parents paths pull push |
|
204 | init locate log manifest merge outgoing parents paths pull push | |
205 | qapplied qclone qcommit qdelete qdiff qfold qguard qheader qimport |
|
205 | qapplied qclone qcommit qdelete qdiff qfold qguard qheader qimport | |
206 | qinit qnew qnext qpop qprev qpush qrefresh qrename qrestore qsave |
|
206 | qinit qnew qnext qpop qprev qpush qrefresh qrename qrestore qsave | |
207 | qselect qseries qtop qunapplied recover remove rename revert rollback |
|
207 | qselect qseries qtop qunapplied recover remove rename revert rollback | |
208 | root serve showconfig status strip tag tags tip unbundle update verify |
|
208 | root serve showconfig status strip tag tags tip unbundle update verify | |
209 | version |
|
209 | version | |
210 | """ |
|
210 | """ | |
211 |
|
211 | |||
212 | def hg_completer(self,event): |
|
212 | def hg_completer(self,event): | |
213 | """ Completer for mercurial commands """ |
|
213 | """ Completer for mercurial commands """ | |
214 |
|
214 | |||
215 | return vcs_completer(hg_commands, event) |
|
215 | return vcs_completer(hg_commands, event) | |
216 |
|
216 | |||
217 |
|
217 | |||
218 |
|
218 | |||
219 | __bzr_commands = None |
|
219 | __bzr_commands = None | |
220 |
|
220 | |||
221 | def bzr_commands(): |
|
221 | def bzr_commands(): | |
222 | global __bzr_commands |
|
222 | global __bzr_commands | |
223 | if __bzr_commands is not None: |
|
223 | if __bzr_commands is not None: | |
224 | return __bzr_commands |
|
224 | return __bzr_commands | |
225 | out = os.popen('bzr help commands') |
|
225 | out = os.popen('bzr help commands') | |
226 | __bzr_commands = [l.split()[0] for l in out] |
|
226 | __bzr_commands = [l.split()[0] for l in out] | |
227 | return __bzr_commands |
|
227 | return __bzr_commands | |
228 |
|
228 | |||
229 | def bzr_completer(self,event): |
|
229 | def bzr_completer(self,event): | |
230 | """ Completer for bazaar commands """ |
|
230 | """ Completer for bazaar commands """ | |
231 | cmd_param = event.line.split() |
|
231 | cmd_param = event.line.split() | |
232 | if event.line.endswith(' '): |
|
232 | if event.line.endswith(' '): | |
233 | cmd_param.append('') |
|
233 | cmd_param.append('') | |
234 |
|
234 | |||
235 | if len(cmd_param) > 2: |
|
235 | if len(cmd_param) > 2: | |
236 | cmd = cmd_param[1] |
|
236 | cmd = cmd_param[1] | |
237 | param = cmd_param[-1] |
|
237 | param = cmd_param[-1] | |
238 | output_file = (param == '--output=') |
|
238 | output_file = (param == '--output=') | |
239 | if cmd == 'help': |
|
239 | if cmd == 'help': | |
240 | return bzr_commands() |
|
240 | return bzr_commands() | |
241 | elif cmd in ['bundle-revisions','conflicts', |
|
241 | elif cmd in ['bundle-revisions','conflicts', | |
242 | 'deleted','nick','register-branch', |
|
242 | 'deleted','nick','register-branch', | |
243 | 'serve','unbind','upgrade','version', |
|
243 | 'serve','unbind','upgrade','version', | |
244 | 'whoami'] and not output_file: |
|
244 | 'whoami'] and not output_file: | |
245 | return [] |
|
245 | return [] | |
246 | else: |
|
246 | else: | |
247 | # the rest are probably file names |
|
247 | # the rest are probably file names | |
248 | return ip.IP.Completer.file_matches(event.symbol) |
|
248 | return ip.IP.Completer.file_matches(event.symbol) | |
249 |
|
249 | |||
250 | return bzr_commands() |
|
250 | return bzr_commands() | |
251 |
|
251 | |||
252 |
|
252 | |||
253 | def shlex_split(x): |
|
253 | def shlex_split(x): | |
254 | """Helper function to split lines into segments.""" |
|
254 | """Helper function to split lines into segments.""" | |
255 | #shlex.split raise exception if syntax error in sh syntax |
|
255 | #shlex.split raise exception if syntax error in sh syntax | |
256 | #for example if no closing " is found. This function keeps dropping |
|
256 | #for example if no closing " is found. This function keeps dropping | |
257 | #the last character of the line until shlex.split does not raise |
|
257 | #the last character of the line until shlex.split does not raise | |
258 | #exception. Adds end of the line to the result of shlex.split |
|
258 | #exception. Adds end of the line to the result of shlex.split | |
259 | #example: %run "c:/python -> ['%run','"c:/python'] |
|
259 | #example: %run "c:/python -> ['%run','"c:/python'] | |
260 | endofline=[] |
|
260 | endofline=[] | |
261 | while x!="": |
|
261 | while x!="": | |
262 | try: |
|
262 | try: | |
263 | comps=shlex.split(x) |
|
263 | comps=shlex.split(x) | |
264 | if len(endofline)>=1: |
|
264 | if len(endofline)>=1: | |
265 | comps.append("".join(endofline)) |
|
265 | comps.append("".join(endofline)) | |
266 | return comps |
|
266 | return comps | |
267 | except ValueError: |
|
267 | except ValueError: | |
268 | endofline=[x[-1:]]+endofline |
|
268 | endofline=[x[-1:]]+endofline | |
269 | x=x[:-1] |
|
269 | x=x[:-1] | |
270 | return ["".join(endofline)] |
|
270 | return ["".join(endofline)] | |
271 |
|
271 | |||
272 | def runlistpy(self, event): |
|
272 | def runlistpy(self, event): | |
273 | comps = shlex_split(event.line) |
|
273 | comps = shlex_split(event.line) | |
274 | relpath = (len(comps) > 1 and comps[-1] or '').strip("'\"") |
|
274 | relpath = (len(comps) > 1 and comps[-1] or '').strip("'\"") | |
275 |
|
275 | |||
276 | #print "\nev=",event # dbg |
|
276 | #print "\nev=",event # dbg | |
277 | #print "rp=",relpath # dbg |
|
277 | #print "rp=",relpath # dbg | |
278 | #print 'comps=',comps # dbg |
|
278 | #print 'comps=',comps # dbg | |
279 |
|
279 | |||
280 | lglob = glob.glob |
|
280 | lglob = glob.glob | |
281 | isdir = os.path.isdir |
|
281 | isdir = os.path.isdir | |
282 | if relpath.startswith('~'): |
|
282 | if relpath.startswith('~'): | |
283 | relpath = os.path.expanduser(relpath) |
|
283 | relpath = os.path.expanduser(relpath) | |
284 | dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*') |
|
284 | dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*') | |
285 | if isdir(f)] |
|
285 | if isdir(f)] | |
286 |
|
286 | |||
287 | # Find if the user has already typed the first filename, after which we |
|
287 | # Find if the user has already typed the first filename, after which we | |
288 | # should complete on all files, since after the first one other files may |
|
288 | # should complete on all files, since after the first one other files may | |
289 | # be arguments to the input script. |
|
289 | # be arguments to the input script. | |
290 | #filter( |
|
290 | #filter( | |
291 | if filter(lambda f: f.endswith('.py') or f.endswith('.ipy') or |
|
291 | if filter(lambda f: f.endswith('.py') or f.endswith('.ipy') or | |
292 | f.endswith('.pyw'),comps): |
|
292 | f.endswith('.pyw'),comps): | |
293 | pys = [f.replace('\\','/') for f in lglob('*')] |
|
293 | pys = [f.replace('\\','/') for f in lglob('*')] | |
294 | else: |
|
294 | else: | |
295 | pys = [f.replace('\\','/') |
|
295 | pys = [f.replace('\\','/') | |
296 | for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') + |
|
296 | for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') + | |
297 | lglob(relpath + '*.pyw')] |
|
297 | lglob(relpath + '*.pyw')] | |
298 | return dirs + pys |
|
298 | return dirs + pys | |
299 |
|
299 | |||
300 |
|
300 | |||
301 | def cd_completer(self, event): |
|
301 | def cd_completer(self, event): | |
302 | relpath = event.symbol |
|
302 | relpath = event.symbol | |
303 | #print event # dbg |
|
303 | #print event # dbg | |
304 | if '-b' in event.line: |
|
304 | if '-b' in event.line: | |
305 | # return only bookmark completions |
|
305 | # return only bookmark completions | |
306 | bkms = self.db.get('bookmarks',{}) |
|
306 | bkms = self.db.get('bookmarks',{}) | |
307 | return bkms.keys() |
|
307 | return bkms.keys() | |
308 |
|
308 | |||
309 |
|
309 | |||
310 | if event.symbol == '-': |
|
310 | if event.symbol == '-': | |
311 | width_dh = str(len(str(len(ip.user_ns['_dh']) + 1))) |
|
311 | width_dh = str(len(str(len(ip.user_ns['_dh']) + 1))) | |
312 | # jump in directory history by number |
|
312 | # jump in directory history by number | |
313 | fmt = '-%0' + width_dh +'d [%s]' |
|
313 | fmt = '-%0' + width_dh +'d [%s]' | |
314 | ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['_dh'])] |
|
314 | ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['_dh'])] | |
315 | if len(ents) > 1: |
|
315 | if len(ents) > 1: | |
316 | return ents |
|
316 | return ents | |
317 | return [] |
|
317 | return [] | |
318 |
|
318 | |||
319 | if relpath.startswith('~'): |
|
319 | if relpath.startswith('~'): | |
320 | relpath = os.path.expanduser(relpath).replace('\\','/') |
|
320 | relpath = os.path.expanduser(relpath).replace('\\','/') | |
321 | found = [] |
|
321 | found = [] | |
322 | for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*') |
|
322 | for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*') | |
323 | if os.path.isdir(f)]: |
|
323 | if os.path.isdir(f)]: | |
324 | if ' ' in d: |
|
324 | if ' ' in d: | |
325 | # we don't want to deal with any of that, complex code |
|
325 | # we don't want to deal with any of that, complex code | |
326 | # for this is elsewhere |
|
326 | # for this is elsewhere | |
327 | raise IPython.ipapi.TryNext |
|
327 | raise IPython.ipapi.TryNext | |
328 | found.append( d ) |
|
328 | found.append( d ) | |
329 |
|
329 | |||
330 | if not found: |
|
330 | if not found: | |
331 | if os.path.isdir(relpath): |
|
331 | if os.path.isdir(relpath): | |
332 | return [relpath] |
|
332 | return [relpath] | |
333 | raise IPython.ipapi.TryNext |
|
333 | raise IPython.ipapi.TryNext | |
334 | return found |
|
334 | ||
|
335 | ||||
|
336 | def single_dir_expand(matches): | |||
|
337 | "Recursively expand match lists containing a single dir." | |||
|
338 | ||||
|
339 | if len(matches) == 1 and os.path.isdir(matches[0]): | |||
|
340 | # Takes care of links to directories also. Use '/' | |||
|
341 | # explicitly, even under Windows, so that name completions | |||
|
342 | # don't end up escaped. | |||
|
343 | d = matches[0] | |||
|
344 | if d[-1] in ['/','\\']: | |||
|
345 | d = d[:-1] | |||
|
346 | ||||
|
347 | subdirs = [p for p in os.listdir(d) if os.path.isdir( d + '/' + p)] | |||
|
348 | if subdirs: | |||
|
349 | matches = [ (d + '/' + p) for p in subdirs ] | |||
|
350 | return single_dir_expand(matches) | |||
|
351 | else: | |||
|
352 | return matches | |||
|
353 | else: | |||
|
354 | return matches | |||
|
355 | ||||
|
356 | return single_dir_expand(found) | |||
335 |
|
357 | |||
336 | def apt_get_packages(prefix): |
|
358 | def apt_get_packages(prefix): | |
337 | out = os.popen('apt-cache pkgnames') |
|
359 | out = os.popen('apt-cache pkgnames') | |
338 | for p in out: |
|
360 | for p in out: | |
339 | if p.startswith(prefix): |
|
361 | if p.startswith(prefix): | |
340 | yield p.rstrip() |
|
362 | yield p.rstrip() | |
341 |
|
363 | |||
342 |
|
364 | |||
343 | apt_commands = """\ |
|
365 | apt_commands = """\ | |
344 | update upgrade install remove purge source build-dep dist-upgrade |
|
366 | update upgrade install remove purge source build-dep dist-upgrade | |
345 | dselect-upgrade clean autoclean check""" |
|
367 | dselect-upgrade clean autoclean check""" | |
346 |
|
368 | |||
347 | def apt_completer(self, event): |
|
369 | def apt_completer(self, event): | |
348 | """ Completer for apt-get (uses apt-cache internally) |
|
370 | """ Completer for apt-get (uses apt-cache internally) | |
349 |
|
371 | |||
350 | """ |
|
372 | """ | |
351 |
|
373 | |||
352 |
|
374 | |||
353 | cmd_param = event.line.split() |
|
375 | cmd_param = event.line.split() | |
354 | if event.line.endswith(' '): |
|
376 | if event.line.endswith(' '): | |
355 | cmd_param.append('') |
|
377 | cmd_param.append('') | |
356 |
|
378 | |||
357 | if cmd_param[0] == 'sudo': |
|
379 | if cmd_param[0] == 'sudo': | |
358 | cmd_param = cmd_param[1:] |
|
380 | cmd_param = cmd_param[1:] | |
359 |
|
381 | |||
360 | if len(cmd_param) == 2 or 'help' in cmd_param: |
|
382 | if len(cmd_param) == 2 or 'help' in cmd_param: | |
361 | return apt_commands.split() |
|
383 | return apt_commands.split() | |
362 |
|
384 | |||
363 | return list(apt_get_packages(event.symbol)) |
|
385 | return list(apt_get_packages(event.symbol)) | |
364 |
|
386 |
@@ -1,3311 +1,3311 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Magic functions for InteractiveShell. |
|
2 | """Magic functions for InteractiveShell. | |
3 |
|
3 | |||
4 | $Id: Magic.py 2996 2008-01-30 06:31:39Z fperez $""" |
|
4 | $Id: Magic.py 2996 2008-01-30 06:31:39Z fperez $""" | |
5 |
|
5 | |||
6 | #***************************************************************************** |
|
6 | #***************************************************************************** | |
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
8 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> |
|
8 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> | |
9 | # |
|
9 | # | |
10 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | # Distributed under the terms of the BSD License. The full license is in | |
11 | # the file COPYING, distributed as part of this software. |
|
11 | # the file COPYING, distributed as part of this software. | |
12 | #***************************************************************************** |
|
12 | #***************************************************************************** | |
13 |
|
13 | |||
14 | #**************************************************************************** |
|
14 | #**************************************************************************** | |
15 | # Modules and globals |
|
15 | # Modules and globals | |
16 |
|
16 | |||
17 | from IPython import Release |
|
17 | from IPython import Release | |
18 | __author__ = '%s <%s>\n%s <%s>' % \ |
|
18 | __author__ = '%s <%s>\n%s <%s>' % \ | |
19 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) |
|
19 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) | |
20 | __license__ = Release.license |
|
20 | __license__ = Release.license | |
21 |
|
21 | |||
22 | # Python standard modules |
|
22 | # Python standard modules | |
23 | import __builtin__ |
|
23 | import __builtin__ | |
24 | import bdb |
|
24 | import bdb | |
25 | import inspect |
|
25 | import inspect | |
26 | import os |
|
26 | import os | |
27 | import pdb |
|
27 | import pdb | |
28 | import pydoc |
|
28 | import pydoc | |
29 | import sys |
|
29 | import sys | |
30 | import re |
|
30 | import re | |
31 | import tempfile |
|
31 | import tempfile | |
32 | import time |
|
32 | import time | |
33 | import cPickle as pickle |
|
33 | import cPickle as pickle | |
34 | import textwrap |
|
34 | import textwrap | |
35 | from cStringIO import StringIO |
|
35 | from cStringIO import StringIO | |
36 | from getopt import getopt,GetoptError |
|
36 | from getopt import getopt,GetoptError | |
37 | from pprint import pprint, pformat |
|
37 | from pprint import pprint, pformat | |
38 | from sets import Set |
|
38 | from sets import Set | |
39 |
|
39 | |||
40 | # cProfile was added in Python2.5 |
|
40 | # cProfile was added in Python2.5 | |
41 | try: |
|
41 | try: | |
42 | import cProfile as profile |
|
42 | import cProfile as profile | |
43 | import pstats |
|
43 | import pstats | |
44 | except ImportError: |
|
44 | except ImportError: | |
45 | # profile isn't bundled by default in Debian for license reasons |
|
45 | # profile isn't bundled by default in Debian for license reasons | |
46 | try: |
|
46 | try: | |
47 | import profile,pstats |
|
47 | import profile,pstats | |
48 | except ImportError: |
|
48 | except ImportError: | |
49 | profile = pstats = None |
|
49 | profile = pstats = None | |
50 |
|
50 | |||
51 | # Homebrewed |
|
51 | # Homebrewed | |
52 | import IPython |
|
52 | import IPython | |
53 | from IPython import Debugger, OInspect, wildcard |
|
53 | from IPython import Debugger, OInspect, wildcard | |
54 | from IPython.FakeModule import FakeModule |
|
54 | from IPython.FakeModule import FakeModule | |
55 | from IPython.Itpl import Itpl, itpl, printpl,itplns |
|
55 | from IPython.Itpl import Itpl, itpl, printpl,itplns | |
56 | from IPython.PyColorize import Parser |
|
56 | from IPython.PyColorize import Parser | |
57 | from IPython.ipstruct import Struct |
|
57 | from IPython.ipstruct import Struct | |
58 | from IPython.macro import Macro |
|
58 | from IPython.macro import Macro | |
59 | from IPython.genutils import * |
|
59 | from IPython.genutils import * | |
60 | from IPython import platutils |
|
60 | from IPython import platutils | |
61 | import IPython.generics |
|
61 | import IPython.generics | |
62 | import IPython.ipapi |
|
62 | import IPython.ipapi | |
63 | from IPython.ipapi import UsageError |
|
63 | from IPython.ipapi import UsageError | |
64 | #*************************************************************************** |
|
64 | #*************************************************************************** | |
65 | # Utility functions |
|
65 | # Utility functions | |
66 | def on_off(tag): |
|
66 | def on_off(tag): | |
67 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
67 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
68 | return ['OFF','ON'][tag] |
|
68 | return ['OFF','ON'][tag] | |
69 |
|
69 | |||
70 | class Bunch: pass |
|
70 | class Bunch: pass | |
71 |
|
71 | |||
72 | def compress_dhist(dh): |
|
72 | def compress_dhist(dh): | |
73 | head, tail = dh[:-10], dh[-10:] |
|
73 | head, tail = dh[:-10], dh[-10:] | |
74 |
|
74 | |||
75 | newhead = [] |
|
75 | newhead = [] | |
76 | done = Set() |
|
76 | done = Set() | |
77 | for h in head: |
|
77 | for h in head: | |
78 | if h in done: |
|
78 | if h in done: | |
79 | continue |
|
79 | continue | |
80 | newhead.append(h) |
|
80 | newhead.append(h) | |
81 | done.add(h) |
|
81 | done.add(h) | |
82 |
|
82 | |||
83 | return newhead + tail |
|
83 | return newhead + tail | |
84 |
|
84 | |||
85 |
|
85 | |||
86 | #*************************************************************************** |
|
86 | #*************************************************************************** | |
87 | # Main class implementing Magic functionality |
|
87 | # Main class implementing Magic functionality | |
88 | class Magic: |
|
88 | class Magic: | |
89 | """Magic functions for InteractiveShell. |
|
89 | """Magic functions for InteractiveShell. | |
90 |
|
90 | |||
91 | Shell functions which can be reached as %function_name. All magic |
|
91 | Shell functions which can be reached as %function_name. All magic | |
92 | functions should accept a string, which they can parse for their own |
|
92 | functions should accept a string, which they can parse for their own | |
93 | needs. This can make some functions easier to type, eg `%cd ../` |
|
93 | needs. This can make some functions easier to type, eg `%cd ../` | |
94 | vs. `%cd("../")` |
|
94 | vs. `%cd("../")` | |
95 |
|
95 | |||
96 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
96 | ALL definitions MUST begin with the prefix magic_. The user won't need it | |
97 | at the command line, but it is is needed in the definition. """ |
|
97 | at the command line, but it is is needed in the definition. """ | |
98 |
|
98 | |||
99 | # class globals |
|
99 | # class globals | |
100 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
100 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', | |
101 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
101 | 'Automagic is ON, % prefix NOT needed for magic functions.'] | |
102 |
|
102 | |||
103 | #...................................................................... |
|
103 | #...................................................................... | |
104 | # some utility functions |
|
104 | # some utility functions | |
105 |
|
105 | |||
106 | def __init__(self,shell): |
|
106 | def __init__(self,shell): | |
107 |
|
107 | |||
108 | self.options_table = {} |
|
108 | self.options_table = {} | |
109 | if profile is None: |
|
109 | if profile is None: | |
110 | self.magic_prun = self.profile_missing_notice |
|
110 | self.magic_prun = self.profile_missing_notice | |
111 | self.shell = shell |
|
111 | self.shell = shell | |
112 |
|
112 | |||
113 | # namespace for holding state we may need |
|
113 | # namespace for holding state we may need | |
114 | self._magic_state = Bunch() |
|
114 | self._magic_state = Bunch() | |
115 |
|
115 | |||
116 | def profile_missing_notice(self, *args, **kwargs): |
|
116 | def profile_missing_notice(self, *args, **kwargs): | |
117 | error("""\ |
|
117 | error("""\ | |
118 | The profile module could not be found. It has been removed from the standard |
|
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 |
|
119 | python packages because of its non-free license. To use profiling, install the | |
120 | python-profiler package from non-free.""") |
|
120 | python-profiler package from non-free.""") | |
121 |
|
121 | |||
122 | def default_option(self,fn,optstr): |
|
122 | def default_option(self,fn,optstr): | |
123 | """Make an entry in the options_table for fn, with value optstr""" |
|
123 | """Make an entry in the options_table for fn, with value optstr""" | |
124 |
|
124 | |||
125 | if fn not in self.lsmagic(): |
|
125 | if fn not in self.lsmagic(): | |
126 | error("%s is not a magic function" % fn) |
|
126 | error("%s is not a magic function" % fn) | |
127 | self.options_table[fn] = optstr |
|
127 | self.options_table[fn] = optstr | |
128 |
|
128 | |||
129 | def lsmagic(self): |
|
129 | def lsmagic(self): | |
130 | """Return a list of currently available magic functions. |
|
130 | """Return a list of currently available magic functions. | |
131 |
|
131 | |||
132 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
132 | Gives a list of the bare names after mangling (['ls','cd', ...], not | |
133 | ['magic_ls','magic_cd',...]""" |
|
133 | ['magic_ls','magic_cd',...]""" | |
134 |
|
134 | |||
135 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
135 | # FIXME. This needs a cleanup, in the way the magics list is built. | |
136 |
|
136 | |||
137 | # magics in class definition |
|
137 | # magics in class definition | |
138 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
138 | class_magic = lambda fn: fn.startswith('magic_') and \ | |
139 | callable(Magic.__dict__[fn]) |
|
139 | callable(Magic.__dict__[fn]) | |
140 | # in instance namespace (run-time user additions) |
|
140 | # in instance namespace (run-time user additions) | |
141 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
141 | inst_magic = lambda fn: fn.startswith('magic_') and \ | |
142 | callable(self.__dict__[fn]) |
|
142 | callable(self.__dict__[fn]) | |
143 | # and bound magics by user (so they can access self): |
|
143 | # and bound magics by user (so they can access self): | |
144 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
144 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ | |
145 | callable(self.__class__.__dict__[fn]) |
|
145 | callable(self.__class__.__dict__[fn]) | |
146 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
146 | magics = filter(class_magic,Magic.__dict__.keys()) + \ | |
147 | filter(inst_magic,self.__dict__.keys()) + \ |
|
147 | filter(inst_magic,self.__dict__.keys()) + \ | |
148 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
148 | filter(inst_bound_magic,self.__class__.__dict__.keys()) | |
149 | out = [] |
|
149 | out = [] | |
150 | for fn in Set(magics): |
|
150 | for fn in Set(magics): | |
151 | out.append(fn.replace('magic_','',1)) |
|
151 | out.append(fn.replace('magic_','',1)) | |
152 | out.sort() |
|
152 | out.sort() | |
153 | return out |
|
153 | return out | |
154 |
|
154 | |||
155 | def extract_input_slices(self,slices,raw=False): |
|
155 | def extract_input_slices(self,slices,raw=False): | |
156 | """Return as a string a set of input history slices. |
|
156 | """Return as a string a set of input history slices. | |
157 |
|
157 | |||
158 | Inputs: |
|
158 | Inputs: | |
159 |
|
159 | |||
160 | - slices: the set of slices is given as a list of strings (like |
|
160 | - slices: the set of slices is given as a list of strings (like | |
161 | ['1','4:8','9'], since this function is for use by magic functions |
|
161 | ['1','4:8','9'], since this function is for use by magic functions | |
162 | which get their arguments as strings. |
|
162 | which get their arguments as strings. | |
163 |
|
163 | |||
164 | Optional inputs: |
|
164 | Optional inputs: | |
165 |
|
165 | |||
166 | - raw(False): by default, the processed input is used. If this is |
|
166 | - raw(False): by default, the processed input is used. If this is | |
167 | true, the raw input history is used instead. |
|
167 | true, the raw input history is used instead. | |
168 |
|
168 | |||
169 | Note that slices can be called with two notations: |
|
169 | Note that slices can be called with two notations: | |
170 |
|
170 | |||
171 | N:M -> standard python form, means including items N...(M-1). |
|
171 | N:M -> standard python form, means including items N...(M-1). | |
172 |
|
172 | |||
173 | N-M -> include items N..M (closed endpoint).""" |
|
173 | N-M -> include items N..M (closed endpoint).""" | |
174 |
|
174 | |||
175 | if raw: |
|
175 | if raw: | |
176 | hist = self.shell.input_hist_raw |
|
176 | hist = self.shell.input_hist_raw | |
177 | else: |
|
177 | else: | |
178 | hist = self.shell.input_hist |
|
178 | hist = self.shell.input_hist | |
179 |
|
179 | |||
180 | cmds = [] |
|
180 | cmds = [] | |
181 | for chunk in slices: |
|
181 | for chunk in slices: | |
182 | if ':' in chunk: |
|
182 | if ':' in chunk: | |
183 | ini,fin = map(int,chunk.split(':')) |
|
183 | ini,fin = map(int,chunk.split(':')) | |
184 | elif '-' in chunk: |
|
184 | elif '-' in chunk: | |
185 | ini,fin = map(int,chunk.split('-')) |
|
185 | ini,fin = map(int,chunk.split('-')) | |
186 | fin += 1 |
|
186 | fin += 1 | |
187 | else: |
|
187 | else: | |
188 | ini = int(chunk) |
|
188 | ini = int(chunk) | |
189 | fin = ini+1 |
|
189 | fin = ini+1 | |
190 | cmds.append(hist[ini:fin]) |
|
190 | cmds.append(hist[ini:fin]) | |
191 | return cmds |
|
191 | return cmds | |
192 |
|
192 | |||
193 | def _ofind(self, oname, namespaces=None): |
|
193 | def _ofind(self, oname, namespaces=None): | |
194 | """Find an object in the available namespaces. |
|
194 | """Find an object in the available namespaces. | |
195 |
|
195 | |||
196 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
196 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
197 |
|
197 | |||
198 | Has special code to detect magic functions. |
|
198 | Has special code to detect magic functions. | |
199 | """ |
|
199 | """ | |
200 |
|
200 | |||
201 | oname = oname.strip() |
|
201 | oname = oname.strip() | |
202 |
|
202 | |||
203 | alias_ns = None |
|
203 | alias_ns = None | |
204 | if namespaces is None: |
|
204 | if namespaces is None: | |
205 | # Namespaces to search in: |
|
205 | # Namespaces to search in: | |
206 | # Put them in a list. The order is important so that we |
|
206 | # Put them in a list. The order is important so that we | |
207 | # find things in the same order that Python finds them. |
|
207 | # find things in the same order that Python finds them. | |
208 | namespaces = [ ('Interactive', self.shell.user_ns), |
|
208 | namespaces = [ ('Interactive', self.shell.user_ns), | |
209 | ('IPython internal', self.shell.internal_ns), |
|
209 | ('IPython internal', self.shell.internal_ns), | |
210 | ('Python builtin', __builtin__.__dict__), |
|
210 | ('Python builtin', __builtin__.__dict__), | |
211 | ('Alias', self.shell.alias_table), |
|
211 | ('Alias', self.shell.alias_table), | |
212 | ] |
|
212 | ] | |
213 | alias_ns = self.shell.alias_table |
|
213 | alias_ns = self.shell.alias_table | |
214 |
|
214 | |||
215 | # initialize results to 'null' |
|
215 | # initialize results to 'null' | |
216 | found = 0; obj = None; ospace = None; ds = None; |
|
216 | found = 0; obj = None; ospace = None; ds = None; | |
217 | ismagic = 0; isalias = 0; parent = None |
|
217 | ismagic = 0; isalias = 0; parent = None | |
218 |
|
218 | |||
219 | # Look for the given name by splitting it in parts. If the head is |
|
219 | # Look for the given name by splitting it in parts. If the head is | |
220 | # found, then we look for all the remaining parts as members, and only |
|
220 | # found, then we look for all the remaining parts as members, and only | |
221 | # declare success if we can find them all. |
|
221 | # declare success if we can find them all. | |
222 | oname_parts = oname.split('.') |
|
222 | oname_parts = oname.split('.') | |
223 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
223 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
224 | for nsname,ns in namespaces: |
|
224 | for nsname,ns in namespaces: | |
225 | try: |
|
225 | try: | |
226 | obj = ns[oname_head] |
|
226 | obj = ns[oname_head] | |
227 | except KeyError: |
|
227 | except KeyError: | |
228 | continue |
|
228 | continue | |
229 | else: |
|
229 | else: | |
230 | #print 'oname_rest:', oname_rest # dbg |
|
230 | #print 'oname_rest:', oname_rest # dbg | |
231 | for part in oname_rest: |
|
231 | for part in oname_rest: | |
232 | try: |
|
232 | try: | |
233 | parent = obj |
|
233 | parent = obj | |
234 | obj = getattr(obj,part) |
|
234 | obj = getattr(obj,part) | |
235 | except: |
|
235 | except: | |
236 | # Blanket except b/c some badly implemented objects |
|
236 | # Blanket except b/c some badly implemented objects | |
237 | # allow __getattr__ to raise exceptions other than |
|
237 | # allow __getattr__ to raise exceptions other than | |
238 | # AttributeError, which then crashes IPython. |
|
238 | # AttributeError, which then crashes IPython. | |
239 | break |
|
239 | break | |
240 | else: |
|
240 | else: | |
241 | # If we finish the for loop (no break), we got all members |
|
241 | # If we finish the for loop (no break), we got all members | |
242 | found = 1 |
|
242 | found = 1 | |
243 | ospace = nsname |
|
243 | ospace = nsname | |
244 | if ns == alias_ns: |
|
244 | if ns == alias_ns: | |
245 | isalias = 1 |
|
245 | isalias = 1 | |
246 | break # namespace loop |
|
246 | break # namespace loop | |
247 |
|
247 | |||
248 | # Try to see if it's magic |
|
248 | # Try to see if it's magic | |
249 | if not found: |
|
249 | if not found: | |
250 | if oname.startswith(self.shell.ESC_MAGIC): |
|
250 | if oname.startswith(self.shell.ESC_MAGIC): | |
251 | oname = oname[1:] |
|
251 | oname = oname[1:] | |
252 | obj = getattr(self,'magic_'+oname,None) |
|
252 | obj = getattr(self,'magic_'+oname,None) | |
253 | if obj is not None: |
|
253 | if obj is not None: | |
254 | found = 1 |
|
254 | found = 1 | |
255 | ospace = 'IPython internal' |
|
255 | ospace = 'IPython internal' | |
256 | ismagic = 1 |
|
256 | ismagic = 1 | |
257 |
|
257 | |||
258 | # Last try: special-case some literals like '', [], {}, etc: |
|
258 | # Last try: special-case some literals like '', [], {}, etc: | |
259 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
259 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
260 | obj = eval(oname_head) |
|
260 | obj = eval(oname_head) | |
261 | found = 1 |
|
261 | found = 1 | |
262 | ospace = 'Interactive' |
|
262 | ospace = 'Interactive' | |
263 |
|
263 | |||
264 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
264 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
265 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
265 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
266 |
|
266 | |||
267 | def arg_err(self,func): |
|
267 | def arg_err(self,func): | |
268 | """Print docstring if incorrect arguments were passed""" |
|
268 | """Print docstring if incorrect arguments were passed""" | |
269 | print 'Error in arguments:' |
|
269 | print 'Error in arguments:' | |
270 | print OInspect.getdoc(func) |
|
270 | print OInspect.getdoc(func) | |
271 |
|
271 | |||
272 | def format_latex(self,strng): |
|
272 | def format_latex(self,strng): | |
273 | """Format a string for latex inclusion.""" |
|
273 | """Format a string for latex inclusion.""" | |
274 |
|
274 | |||
275 | # Characters that need to be escaped for latex: |
|
275 | # Characters that need to be escaped for latex: | |
276 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
276 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) | |
277 | # Magic command names as headers: |
|
277 | # Magic command names as headers: | |
278 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, |
|
278 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, | |
279 | re.MULTILINE) |
|
279 | re.MULTILINE) | |
280 | # Magic commands |
|
280 | # Magic commands | |
281 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, |
|
281 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, | |
282 | re.MULTILINE) |
|
282 | re.MULTILINE) | |
283 | # Paragraph continue |
|
283 | # Paragraph continue | |
284 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
284 | par_re = re.compile(r'\\$',re.MULTILINE) | |
285 |
|
285 | |||
286 | # The "\n" symbol |
|
286 | # The "\n" symbol | |
287 | newline_re = re.compile(r'\\n') |
|
287 | newline_re = re.compile(r'\\n') | |
288 |
|
288 | |||
289 | # Now build the string for output: |
|
289 | # Now build the string for output: | |
290 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
290 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) | |
291 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
291 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', | |
292 | strng) |
|
292 | strng) | |
293 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
293 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) | |
294 | strng = par_re.sub(r'\\\\',strng) |
|
294 | strng = par_re.sub(r'\\\\',strng) | |
295 | strng = escape_re.sub(r'\\\1',strng) |
|
295 | strng = escape_re.sub(r'\\\1',strng) | |
296 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
296 | strng = newline_re.sub(r'\\textbackslash{}n',strng) | |
297 | return strng |
|
297 | return strng | |
298 |
|
298 | |||
299 | def format_screen(self,strng): |
|
299 | def format_screen(self,strng): | |
300 | """Format a string for screen printing. |
|
300 | """Format a string for screen printing. | |
301 |
|
301 | |||
302 | This removes some latex-type format codes.""" |
|
302 | This removes some latex-type format codes.""" | |
303 | # Paragraph continue |
|
303 | # Paragraph continue | |
304 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
304 | par_re = re.compile(r'\\$',re.MULTILINE) | |
305 | strng = par_re.sub('',strng) |
|
305 | strng = par_re.sub('',strng) | |
306 | return strng |
|
306 | return strng | |
307 |
|
307 | |||
308 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
308 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): | |
309 | """Parse options passed to an argument string. |
|
309 | """Parse options passed to an argument string. | |
310 |
|
310 | |||
311 | The interface is similar to that of getopt(), but it returns back a |
|
311 | The interface is similar to that of getopt(), but it returns back a | |
312 | Struct with the options as keys and the stripped argument string still |
|
312 | Struct with the options as keys and the stripped argument string still | |
313 | as a string. |
|
313 | as a string. | |
314 |
|
314 | |||
315 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
315 | arg_str is quoted as a true sys.argv vector by using shlex.split. | |
316 | This allows us to easily expand variables, glob files, quote |
|
316 | This allows us to easily expand variables, glob files, quote | |
317 | arguments, etc. |
|
317 | arguments, etc. | |
318 |
|
318 | |||
319 | Options: |
|
319 | Options: | |
320 | -mode: default 'string'. If given as 'list', the argument string is |
|
320 | -mode: default 'string'. If given as 'list', the argument string is | |
321 | returned as a list (split on whitespace) instead of a string. |
|
321 | returned as a list (split on whitespace) instead of a string. | |
322 |
|
322 | |||
323 | -list_all: put all option values in lists. Normally only options |
|
323 | -list_all: put all option values in lists. Normally only options | |
324 | appearing more than once are put in a list. |
|
324 | appearing more than once are put in a list. | |
325 |
|
325 | |||
326 | -posix (True): whether to split the input line in POSIX mode or not, |
|
326 | -posix (True): whether to split the input line in POSIX mode or not, | |
327 | as per the conventions outlined in the shlex module from the |
|
327 | as per the conventions outlined in the shlex module from the | |
328 | standard library.""" |
|
328 | standard library.""" | |
329 |
|
329 | |||
330 | # inject default options at the beginning of the input line |
|
330 | # inject default options at the beginning of the input line | |
331 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
331 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') | |
332 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
332 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
333 |
|
333 | |||
334 | mode = kw.get('mode','string') |
|
334 | mode = kw.get('mode','string') | |
335 | if mode not in ['string','list']: |
|
335 | if mode not in ['string','list']: | |
336 | raise ValueError,'incorrect mode given: %s' % mode |
|
336 | raise ValueError,'incorrect mode given: %s' % mode | |
337 | # Get options |
|
337 | # Get options | |
338 | list_all = kw.get('list_all',0) |
|
338 | list_all = kw.get('list_all',0) | |
339 | posix = kw.get('posix',True) |
|
339 | posix = kw.get('posix',True) | |
340 |
|
340 | |||
341 | # Check if we have more than one argument to warrant extra processing: |
|
341 | # Check if we have more than one argument to warrant extra processing: | |
342 | odict = {} # Dictionary with options |
|
342 | odict = {} # Dictionary with options | |
343 | args = arg_str.split() |
|
343 | args = arg_str.split() | |
344 | if len(args) >= 1: |
|
344 | if len(args) >= 1: | |
345 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
345 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
346 | # need to look for options |
|
346 | # need to look for options | |
347 | argv = arg_split(arg_str,posix) |
|
347 | argv = arg_split(arg_str,posix) | |
348 | # Do regular option processing |
|
348 | # Do regular option processing | |
349 | try: |
|
349 | try: | |
350 | opts,args = getopt(argv,opt_str,*long_opts) |
|
350 | opts,args = getopt(argv,opt_str,*long_opts) | |
351 | except GetoptError,e: |
|
351 | except GetoptError,e: | |
352 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
352 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, | |
353 | " ".join(long_opts))) |
|
353 | " ".join(long_opts))) | |
354 | for o,a in opts: |
|
354 | for o,a in opts: | |
355 | if o.startswith('--'): |
|
355 | if o.startswith('--'): | |
356 | o = o[2:] |
|
356 | o = o[2:] | |
357 | else: |
|
357 | else: | |
358 | o = o[1:] |
|
358 | o = o[1:] | |
359 | try: |
|
359 | try: | |
360 | odict[o].append(a) |
|
360 | odict[o].append(a) | |
361 | except AttributeError: |
|
361 | except AttributeError: | |
362 | odict[o] = [odict[o],a] |
|
362 | odict[o] = [odict[o],a] | |
363 | except KeyError: |
|
363 | except KeyError: | |
364 | if list_all: |
|
364 | if list_all: | |
365 | odict[o] = [a] |
|
365 | odict[o] = [a] | |
366 | else: |
|
366 | else: | |
367 | odict[o] = a |
|
367 | odict[o] = a | |
368 |
|
368 | |||
369 | # Prepare opts,args for return |
|
369 | # Prepare opts,args for return | |
370 | opts = Struct(odict) |
|
370 | opts = Struct(odict) | |
371 | if mode == 'string': |
|
371 | if mode == 'string': | |
372 | args = ' '.join(args) |
|
372 | args = ' '.join(args) | |
373 |
|
373 | |||
374 | return opts,args |
|
374 | return opts,args | |
375 |
|
375 | |||
376 | #...................................................................... |
|
376 | #...................................................................... | |
377 | # And now the actual magic functions |
|
377 | # And now the actual magic functions | |
378 |
|
378 | |||
379 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
379 | # Functions for IPython shell work (vars,funcs, config, etc) | |
380 | def magic_lsmagic(self, parameter_s = ''): |
|
380 | def magic_lsmagic(self, parameter_s = ''): | |
381 | """List currently available magic functions.""" |
|
381 | """List currently available magic functions.""" | |
382 | mesc = self.shell.ESC_MAGIC |
|
382 | mesc = self.shell.ESC_MAGIC | |
383 | print 'Available magic functions:\n'+mesc+\ |
|
383 | print 'Available magic functions:\n'+mesc+\ | |
384 | (' '+mesc).join(self.lsmagic()) |
|
384 | (' '+mesc).join(self.lsmagic()) | |
385 | print '\n' + Magic.auto_status[self.shell.rc.automagic] |
|
385 | print '\n' + Magic.auto_status[self.shell.rc.automagic] | |
386 | return None |
|
386 | return None | |
387 |
|
387 | |||
388 | def magic_magic(self, parameter_s = ''): |
|
388 | def magic_magic(self, parameter_s = ''): | |
389 | """Print information about the magic function system. |
|
389 | """Print information about the magic function system. | |
390 |
|
390 | |||
391 | Supported formats: -latex, -brief, -rest |
|
391 | Supported formats: -latex, -brief, -rest | |
392 | """ |
|
392 | """ | |
393 |
|
393 | |||
394 | mode = '' |
|
394 | mode = '' | |
395 | try: |
|
395 | try: | |
396 | if parameter_s.split()[0] == '-latex': |
|
396 | if parameter_s.split()[0] == '-latex': | |
397 | mode = 'latex' |
|
397 | mode = 'latex' | |
398 | if parameter_s.split()[0] == '-brief': |
|
398 | if parameter_s.split()[0] == '-brief': | |
399 | mode = 'brief' |
|
399 | mode = 'brief' | |
400 | if parameter_s.split()[0] == '-rest': |
|
400 | if parameter_s.split()[0] == '-rest': | |
401 | mode = 'rest' |
|
401 | mode = 'rest' | |
402 | rest_docs = [] |
|
402 | rest_docs = [] | |
403 | except: |
|
403 | except: | |
404 | pass |
|
404 | pass | |
405 |
|
405 | |||
406 | magic_docs = [] |
|
406 | magic_docs = [] | |
407 | for fname in self.lsmagic(): |
|
407 | for fname in self.lsmagic(): | |
408 | mname = 'magic_' + fname |
|
408 | mname = 'magic_' + fname | |
409 | for space in (Magic,self,self.__class__): |
|
409 | for space in (Magic,self,self.__class__): | |
410 | try: |
|
410 | try: | |
411 | fn = space.__dict__[mname] |
|
411 | fn = space.__dict__[mname] | |
412 | except KeyError: |
|
412 | except KeyError: | |
413 | pass |
|
413 | pass | |
414 | else: |
|
414 | else: | |
415 | break |
|
415 | break | |
416 | if mode == 'brief': |
|
416 | if mode == 'brief': | |
417 | # only first line |
|
417 | # only first line | |
418 | if fn.__doc__: |
|
418 | if fn.__doc__: | |
419 | fndoc = fn.__doc__.split('\n',1)[0] |
|
419 | fndoc = fn.__doc__.split('\n',1)[0] | |
420 | else: |
|
420 | else: | |
421 | fndoc = 'No documentation' |
|
421 | fndoc = 'No documentation' | |
422 | else: |
|
422 | else: | |
423 | fndoc = fn.__doc__.rstrip() |
|
423 | fndoc = fn.__doc__.rstrip() | |
424 |
|
424 | |||
425 | if mode == 'rest': |
|
425 | if mode == 'rest': | |
426 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC, |
|
426 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC, | |
427 | fname,fndoc)) |
|
427 | fname,fndoc)) | |
428 |
|
428 | |||
429 | else: |
|
429 | else: | |
430 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, |
|
430 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, | |
431 | fname,fndoc)) |
|
431 | fname,fndoc)) | |
432 |
|
432 | |||
433 | magic_docs = ''.join(magic_docs) |
|
433 | magic_docs = ''.join(magic_docs) | |
434 |
|
434 | |||
435 | if mode == 'rest': |
|
435 | if mode == 'rest': | |
436 | return "".join(rest_docs) |
|
436 | return "".join(rest_docs) | |
437 |
|
437 | |||
438 | if mode == 'latex': |
|
438 | if mode == 'latex': | |
439 | print self.format_latex(magic_docs) |
|
439 | print self.format_latex(magic_docs) | |
440 | return |
|
440 | return | |
441 | else: |
|
441 | else: | |
442 | magic_docs = self.format_screen(magic_docs) |
|
442 | magic_docs = self.format_screen(magic_docs) | |
443 | if mode == 'brief': |
|
443 | if mode == 'brief': | |
444 | return magic_docs |
|
444 | return magic_docs | |
445 |
|
445 | |||
446 | outmsg = """ |
|
446 | outmsg = """ | |
447 | IPython's 'magic' functions |
|
447 | IPython's 'magic' functions | |
448 | =========================== |
|
448 | =========================== | |
449 |
|
449 | |||
450 | The magic function system provides a series of functions which allow you to |
|
450 | The magic function system provides a series of functions which allow you to | |
451 | control the behavior of IPython itself, plus a lot of system-type |
|
451 | control the behavior of IPython itself, plus a lot of system-type | |
452 | features. All these functions are prefixed with a % character, but parameters |
|
452 | features. All these functions are prefixed with a % character, but parameters | |
453 | are given without parentheses or quotes. |
|
453 | are given without parentheses or quotes. | |
454 |
|
454 | |||
455 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
455 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
456 | %automagic function), you don't need to type in the % explicitly. By default, |
|
456 | %automagic function), you don't need to type in the % explicitly. By default, | |
457 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
457 | IPython ships with automagic on, so you should only rarely need the % escape. | |
458 |
|
458 | |||
459 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
459 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
460 | to 'mydir', if it exists. |
|
460 | to 'mydir', if it exists. | |
461 |
|
461 | |||
462 | You can define your own magic functions to extend the system. See the supplied |
|
462 | You can define your own magic functions to extend the system. See the supplied | |
463 | ipythonrc and example-magic.py files for details (in your ipython |
|
463 | ipythonrc and example-magic.py files for details (in your ipython | |
464 | configuration directory, typically $HOME/.ipython/). |
|
464 | configuration directory, typically $HOME/.ipython/). | |
465 |
|
465 | |||
466 | You can also define your own aliased names for magic functions. In your |
|
466 | You can also define your own aliased names for magic functions. In your | |
467 | ipythonrc file, placing a line like: |
|
467 | ipythonrc file, placing a line like: | |
468 |
|
468 | |||
469 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
469 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile | |
470 |
|
470 | |||
471 | will define %pf as a new name for %profile. |
|
471 | will define %pf as a new name for %profile. | |
472 |
|
472 | |||
473 | You can also call magics in code using the ipmagic() function, which IPython |
|
473 | You can also call magics in code using the ipmagic() function, which IPython | |
474 | automatically adds to the builtin namespace. Type 'ipmagic?' for details. |
|
474 | automatically adds to the builtin namespace. Type 'ipmagic?' for details. | |
475 |
|
475 | |||
476 | For a list of the available magic functions, use %lsmagic. For a description |
|
476 | For a list of the available magic functions, use %lsmagic. For a description | |
477 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
477 | of any of them, type %magic_name?, e.g. '%cd?'. | |
478 |
|
478 | |||
479 | Currently the magic system has the following functions:\n""" |
|
479 | Currently the magic system has the following functions:\n""" | |
480 |
|
480 | |||
481 | mesc = self.shell.ESC_MAGIC |
|
481 | mesc = self.shell.ESC_MAGIC | |
482 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
482 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" | |
483 | "\n\n%s%s\n\n%s" % (outmsg, |
|
483 | "\n\n%s%s\n\n%s" % (outmsg, | |
484 | magic_docs,mesc,mesc, |
|
484 | magic_docs,mesc,mesc, | |
485 | (' '+mesc).join(self.lsmagic()), |
|
485 | (' '+mesc).join(self.lsmagic()), | |
486 | Magic.auto_status[self.shell.rc.automagic] ) ) |
|
486 | Magic.auto_status[self.shell.rc.automagic] ) ) | |
487 |
|
487 | |||
488 | page(outmsg,screen_lines=self.shell.rc.screen_length) |
|
488 | page(outmsg,screen_lines=self.shell.rc.screen_length) | |
489 |
|
489 | |||
490 |
|
490 | |||
491 | def magic_autoindent(self, parameter_s = ''): |
|
491 | def magic_autoindent(self, parameter_s = ''): | |
492 | """Toggle autoindent on/off (if available).""" |
|
492 | """Toggle autoindent on/off (if available).""" | |
493 |
|
493 | |||
494 | self.shell.set_autoindent() |
|
494 | self.shell.set_autoindent() | |
495 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
495 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] | |
496 |
|
496 | |||
497 |
|
497 | |||
498 | def magic_automagic(self, parameter_s = ''): |
|
498 | def magic_automagic(self, parameter_s = ''): | |
499 | """Make magic functions callable without having to type the initial %. |
|
499 | """Make magic functions callable without having to type the initial %. | |
500 |
|
500 | |||
501 | Without argumentsl toggles on/off (when off, you must call it as |
|
501 | Without argumentsl toggles on/off (when off, you must call it as | |
502 | %automagic, of course). With arguments it sets the value, and you can |
|
502 | %automagic, of course). With arguments it sets the value, and you can | |
503 | use any of (case insensitive): |
|
503 | use any of (case insensitive): | |
504 |
|
504 | |||
505 | - on,1,True: to activate |
|
505 | - on,1,True: to activate | |
506 |
|
506 | |||
507 | - off,0,False: to deactivate. |
|
507 | - off,0,False: to deactivate. | |
508 |
|
508 | |||
509 | Note that magic functions have lowest priority, so if there's a |
|
509 | Note that magic functions have lowest priority, so if there's a | |
510 | variable whose name collides with that of a magic fn, automagic won't |
|
510 | variable whose name collides with that of a magic fn, automagic won't | |
511 | work for that function (you get the variable instead). However, if you |
|
511 | work for that function (you get the variable instead). However, if you | |
512 | delete the variable (del var), the previously shadowed magic function |
|
512 | delete the variable (del var), the previously shadowed magic function | |
513 | becomes visible to automagic again.""" |
|
513 | becomes visible to automagic again.""" | |
514 |
|
514 | |||
515 | rc = self.shell.rc |
|
515 | rc = self.shell.rc | |
516 | arg = parameter_s.lower() |
|
516 | arg = parameter_s.lower() | |
517 | if parameter_s in ('on','1','true'): |
|
517 | if parameter_s in ('on','1','true'): | |
518 | rc.automagic = True |
|
518 | rc.automagic = True | |
519 | elif parameter_s in ('off','0','false'): |
|
519 | elif parameter_s in ('off','0','false'): | |
520 | rc.automagic = False |
|
520 | rc.automagic = False | |
521 | else: |
|
521 | else: | |
522 | rc.automagic = not rc.automagic |
|
522 | rc.automagic = not rc.automagic | |
523 | print '\n' + Magic.auto_status[rc.automagic] |
|
523 | print '\n' + Magic.auto_status[rc.automagic] | |
524 |
|
524 | |||
525 |
|
525 | |||
526 | def magic_autocall(self, parameter_s = ''): |
|
526 | def magic_autocall(self, parameter_s = ''): | |
527 | """Make functions callable without having to type parentheses. |
|
527 | """Make functions callable without having to type parentheses. | |
528 |
|
528 | |||
529 | Usage: |
|
529 | Usage: | |
530 |
|
530 | |||
531 | %autocall [mode] |
|
531 | %autocall [mode] | |
532 |
|
532 | |||
533 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
533 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the | |
534 | value is toggled on and off (remembering the previous state). |
|
534 | value is toggled on and off (remembering the previous state). | |
535 |
|
535 | |||
536 | In more detail, these values mean: |
|
536 | In more detail, these values mean: | |
537 |
|
537 | |||
538 | 0 -> fully disabled |
|
538 | 0 -> fully disabled | |
539 |
|
539 | |||
540 | 1 -> active, but do not apply if there are no arguments on the line. |
|
540 | 1 -> active, but do not apply if there are no arguments on the line. | |
541 |
|
541 | |||
542 | In this mode, you get: |
|
542 | In this mode, you get: | |
543 |
|
543 | |||
544 | In [1]: callable |
|
544 | In [1]: callable | |
545 | Out[1]: <built-in function callable> |
|
545 | Out[1]: <built-in function callable> | |
546 |
|
546 | |||
547 | In [2]: callable 'hello' |
|
547 | In [2]: callable 'hello' | |
548 | ------> callable('hello') |
|
548 | ------> callable('hello') | |
549 | Out[2]: False |
|
549 | Out[2]: False | |
550 |
|
550 | |||
551 | 2 -> Active always. Even if no arguments are present, the callable |
|
551 | 2 -> Active always. Even if no arguments are present, the callable | |
552 | object is called: |
|
552 | object is called: | |
553 |
|
553 | |||
554 | In [4]: callable |
|
554 | In [4]: callable | |
555 | ------> callable() |
|
555 | ------> callable() | |
556 |
|
556 | |||
557 | Note that even with autocall off, you can still use '/' at the start of |
|
557 | Note that even with autocall off, you can still use '/' at the start of | |
558 | a line to treat the first argument on the command line as a function |
|
558 | a line to treat the first argument on the command line as a function | |
559 | and add parentheses to it: |
|
559 | and add parentheses to it: | |
560 |
|
560 | |||
561 | In [8]: /str 43 |
|
561 | In [8]: /str 43 | |
562 | ------> str(43) |
|
562 | ------> str(43) | |
563 | Out[8]: '43' |
|
563 | Out[8]: '43' | |
564 | """ |
|
564 | """ | |
565 |
|
565 | |||
566 | rc = self.shell.rc |
|
566 | rc = self.shell.rc | |
567 |
|
567 | |||
568 | if parameter_s: |
|
568 | if parameter_s: | |
569 | arg = int(parameter_s) |
|
569 | arg = int(parameter_s) | |
570 | else: |
|
570 | else: | |
571 | arg = 'toggle' |
|
571 | arg = 'toggle' | |
572 |
|
572 | |||
573 | if not arg in (0,1,2,'toggle'): |
|
573 | if not arg in (0,1,2,'toggle'): | |
574 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
574 | error('Valid modes: (0->Off, 1->Smart, 2->Full') | |
575 | return |
|
575 | return | |
576 |
|
576 | |||
577 | if arg in (0,1,2): |
|
577 | if arg in (0,1,2): | |
578 | rc.autocall = arg |
|
578 | rc.autocall = arg | |
579 | else: # toggle |
|
579 | else: # toggle | |
580 | if rc.autocall: |
|
580 | if rc.autocall: | |
581 | self._magic_state.autocall_save = rc.autocall |
|
581 | self._magic_state.autocall_save = rc.autocall | |
582 | rc.autocall = 0 |
|
582 | rc.autocall = 0 | |
583 | else: |
|
583 | else: | |
584 | try: |
|
584 | try: | |
585 | rc.autocall = self._magic_state.autocall_save |
|
585 | rc.autocall = self._magic_state.autocall_save | |
586 | except AttributeError: |
|
586 | except AttributeError: | |
587 | rc.autocall = self._magic_state.autocall_save = 1 |
|
587 | rc.autocall = self._magic_state.autocall_save = 1 | |
588 |
|
588 | |||
589 | print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall] |
|
589 | print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall] | |
590 |
|
590 | |||
591 | def magic_system_verbose(self, parameter_s = ''): |
|
591 | def magic_system_verbose(self, parameter_s = ''): | |
592 | """Set verbose printing of system calls. |
|
592 | """Set verbose printing of system calls. | |
593 |
|
593 | |||
594 | If called without an argument, act as a toggle""" |
|
594 | If called without an argument, act as a toggle""" | |
595 |
|
595 | |||
596 | if parameter_s: |
|
596 | if parameter_s: | |
597 | val = bool(eval(parameter_s)) |
|
597 | val = bool(eval(parameter_s)) | |
598 | else: |
|
598 | else: | |
599 | val = None |
|
599 | val = None | |
600 |
|
600 | |||
601 | self.shell.rc_set_toggle('system_verbose',val) |
|
601 | self.shell.rc_set_toggle('system_verbose',val) | |
602 | print "System verbose printing is:",\ |
|
602 | print "System verbose printing is:",\ | |
603 | ['OFF','ON'][self.shell.rc.system_verbose] |
|
603 | ['OFF','ON'][self.shell.rc.system_verbose] | |
604 |
|
604 | |||
605 |
|
605 | |||
606 | def magic_page(self, parameter_s=''): |
|
606 | def magic_page(self, parameter_s=''): | |
607 | """Pretty print the object and display it through a pager. |
|
607 | """Pretty print the object and display it through a pager. | |
608 |
|
608 | |||
609 | %page [options] OBJECT |
|
609 | %page [options] OBJECT | |
610 |
|
610 | |||
611 | If no object is given, use _ (last output). |
|
611 | If no object is given, use _ (last output). | |
612 |
|
612 | |||
613 | Options: |
|
613 | Options: | |
614 |
|
614 | |||
615 | -r: page str(object), don't pretty-print it.""" |
|
615 | -r: page str(object), don't pretty-print it.""" | |
616 |
|
616 | |||
617 | # After a function contributed by Olivier Aubert, slightly modified. |
|
617 | # After a function contributed by Olivier Aubert, slightly modified. | |
618 |
|
618 | |||
619 | # Process options/args |
|
619 | # Process options/args | |
620 | opts,args = self.parse_options(parameter_s,'r') |
|
620 | opts,args = self.parse_options(parameter_s,'r') | |
621 | raw = 'r' in opts |
|
621 | raw = 'r' in opts | |
622 |
|
622 | |||
623 | oname = args and args or '_' |
|
623 | oname = args and args or '_' | |
624 | info = self._ofind(oname) |
|
624 | info = self._ofind(oname) | |
625 | if info['found']: |
|
625 | if info['found']: | |
626 | txt = (raw and str or pformat)( info['obj'] ) |
|
626 | txt = (raw and str or pformat)( info['obj'] ) | |
627 | page(txt) |
|
627 | page(txt) | |
628 | else: |
|
628 | else: | |
629 | print 'Object `%s` not found' % oname |
|
629 | print 'Object `%s` not found' % oname | |
630 |
|
630 | |||
631 | def magic_profile(self, parameter_s=''): |
|
631 | def magic_profile(self, parameter_s=''): | |
632 | """Print your currently active IPyhton profile.""" |
|
632 | """Print your currently active IPyhton profile.""" | |
633 | if self.shell.rc.profile: |
|
633 | if self.shell.rc.profile: | |
634 | printpl('Current IPython profile: $self.shell.rc.profile.') |
|
634 | printpl('Current IPython profile: $self.shell.rc.profile.') | |
635 | else: |
|
635 | else: | |
636 | print 'No profile active.' |
|
636 | print 'No profile active.' | |
637 |
|
637 | |||
638 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
638 | def magic_pinfo(self, parameter_s='', namespaces=None): | |
639 | """Provide detailed information about an object. |
|
639 | """Provide detailed information about an object. | |
640 |
|
640 | |||
641 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
641 | '%pinfo object' is just a synonym for object? or ?object.""" | |
642 |
|
642 | |||
643 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
643 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
644 |
|
644 | |||
645 |
|
645 | |||
646 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
646 | # detail_level: 0 -> obj? , 1 -> obj?? | |
647 | detail_level = 0 |
|
647 | detail_level = 0 | |
648 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
648 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
649 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
649 | # happen if the user types 'pinfo foo?' at the cmd line. | |
650 | pinfo,qmark1,oname,qmark2 = \ |
|
650 | pinfo,qmark1,oname,qmark2 = \ | |
651 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
651 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
652 | if pinfo or qmark1 or qmark2: |
|
652 | if pinfo or qmark1 or qmark2: | |
653 | detail_level = 1 |
|
653 | detail_level = 1 | |
654 | if "*" in oname: |
|
654 | if "*" in oname: | |
655 | self.magic_psearch(oname) |
|
655 | self.magic_psearch(oname) | |
656 | else: |
|
656 | else: | |
657 | self._inspect('pinfo', oname, detail_level=detail_level, |
|
657 | self._inspect('pinfo', oname, detail_level=detail_level, | |
658 | namespaces=namespaces) |
|
658 | namespaces=namespaces) | |
659 |
|
659 | |||
660 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
660 | def magic_pdef(self, parameter_s='', namespaces=None): | |
661 | """Print the definition header for any callable object. |
|
661 | """Print the definition header for any callable object. | |
662 |
|
662 | |||
663 | If the object is a class, print the constructor information.""" |
|
663 | If the object is a class, print the constructor information.""" | |
664 | self._inspect('pdef',parameter_s, namespaces) |
|
664 | self._inspect('pdef',parameter_s, namespaces) | |
665 |
|
665 | |||
666 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
666 | def magic_pdoc(self, parameter_s='', namespaces=None): | |
667 | """Print the docstring for an object. |
|
667 | """Print the docstring for an object. | |
668 |
|
668 | |||
669 | If the given object is a class, it will print both the class and the |
|
669 | If the given object is a class, it will print both the class and the | |
670 | constructor docstrings.""" |
|
670 | constructor docstrings.""" | |
671 | self._inspect('pdoc',parameter_s, namespaces) |
|
671 | self._inspect('pdoc',parameter_s, namespaces) | |
672 |
|
672 | |||
673 | def magic_psource(self, parameter_s='', namespaces=None): |
|
673 | def magic_psource(self, parameter_s='', namespaces=None): | |
674 | """Print (or run through pager) the source code for an object.""" |
|
674 | """Print (or run through pager) the source code for an object.""" | |
675 | self._inspect('psource',parameter_s, namespaces) |
|
675 | self._inspect('psource',parameter_s, namespaces) | |
676 |
|
676 | |||
677 | def magic_pfile(self, parameter_s=''): |
|
677 | def magic_pfile(self, parameter_s=''): | |
678 | """Print (or run through pager) the file where an object is defined. |
|
678 | """Print (or run through pager) the file where an object is defined. | |
679 |
|
679 | |||
680 | The file opens at the line where the object definition begins. IPython |
|
680 | The file opens at the line where the object definition begins. IPython | |
681 | will honor the environment variable PAGER if set, and otherwise will |
|
681 | will honor the environment variable PAGER if set, and otherwise will | |
682 | do its best to print the file in a convenient form. |
|
682 | do its best to print the file in a convenient form. | |
683 |
|
683 | |||
684 | If the given argument is not an object currently defined, IPython will |
|
684 | If the given argument is not an object currently defined, IPython will | |
685 | try to interpret it as a filename (automatically adding a .py extension |
|
685 | try to interpret it as a filename (automatically adding a .py extension | |
686 | if needed). You can thus use %pfile as a syntax highlighting code |
|
686 | if needed). You can thus use %pfile as a syntax highlighting code | |
687 | viewer.""" |
|
687 | viewer.""" | |
688 |
|
688 | |||
689 | # first interpret argument as an object name |
|
689 | # first interpret argument as an object name | |
690 | out = self._inspect('pfile',parameter_s) |
|
690 | out = self._inspect('pfile',parameter_s) | |
691 | # if not, try the input as a filename |
|
691 | # if not, try the input as a filename | |
692 | if out == 'not found': |
|
692 | if out == 'not found': | |
693 | try: |
|
693 | try: | |
694 | filename = get_py_filename(parameter_s) |
|
694 | filename = get_py_filename(parameter_s) | |
695 | except IOError,msg: |
|
695 | except IOError,msg: | |
696 | print msg |
|
696 | print msg | |
697 | return |
|
697 | return | |
698 | page(self.shell.inspector.format(file(filename).read())) |
|
698 | page(self.shell.inspector.format(file(filename).read())) | |
699 |
|
699 | |||
700 | def _inspect(self,meth,oname,namespaces=None,**kw): |
|
700 | def _inspect(self,meth,oname,namespaces=None,**kw): | |
701 | """Generic interface to the inspector system. |
|
701 | """Generic interface to the inspector system. | |
702 |
|
702 | |||
703 | This function is meant to be called by pdef, pdoc & friends.""" |
|
703 | This function is meant to be called by pdef, pdoc & friends.""" | |
704 |
|
704 | |||
705 | #oname = oname.strip() |
|
705 | #oname = oname.strip() | |
706 | #print '1- oname: <%r>' % oname # dbg |
|
706 | #print '1- oname: <%r>' % oname # dbg | |
707 | try: |
|
707 | try: | |
708 | oname = oname.strip().encode('ascii') |
|
708 | oname = oname.strip().encode('ascii') | |
709 | #print '2- oname: <%r>' % oname # dbg |
|
709 | #print '2- oname: <%r>' % oname # dbg | |
710 | except UnicodeEncodeError: |
|
710 | except UnicodeEncodeError: | |
711 | print 'Python identifiers can only contain ascii characters.' |
|
711 | print 'Python identifiers can only contain ascii characters.' | |
712 | return 'not found' |
|
712 | return 'not found' | |
713 |
|
713 | |||
714 | info = Struct(self._ofind(oname, namespaces)) |
|
714 | info = Struct(self._ofind(oname, namespaces)) | |
715 |
|
715 | |||
716 | if info.found: |
|
716 | if info.found: | |
717 | try: |
|
717 | try: | |
718 | IPython.generics.inspect_object(info.obj) |
|
718 | IPython.generics.inspect_object(info.obj) | |
719 | return |
|
719 | return | |
720 | except IPython.ipapi.TryNext: |
|
720 | except IPython.ipapi.TryNext: | |
721 | pass |
|
721 | pass | |
722 | # Get the docstring of the class property if it exists. |
|
722 | # Get the docstring of the class property if it exists. | |
723 | path = oname.split('.') |
|
723 | path = oname.split('.') | |
724 | root = '.'.join(path[:-1]) |
|
724 | root = '.'.join(path[:-1]) | |
725 | if info.parent is not None: |
|
725 | if info.parent is not None: | |
726 | try: |
|
726 | try: | |
727 | target = getattr(info.parent, '__class__') |
|
727 | target = getattr(info.parent, '__class__') | |
728 | # The object belongs to a class instance. |
|
728 | # The object belongs to a class instance. | |
729 | try: |
|
729 | try: | |
730 | target = getattr(target, path[-1]) |
|
730 | target = getattr(target, path[-1]) | |
731 | # The class defines the object. |
|
731 | # The class defines the object. | |
732 | if isinstance(target, property): |
|
732 | if isinstance(target, property): | |
733 | oname = root + '.__class__.' + path[-1] |
|
733 | oname = root + '.__class__.' + path[-1] | |
734 | info = Struct(self._ofind(oname)) |
|
734 | info = Struct(self._ofind(oname)) | |
735 | except AttributeError: pass |
|
735 | except AttributeError: pass | |
736 | except AttributeError: pass |
|
736 | except AttributeError: pass | |
737 |
|
737 | |||
738 | pmethod = getattr(self.shell.inspector,meth) |
|
738 | pmethod = getattr(self.shell.inspector,meth) | |
739 | formatter = info.ismagic and self.format_screen or None |
|
739 | formatter = info.ismagic and self.format_screen or None | |
740 | if meth == 'pdoc': |
|
740 | if meth == 'pdoc': | |
741 | pmethod(info.obj,oname,formatter) |
|
741 | pmethod(info.obj,oname,formatter) | |
742 | elif meth == 'pinfo': |
|
742 | elif meth == 'pinfo': | |
743 | pmethod(info.obj,oname,formatter,info,**kw) |
|
743 | pmethod(info.obj,oname,formatter,info,**kw) | |
744 | else: |
|
744 | else: | |
745 | pmethod(info.obj,oname) |
|
745 | pmethod(info.obj,oname) | |
746 | else: |
|
746 | else: | |
747 | print 'Object `%s` not found.' % oname |
|
747 | print 'Object `%s` not found.' % oname | |
748 | return 'not found' # so callers can take other action |
|
748 | return 'not found' # so callers can take other action | |
749 |
|
749 | |||
750 | def magic_psearch(self, parameter_s=''): |
|
750 | def magic_psearch(self, parameter_s=''): | |
751 | """Search for object in namespaces by wildcard. |
|
751 | """Search for object in namespaces by wildcard. | |
752 |
|
752 | |||
753 | %psearch [options] PATTERN [OBJECT TYPE] |
|
753 | %psearch [options] PATTERN [OBJECT TYPE] | |
754 |
|
754 | |||
755 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
755 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
756 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
756 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
757 | rest of the command line must be unchanged (options come first), so |
|
757 | rest of the command line must be unchanged (options come first), so | |
758 | for example the following forms are equivalent |
|
758 | for example the following forms are equivalent | |
759 |
|
759 | |||
760 | %psearch -i a* function |
|
760 | %psearch -i a* function | |
761 | -i a* function? |
|
761 | -i a* function? | |
762 | ?-i a* function |
|
762 | ?-i a* function | |
763 |
|
763 | |||
764 | Arguments: |
|
764 | Arguments: | |
765 |
|
765 | |||
766 | PATTERN |
|
766 | PATTERN | |
767 |
|
767 | |||
768 | where PATTERN is a string containing * as a wildcard similar to its |
|
768 | where PATTERN is a string containing * as a wildcard similar to its | |
769 | use in a shell. The pattern is matched in all namespaces on the |
|
769 | use in a shell. The pattern is matched in all namespaces on the | |
770 | search path. By default objects starting with a single _ are not |
|
770 | search path. By default objects starting with a single _ are not | |
771 | matched, many IPython generated objects have a single |
|
771 | matched, many IPython generated objects have a single | |
772 | underscore. The default is case insensitive matching. Matching is |
|
772 | underscore. The default is case insensitive matching. Matching is | |
773 | also done on the attributes of objects and not only on the objects |
|
773 | also done on the attributes of objects and not only on the objects | |
774 | in a module. |
|
774 | in a module. | |
775 |
|
775 | |||
776 | [OBJECT TYPE] |
|
776 | [OBJECT TYPE] | |
777 |
|
777 | |||
778 | Is the name of a python type from the types module. The name is |
|
778 | Is the name of a python type from the types module. The name is | |
779 | given in lowercase without the ending type, ex. StringType is |
|
779 | given in lowercase without the ending type, ex. StringType is | |
780 | written string. By adding a type here only objects matching the |
|
780 | written string. By adding a type here only objects matching the | |
781 | given type are matched. Using all here makes the pattern match all |
|
781 | given type are matched. Using all here makes the pattern match all | |
782 | types (this is the default). |
|
782 | types (this is the default). | |
783 |
|
783 | |||
784 | Options: |
|
784 | Options: | |
785 |
|
785 | |||
786 | -a: makes the pattern match even objects whose names start with a |
|
786 | -a: makes the pattern match even objects whose names start with a | |
787 | single underscore. These names are normally ommitted from the |
|
787 | single underscore. These names are normally ommitted from the | |
788 | search. |
|
788 | search. | |
789 |
|
789 | |||
790 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
790 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
791 | these options is given, the default is read from your ipythonrc |
|
791 | these options is given, the default is read from your ipythonrc | |
792 | file. The option name which sets this value is |
|
792 | file. The option name which sets this value is | |
793 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
793 | 'wildcards_case_sensitive'. If this option is not specified in your | |
794 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
794 | ipythonrc file, IPython's internal default is to do a case sensitive | |
795 | search. |
|
795 | search. | |
796 |
|
796 | |||
797 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
797 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
798 | specifiy can be searched in any of the following namespaces: |
|
798 | specifiy can be searched in any of the following namespaces: | |
799 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
799 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
800 | 'builtin' and 'user' are the search defaults. Note that you should |
|
800 | 'builtin' and 'user' are the search defaults. Note that you should | |
801 | not use quotes when specifying namespaces. |
|
801 | not use quotes when specifying namespaces. | |
802 |
|
802 | |||
803 | 'Builtin' contains the python module builtin, 'user' contains all |
|
803 | 'Builtin' contains the python module builtin, 'user' contains all | |
804 | user data, 'alias' only contain the shell aliases and no python |
|
804 | user data, 'alias' only contain the shell aliases and no python | |
805 | objects, 'internal' contains objects used by IPython. The |
|
805 | objects, 'internal' contains objects used by IPython. The | |
806 | 'user_global' namespace is only used by embedded IPython instances, |
|
806 | 'user_global' namespace is only used by embedded IPython instances, | |
807 | and it contains module-level globals. You can add namespaces to the |
|
807 | and it contains module-level globals. You can add namespaces to the | |
808 | search with -s or exclude them with -e (these options can be given |
|
808 | search with -s or exclude them with -e (these options can be given | |
809 | more than once). |
|
809 | more than once). | |
810 |
|
810 | |||
811 | Examples: |
|
811 | Examples: | |
812 |
|
812 | |||
813 | %psearch a* -> objects beginning with an a |
|
813 | %psearch a* -> objects beginning with an a | |
814 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
814 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
815 | %psearch a* function -> all functions beginning with an a |
|
815 | %psearch a* function -> all functions beginning with an a | |
816 | %psearch re.e* -> objects beginning with an e in module re |
|
816 | %psearch re.e* -> objects beginning with an e in module re | |
817 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
817 | %psearch r*.e* -> objects that start with e in modules starting in r | |
818 | %psearch r*.* string -> all strings in modules beginning with r |
|
818 | %psearch r*.* string -> all strings in modules beginning with r | |
819 |
|
819 | |||
820 | Case sensitve search: |
|
820 | Case sensitve search: | |
821 |
|
821 | |||
822 | %psearch -c a* list all object beginning with lower case a |
|
822 | %psearch -c a* list all object beginning with lower case a | |
823 |
|
823 | |||
824 | Show objects beginning with a single _: |
|
824 | Show objects beginning with a single _: | |
825 |
|
825 | |||
826 | %psearch -a _* list objects beginning with a single underscore""" |
|
826 | %psearch -a _* list objects beginning with a single underscore""" | |
827 | try: |
|
827 | try: | |
828 | parameter_s = parameter_s.encode('ascii') |
|
828 | parameter_s = parameter_s.encode('ascii') | |
829 | except UnicodeEncodeError: |
|
829 | except UnicodeEncodeError: | |
830 | print 'Python identifiers can only contain ascii characters.' |
|
830 | print 'Python identifiers can only contain ascii characters.' | |
831 | return |
|
831 | return | |
832 |
|
832 | |||
833 | # default namespaces to be searched |
|
833 | # default namespaces to be searched | |
834 | def_search = ['user','builtin'] |
|
834 | def_search = ['user','builtin'] | |
835 |
|
835 | |||
836 | # Process options/args |
|
836 | # Process options/args | |
837 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
837 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
838 | opt = opts.get |
|
838 | opt = opts.get | |
839 | shell = self.shell |
|
839 | shell = self.shell | |
840 | psearch = shell.inspector.psearch |
|
840 | psearch = shell.inspector.psearch | |
841 |
|
841 | |||
842 | # select case options |
|
842 | # select case options | |
843 | if opts.has_key('i'): |
|
843 | if opts.has_key('i'): | |
844 | ignore_case = True |
|
844 | ignore_case = True | |
845 | elif opts.has_key('c'): |
|
845 | elif opts.has_key('c'): | |
846 | ignore_case = False |
|
846 | ignore_case = False | |
847 | else: |
|
847 | else: | |
848 | ignore_case = not shell.rc.wildcards_case_sensitive |
|
848 | ignore_case = not shell.rc.wildcards_case_sensitive | |
849 |
|
849 | |||
850 | # Build list of namespaces to search from user options |
|
850 | # Build list of namespaces to search from user options | |
851 | def_search.extend(opt('s',[])) |
|
851 | def_search.extend(opt('s',[])) | |
852 | ns_exclude = ns_exclude=opt('e',[]) |
|
852 | ns_exclude = ns_exclude=opt('e',[]) | |
853 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
853 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
854 |
|
854 | |||
855 | # Call the actual search |
|
855 | # Call the actual search | |
856 | try: |
|
856 | try: | |
857 | psearch(args,shell.ns_table,ns_search, |
|
857 | psearch(args,shell.ns_table,ns_search, | |
858 | show_all=opt('a'),ignore_case=ignore_case) |
|
858 | show_all=opt('a'),ignore_case=ignore_case) | |
859 | except: |
|
859 | except: | |
860 | shell.showtraceback() |
|
860 | shell.showtraceback() | |
861 |
|
861 | |||
862 | def magic_who_ls(self, parameter_s=''): |
|
862 | def magic_who_ls(self, parameter_s=''): | |
863 | """Return a sorted list of all interactive variables. |
|
863 | """Return a sorted list of all interactive variables. | |
864 |
|
864 | |||
865 | If arguments are given, only variables of types matching these |
|
865 | If arguments are given, only variables of types matching these | |
866 | arguments are returned.""" |
|
866 | arguments are returned.""" | |
867 |
|
867 | |||
868 | user_ns = self.shell.user_ns |
|
868 | user_ns = self.shell.user_ns | |
869 | internal_ns = self.shell.internal_ns |
|
869 | internal_ns = self.shell.internal_ns | |
870 | user_config_ns = self.shell.user_config_ns |
|
870 | user_config_ns = self.shell.user_config_ns | |
871 | out = [] |
|
871 | out = [] | |
872 | typelist = parameter_s.split() |
|
872 | typelist = parameter_s.split() | |
873 |
|
873 | |||
874 | for i in user_ns: |
|
874 | for i in user_ns: | |
875 | if not (i.startswith('_') or i.startswith('_i')) \ |
|
875 | if not (i.startswith('_') or i.startswith('_i')) \ | |
876 | and not (i in internal_ns or i in user_config_ns): |
|
876 | and not (i in internal_ns or i in user_config_ns): | |
877 | if typelist: |
|
877 | if typelist: | |
878 | if type(user_ns[i]).__name__ in typelist: |
|
878 | if type(user_ns[i]).__name__ in typelist: | |
879 | out.append(i) |
|
879 | out.append(i) | |
880 | else: |
|
880 | else: | |
881 | out.append(i) |
|
881 | out.append(i) | |
882 | out.sort() |
|
882 | out.sort() | |
883 | return out |
|
883 | return out | |
884 |
|
884 | |||
885 | def magic_who(self, parameter_s=''): |
|
885 | def magic_who(self, parameter_s=''): | |
886 | """Print all interactive variables, with some minimal formatting. |
|
886 | """Print all interactive variables, with some minimal formatting. | |
887 |
|
887 | |||
888 | If any arguments are given, only variables whose type matches one of |
|
888 | If any arguments are given, only variables whose type matches one of | |
889 | these are printed. For example: |
|
889 | these are printed. For example: | |
890 |
|
890 | |||
891 | %who function str |
|
891 | %who function str | |
892 |
|
892 | |||
893 | will only list functions and strings, excluding all other types of |
|
893 | will only list functions and strings, excluding all other types of | |
894 | variables. To find the proper type names, simply use type(var) at a |
|
894 | variables. To find the proper type names, simply use type(var) at a | |
895 | command line to see how python prints type names. For example: |
|
895 | command line to see how python prints type names. For example: | |
896 |
|
896 | |||
897 | In [1]: type('hello')\\ |
|
897 | In [1]: type('hello')\\ | |
898 | Out[1]: <type 'str'> |
|
898 | Out[1]: <type 'str'> | |
899 |
|
899 | |||
900 | indicates that the type name for strings is 'str'. |
|
900 | indicates that the type name for strings is 'str'. | |
901 |
|
901 | |||
902 | %who always excludes executed names loaded through your configuration |
|
902 | %who always excludes executed names loaded through your configuration | |
903 | file and things which are internal to IPython. |
|
903 | file and things which are internal to IPython. | |
904 |
|
904 | |||
905 | This is deliberate, as typically you may load many modules and the |
|
905 | This is deliberate, as typically you may load many modules and the | |
906 | purpose of %who is to show you only what you've manually defined.""" |
|
906 | purpose of %who is to show you only what you've manually defined.""" | |
907 |
|
907 | |||
908 | varlist = self.magic_who_ls(parameter_s) |
|
908 | varlist = self.magic_who_ls(parameter_s) | |
909 | if not varlist: |
|
909 | if not varlist: | |
910 | if parameter_s: |
|
910 | if parameter_s: | |
911 | print 'No variables match your requested type.' |
|
911 | print 'No variables match your requested type.' | |
912 | else: |
|
912 | else: | |
913 | print 'Interactive namespace is empty.' |
|
913 | print 'Interactive namespace is empty.' | |
914 | return |
|
914 | return | |
915 |
|
915 | |||
916 | # if we have variables, move on... |
|
916 | # if we have variables, move on... | |
917 | count = 0 |
|
917 | count = 0 | |
918 | for i in varlist: |
|
918 | for i in varlist: | |
919 | print i+'\t', |
|
919 | print i+'\t', | |
920 | count += 1 |
|
920 | count += 1 | |
921 | if count > 8: |
|
921 | if count > 8: | |
922 | count = 0 |
|
922 | count = 0 | |
923 |
|
923 | |||
924 |
|
924 | |||
925 |
|
925 | |||
926 | def magic_whos(self, parameter_s=''): |
|
926 | def magic_whos(self, parameter_s=''): | |
927 | """Like %who, but gives some extra information about each variable. |
|
927 | """Like %who, but gives some extra information about each variable. | |
928 |
|
928 | |||
929 | The same type filtering of %who can be applied here. |
|
929 | The same type filtering of %who can be applied here. | |
930 |
|
930 | |||
931 | For all variables, the type is printed. Additionally it prints: |
|
931 | For all variables, the type is printed. Additionally it prints: | |
932 |
|
932 | |||
933 | - For {},[],(): their length. |
|
933 | - For {},[],(): their length. | |
934 |
|
934 | |||
935 | - For numpy and Numeric arrays, a summary with shape, number of |
|
935 | - For numpy and Numeric arrays, a summary with shape, number of | |
936 | elements, typecode and size in memory. |
|
936 | elements, typecode and size in memory. | |
937 |
|
937 | |||
938 | - Everything else: a string representation, snipping their middle if |
|
938 | - Everything else: a string representation, snipping their middle if | |
939 | too long.""" |
|
939 | too long.""" | |
940 |
|
940 | |||
941 | varnames = self.magic_who_ls(parameter_s) |
|
941 | varnames = self.magic_who_ls(parameter_s) | |
942 | if not varnames: |
|
942 | if not varnames: | |
943 | if parameter_s: |
|
943 | if parameter_s: | |
944 | print 'No variables match your requested type.' |
|
944 | print 'No variables match your requested type.' | |
945 | else: |
|
945 | else: | |
946 | print 'Interactive namespace is empty.' |
|
946 | print 'Interactive namespace is empty.' | |
947 | return |
|
947 | return | |
948 |
|
948 | |||
949 | # if we have variables, move on... |
|
949 | # if we have variables, move on... | |
950 |
|
950 | |||
951 | # for these types, show len() instead of data: |
|
951 | # for these types, show len() instead of data: | |
952 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
952 | seq_types = [types.DictType,types.ListType,types.TupleType] | |
953 |
|
953 | |||
954 | # for numpy/Numeric arrays, display summary info |
|
954 | # for numpy/Numeric arrays, display summary info | |
955 | try: |
|
955 | try: | |
956 | import numpy |
|
956 | import numpy | |
957 | except ImportError: |
|
957 | except ImportError: | |
958 | ndarray_type = None |
|
958 | ndarray_type = None | |
959 | else: |
|
959 | else: | |
960 | ndarray_type = numpy.ndarray.__name__ |
|
960 | ndarray_type = numpy.ndarray.__name__ | |
961 | try: |
|
961 | try: | |
962 | import Numeric |
|
962 | import Numeric | |
963 | except ImportError: |
|
963 | except ImportError: | |
964 | array_type = None |
|
964 | array_type = None | |
965 | else: |
|
965 | else: | |
966 | array_type = Numeric.ArrayType.__name__ |
|
966 | array_type = Numeric.ArrayType.__name__ | |
967 |
|
967 | |||
968 | # Find all variable names and types so we can figure out column sizes |
|
968 | # Find all variable names and types so we can figure out column sizes | |
969 | def get_vars(i): |
|
969 | def get_vars(i): | |
970 | return self.shell.user_ns[i] |
|
970 | return self.shell.user_ns[i] | |
971 |
|
971 | |||
972 | # some types are well known and can be shorter |
|
972 | # some types are well known and can be shorter | |
973 | abbrevs = {'IPython.macro.Macro' : 'Macro'} |
|
973 | abbrevs = {'IPython.macro.Macro' : 'Macro'} | |
974 | def type_name(v): |
|
974 | def type_name(v): | |
975 | tn = type(v).__name__ |
|
975 | tn = type(v).__name__ | |
976 | return abbrevs.get(tn,tn) |
|
976 | return abbrevs.get(tn,tn) | |
977 |
|
977 | |||
978 | varlist = map(get_vars,varnames) |
|
978 | varlist = map(get_vars,varnames) | |
979 |
|
979 | |||
980 | typelist = [] |
|
980 | typelist = [] | |
981 | for vv in varlist: |
|
981 | for vv in varlist: | |
982 | tt = type_name(vv) |
|
982 | tt = type_name(vv) | |
983 |
|
983 | |||
984 | if tt=='instance': |
|
984 | if tt=='instance': | |
985 | typelist.append( abbrevs.get(str(vv.__class__), |
|
985 | typelist.append( abbrevs.get(str(vv.__class__), | |
986 | str(vv.__class__))) |
|
986 | str(vv.__class__))) | |
987 | else: |
|
987 | else: | |
988 | typelist.append(tt) |
|
988 | typelist.append(tt) | |
989 |
|
989 | |||
990 | # column labels and # of spaces as separator |
|
990 | # column labels and # of spaces as separator | |
991 | varlabel = 'Variable' |
|
991 | varlabel = 'Variable' | |
992 | typelabel = 'Type' |
|
992 | typelabel = 'Type' | |
993 | datalabel = 'Data/Info' |
|
993 | datalabel = 'Data/Info' | |
994 | colsep = 3 |
|
994 | colsep = 3 | |
995 | # variable format strings |
|
995 | # variable format strings | |
996 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
996 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" | |
997 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
997 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' | |
998 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
998 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
999 | # find the size of the columns to format the output nicely |
|
999 | # find the size of the columns to format the output nicely | |
1000 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
1000 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
1001 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
1001 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
1002 | # table header |
|
1002 | # table header | |
1003 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
1003 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
1004 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
1004 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
1005 | # and the table itself |
|
1005 | # and the table itself | |
1006 | kb = 1024 |
|
1006 | kb = 1024 | |
1007 | Mb = 1048576 # kb**2 |
|
1007 | Mb = 1048576 # kb**2 | |
1008 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
1008 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
1009 | print itpl(vformat), |
|
1009 | print itpl(vformat), | |
1010 | if vtype in seq_types: |
|
1010 | if vtype in seq_types: | |
1011 | print len(var) |
|
1011 | print len(var) | |
1012 | elif vtype in [array_type,ndarray_type]: |
|
1012 | elif vtype in [array_type,ndarray_type]: | |
1013 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
1013 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
1014 | if vtype==ndarray_type: |
|
1014 | if vtype==ndarray_type: | |
1015 | # numpy |
|
1015 | # numpy | |
1016 | vsize = var.size |
|
1016 | vsize = var.size | |
1017 | vbytes = vsize*var.itemsize |
|
1017 | vbytes = vsize*var.itemsize | |
1018 | vdtype = var.dtype |
|
1018 | vdtype = var.dtype | |
1019 | else: |
|
1019 | else: | |
1020 | # Numeric |
|
1020 | # Numeric | |
1021 | vsize = Numeric.size(var) |
|
1021 | vsize = Numeric.size(var) | |
1022 | vbytes = vsize*var.itemsize() |
|
1022 | vbytes = vsize*var.itemsize() | |
1023 | vdtype = var.typecode() |
|
1023 | vdtype = var.typecode() | |
1024 |
|
1024 | |||
1025 | if vbytes < 100000: |
|
1025 | if vbytes < 100000: | |
1026 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
1026 | print aformat % (vshape,vsize,vdtype,vbytes) | |
1027 | else: |
|
1027 | else: | |
1028 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
1028 | print aformat % (vshape,vsize,vdtype,vbytes), | |
1029 | if vbytes < Mb: |
|
1029 | if vbytes < Mb: | |
1030 | print '(%s kb)' % (vbytes/kb,) |
|
1030 | print '(%s kb)' % (vbytes/kb,) | |
1031 | else: |
|
1031 | else: | |
1032 | print '(%s Mb)' % (vbytes/Mb,) |
|
1032 | print '(%s Mb)' % (vbytes/Mb,) | |
1033 | else: |
|
1033 | else: | |
1034 | try: |
|
1034 | try: | |
1035 | vstr = str(var) |
|
1035 | vstr = str(var) | |
1036 | except UnicodeEncodeError: |
|
1036 | except UnicodeEncodeError: | |
1037 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
1037 | vstr = unicode(var).encode(sys.getdefaultencoding(), | |
1038 | 'backslashreplace') |
|
1038 | 'backslashreplace') | |
1039 | vstr = vstr.replace('\n','\\n') |
|
1039 | vstr = vstr.replace('\n','\\n') | |
1040 | if len(vstr) < 50: |
|
1040 | if len(vstr) < 50: | |
1041 | print vstr |
|
1041 | print vstr | |
1042 | else: |
|
1042 | else: | |
1043 | printpl(vfmt_short) |
|
1043 | printpl(vfmt_short) | |
1044 |
|
1044 | |||
1045 | def magic_reset(self, parameter_s=''): |
|
1045 | def magic_reset(self, parameter_s=''): | |
1046 | """Resets the namespace by removing all names defined by the user. |
|
1046 | """Resets the namespace by removing all names defined by the user. | |
1047 |
|
1047 | |||
1048 | Input/Output history are left around in case you need them.""" |
|
1048 | Input/Output history are left around in case you need them.""" | |
1049 |
|
1049 | |||
1050 | ans = self.shell.ask_yes_no( |
|
1050 | ans = self.shell.ask_yes_no( | |
1051 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1051 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
1052 | if not ans: |
|
1052 | if not ans: | |
1053 | print 'Nothing done.' |
|
1053 | print 'Nothing done.' | |
1054 | return |
|
1054 | return | |
1055 | user_ns = self.shell.user_ns |
|
1055 | user_ns = self.shell.user_ns | |
1056 | for i in self.magic_who_ls(): |
|
1056 | for i in self.magic_who_ls(): | |
1057 | del(user_ns[i]) |
|
1057 | del(user_ns[i]) | |
1058 |
|
1058 | |||
1059 | # Also flush the private list of module references kept for script |
|
1059 | # Also flush the private list of module references kept for script | |
1060 | # execution protection |
|
1060 | # execution protection | |
1061 | self.shell._user_main_modules[:] = [] |
|
1061 | self.shell._user_main_modules[:] = [] | |
1062 |
|
1062 | |||
1063 | def magic_logstart(self,parameter_s=''): |
|
1063 | def magic_logstart(self,parameter_s=''): | |
1064 | """Start logging anywhere in a session. |
|
1064 | """Start logging anywhere in a session. | |
1065 |
|
1065 | |||
1066 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1066 | %logstart [-o|-r|-t] [log_name [log_mode]] | |
1067 |
|
1067 | |||
1068 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1068 | If no name is given, it defaults to a file named 'ipython_log.py' in your | |
1069 | current directory, in 'rotate' mode (see below). |
|
1069 | current directory, in 'rotate' mode (see below). | |
1070 |
|
1070 | |||
1071 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1071 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
1072 | history up to that point and then continues logging. |
|
1072 | history up to that point and then continues logging. | |
1073 |
|
1073 | |||
1074 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1074 | %logstart takes a second optional parameter: logging mode. This can be one | |
1075 | of (note that the modes are given unquoted):\\ |
|
1075 | of (note that the modes are given unquoted):\\ | |
1076 | append: well, that says it.\\ |
|
1076 | append: well, that says it.\\ | |
1077 | backup: rename (if exists) to name~ and start name.\\ |
|
1077 | backup: rename (if exists) to name~ and start name.\\ | |
1078 | global: single logfile in your home dir, appended to.\\ |
|
1078 | global: single logfile in your home dir, appended to.\\ | |
1079 | over : overwrite existing log.\\ |
|
1079 | over : overwrite existing log.\\ | |
1080 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1080 | rotate: create rotating logs name.1~, name.2~, etc. | |
1081 |
|
1081 | |||
1082 | Options: |
|
1082 | Options: | |
1083 |
|
1083 | |||
1084 | -o: log also IPython's output. In this mode, all commands which |
|
1084 | -o: log also IPython's output. In this mode, all commands which | |
1085 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1085 | generate an Out[NN] prompt are recorded to the logfile, right after | |
1086 | their corresponding input line. The output lines are always |
|
1086 | their corresponding input line. The output lines are always | |
1087 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1087 | prepended with a '#[Out]# ' marker, so that the log remains valid | |
1088 | Python code. |
|
1088 | Python code. | |
1089 |
|
1089 | |||
1090 | Since this marker is always the same, filtering only the output from |
|
1090 | Since this marker is always the same, filtering only the output from | |
1091 | a log is very easy, using for example a simple awk call: |
|
1091 | a log is very easy, using for example a simple awk call: | |
1092 |
|
1092 | |||
1093 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1093 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py | |
1094 |
|
1094 | |||
1095 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1095 | -r: log 'raw' input. Normally, IPython's logs contain the processed | |
1096 | input, so that user lines are logged in their final form, converted |
|
1096 | input, so that user lines are logged in their final form, converted | |
1097 | into valid Python. For example, %Exit is logged as |
|
1097 | into valid Python. For example, %Exit is logged as | |
1098 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1098 | '_ip.magic("Exit"). If the -r flag is given, all input is logged | |
1099 | exactly as typed, with no transformations applied. |
|
1099 | exactly as typed, with no transformations applied. | |
1100 |
|
1100 | |||
1101 | -t: put timestamps before each input line logged (these are put in |
|
1101 | -t: put timestamps before each input line logged (these are put in | |
1102 | comments).""" |
|
1102 | comments).""" | |
1103 |
|
1103 | |||
1104 | opts,par = self.parse_options(parameter_s,'ort') |
|
1104 | opts,par = self.parse_options(parameter_s,'ort') | |
1105 | log_output = 'o' in opts |
|
1105 | log_output = 'o' in opts | |
1106 | log_raw_input = 'r' in opts |
|
1106 | log_raw_input = 'r' in opts | |
1107 | timestamp = 't' in opts |
|
1107 | timestamp = 't' in opts | |
1108 |
|
1108 | |||
1109 | rc = self.shell.rc |
|
1109 | rc = self.shell.rc | |
1110 | logger = self.shell.logger |
|
1110 | logger = self.shell.logger | |
1111 |
|
1111 | |||
1112 | # if no args are given, the defaults set in the logger constructor by |
|
1112 | # if no args are given, the defaults set in the logger constructor by | |
1113 | # ipytohn remain valid |
|
1113 | # ipytohn remain valid | |
1114 | if par: |
|
1114 | if par: | |
1115 | try: |
|
1115 | try: | |
1116 | logfname,logmode = par.split() |
|
1116 | logfname,logmode = par.split() | |
1117 | except: |
|
1117 | except: | |
1118 | logfname = par |
|
1118 | logfname = par | |
1119 | logmode = 'backup' |
|
1119 | logmode = 'backup' | |
1120 | else: |
|
1120 | else: | |
1121 | logfname = logger.logfname |
|
1121 | logfname = logger.logfname | |
1122 | logmode = logger.logmode |
|
1122 | logmode = logger.logmode | |
1123 | # put logfname into rc struct as if it had been called on the command |
|
1123 | # put logfname into rc struct as if it had been called on the command | |
1124 | # line, so it ends up saved in the log header Save it in case we need |
|
1124 | # line, so it ends up saved in the log header Save it in case we need | |
1125 | # to restore it... |
|
1125 | # to restore it... | |
1126 | old_logfile = rc.opts.get('logfile','') |
|
1126 | old_logfile = rc.opts.get('logfile','') | |
1127 | if logfname: |
|
1127 | if logfname: | |
1128 | logfname = os.path.expanduser(logfname) |
|
1128 | logfname = os.path.expanduser(logfname) | |
1129 | rc.opts.logfile = logfname |
|
1129 | rc.opts.logfile = logfname | |
1130 | loghead = self.shell.loghead_tpl % (rc.opts,rc.args) |
|
1130 | loghead = self.shell.loghead_tpl % (rc.opts,rc.args) | |
1131 | try: |
|
1131 | try: | |
1132 | started = logger.logstart(logfname,loghead,logmode, |
|
1132 | started = logger.logstart(logfname,loghead,logmode, | |
1133 | log_output,timestamp,log_raw_input) |
|
1133 | log_output,timestamp,log_raw_input) | |
1134 | except: |
|
1134 | except: | |
1135 | rc.opts.logfile = old_logfile |
|
1135 | rc.opts.logfile = old_logfile | |
1136 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1136 | warn("Couldn't start log: %s" % sys.exc_info()[1]) | |
1137 | else: |
|
1137 | else: | |
1138 | # log input history up to this point, optionally interleaving |
|
1138 | # log input history up to this point, optionally interleaving | |
1139 | # output if requested |
|
1139 | # output if requested | |
1140 |
|
1140 | |||
1141 | if timestamp: |
|
1141 | if timestamp: | |
1142 | # disable timestamping for the previous history, since we've |
|
1142 | # disable timestamping for the previous history, since we've | |
1143 | # lost those already (no time machine here). |
|
1143 | # lost those already (no time machine here). | |
1144 | logger.timestamp = False |
|
1144 | logger.timestamp = False | |
1145 |
|
1145 | |||
1146 | if log_raw_input: |
|
1146 | if log_raw_input: | |
1147 | input_hist = self.shell.input_hist_raw |
|
1147 | input_hist = self.shell.input_hist_raw | |
1148 | else: |
|
1148 | else: | |
1149 | input_hist = self.shell.input_hist |
|
1149 | input_hist = self.shell.input_hist | |
1150 |
|
1150 | |||
1151 | if log_output: |
|
1151 | if log_output: | |
1152 | log_write = logger.log_write |
|
1152 | log_write = logger.log_write | |
1153 | output_hist = self.shell.output_hist |
|
1153 | output_hist = self.shell.output_hist | |
1154 | for n in range(1,len(input_hist)-1): |
|
1154 | for n in range(1,len(input_hist)-1): | |
1155 | log_write(input_hist[n].rstrip()) |
|
1155 | log_write(input_hist[n].rstrip()) | |
1156 | if n in output_hist: |
|
1156 | if n in output_hist: | |
1157 | log_write(repr(output_hist[n]),'output') |
|
1157 | log_write(repr(output_hist[n]),'output') | |
1158 | else: |
|
1158 | else: | |
1159 | logger.log_write(input_hist[1:]) |
|
1159 | logger.log_write(input_hist[1:]) | |
1160 | if timestamp: |
|
1160 | if timestamp: | |
1161 | # re-enable timestamping |
|
1161 | # re-enable timestamping | |
1162 | logger.timestamp = True |
|
1162 | logger.timestamp = True | |
1163 |
|
1163 | |||
1164 | print ('Activating auto-logging. ' |
|
1164 | print ('Activating auto-logging. ' | |
1165 | 'Current session state plus future input saved.') |
|
1165 | 'Current session state plus future input saved.') | |
1166 | logger.logstate() |
|
1166 | logger.logstate() | |
1167 |
|
1167 | |||
1168 | def magic_logstop(self,parameter_s=''): |
|
1168 | def magic_logstop(self,parameter_s=''): | |
1169 | """Fully stop logging and close log file. |
|
1169 | """Fully stop logging and close log file. | |
1170 |
|
1170 | |||
1171 | In order to start logging again, a new %logstart call needs to be made, |
|
1171 | In order to start logging again, a new %logstart call needs to be made, | |
1172 | possibly (though not necessarily) with a new filename, mode and other |
|
1172 | possibly (though not necessarily) with a new filename, mode and other | |
1173 | options.""" |
|
1173 | options.""" | |
1174 | self.logger.logstop() |
|
1174 | self.logger.logstop() | |
1175 |
|
1175 | |||
1176 | def magic_logoff(self,parameter_s=''): |
|
1176 | def magic_logoff(self,parameter_s=''): | |
1177 | """Temporarily stop logging. |
|
1177 | """Temporarily stop logging. | |
1178 |
|
1178 | |||
1179 | You must have previously started logging.""" |
|
1179 | You must have previously started logging.""" | |
1180 | self.shell.logger.switch_log(0) |
|
1180 | self.shell.logger.switch_log(0) | |
1181 |
|
1181 | |||
1182 | def magic_logon(self,parameter_s=''): |
|
1182 | def magic_logon(self,parameter_s=''): | |
1183 | """Restart logging. |
|
1183 | """Restart logging. | |
1184 |
|
1184 | |||
1185 | This function is for restarting logging which you've temporarily |
|
1185 | This function is for restarting logging which you've temporarily | |
1186 | stopped with %logoff. For starting logging for the first time, you |
|
1186 | stopped with %logoff. For starting logging for the first time, you | |
1187 | must use the %logstart function, which allows you to specify an |
|
1187 | must use the %logstart function, which allows you to specify an | |
1188 | optional log filename.""" |
|
1188 | optional log filename.""" | |
1189 |
|
1189 | |||
1190 | self.shell.logger.switch_log(1) |
|
1190 | self.shell.logger.switch_log(1) | |
1191 |
|
1191 | |||
1192 | def magic_logstate(self,parameter_s=''): |
|
1192 | def magic_logstate(self,parameter_s=''): | |
1193 | """Print the status of the logging system.""" |
|
1193 | """Print the status of the logging system.""" | |
1194 |
|
1194 | |||
1195 | self.shell.logger.logstate() |
|
1195 | self.shell.logger.logstate() | |
1196 |
|
1196 | |||
1197 | def magic_pdb(self, parameter_s=''): |
|
1197 | def magic_pdb(self, parameter_s=''): | |
1198 | """Control the automatic calling of the pdb interactive debugger. |
|
1198 | """Control the automatic calling of the pdb interactive debugger. | |
1199 |
|
1199 | |||
1200 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1200 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
1201 | argument it works as a toggle. |
|
1201 | argument it works as a toggle. | |
1202 |
|
1202 | |||
1203 | When an exception is triggered, IPython can optionally call the |
|
1203 | When an exception is triggered, IPython can optionally call the | |
1204 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1204 | interactive pdb debugger after the traceback printout. %pdb toggles | |
1205 | this feature on and off. |
|
1205 | this feature on and off. | |
1206 |
|
1206 | |||
1207 | The initial state of this feature is set in your ipythonrc |
|
1207 | The initial state of this feature is set in your ipythonrc | |
1208 | configuration file (the variable is called 'pdb'). |
|
1208 | configuration file (the variable is called 'pdb'). | |
1209 |
|
1209 | |||
1210 | If you want to just activate the debugger AFTER an exception has fired, |
|
1210 | If you want to just activate the debugger AFTER an exception has fired, | |
1211 | without having to type '%pdb on' and rerunning your code, you can use |
|
1211 | without having to type '%pdb on' and rerunning your code, you can use | |
1212 | the %debug magic.""" |
|
1212 | the %debug magic.""" | |
1213 |
|
1213 | |||
1214 | par = parameter_s.strip().lower() |
|
1214 | par = parameter_s.strip().lower() | |
1215 |
|
1215 | |||
1216 | if par: |
|
1216 | if par: | |
1217 | try: |
|
1217 | try: | |
1218 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1218 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
1219 | except KeyError: |
|
1219 | except KeyError: | |
1220 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1220 | print ('Incorrect argument. Use on/1, off/0, ' | |
1221 | 'or nothing for a toggle.') |
|
1221 | 'or nothing for a toggle.') | |
1222 | return |
|
1222 | return | |
1223 | else: |
|
1223 | else: | |
1224 | # toggle |
|
1224 | # toggle | |
1225 | new_pdb = not self.shell.call_pdb |
|
1225 | new_pdb = not self.shell.call_pdb | |
1226 |
|
1226 | |||
1227 | # set on the shell |
|
1227 | # set on the shell | |
1228 | self.shell.call_pdb = new_pdb |
|
1228 | self.shell.call_pdb = new_pdb | |
1229 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1229 | print 'Automatic pdb calling has been turned',on_off(new_pdb) | |
1230 |
|
1230 | |||
1231 | def magic_debug(self, parameter_s=''): |
|
1231 | def magic_debug(self, parameter_s=''): | |
1232 | """Activate the interactive debugger in post-mortem mode. |
|
1232 | """Activate the interactive debugger in post-mortem mode. | |
1233 |
|
1233 | |||
1234 | If an exception has just occurred, this lets you inspect its stack |
|
1234 | If an exception has just occurred, this lets you inspect its stack | |
1235 | frames interactively. Note that this will always work only on the last |
|
1235 | frames interactively. Note that this will always work only on the last | |
1236 | traceback that occurred, so you must call this quickly after an |
|
1236 | traceback that occurred, so you must call this quickly after an | |
1237 | exception that you wish to inspect has fired, because if another one |
|
1237 | exception that you wish to inspect has fired, because if another one | |
1238 | occurs, it clobbers the previous one. |
|
1238 | occurs, it clobbers the previous one. | |
1239 |
|
1239 | |||
1240 | If you want IPython to automatically do this on every exception, see |
|
1240 | If you want IPython to automatically do this on every exception, see | |
1241 | the %pdb magic for more details. |
|
1241 | the %pdb magic for more details. | |
1242 | """ |
|
1242 | """ | |
1243 |
|
1243 | |||
1244 | self.shell.debugger(force=True) |
|
1244 | self.shell.debugger(force=True) | |
1245 |
|
1245 | |||
1246 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1246 | def magic_prun(self, parameter_s ='',user_mode=1, | |
1247 | opts=None,arg_lst=None,prog_ns=None): |
|
1247 | opts=None,arg_lst=None,prog_ns=None): | |
1248 |
|
1248 | |||
1249 | """Run a statement through the python code profiler. |
|
1249 | """Run a statement through the python code profiler. | |
1250 |
|
1250 | |||
1251 | Usage:\\ |
|
1251 | Usage:\\ | |
1252 | %prun [options] statement |
|
1252 | %prun [options] statement | |
1253 |
|
1253 | |||
1254 | The given statement (which doesn't require quote marks) is run via the |
|
1254 | The given statement (which doesn't require quote marks) is run via the | |
1255 | python profiler in a manner similar to the profile.run() function. |
|
1255 | python profiler in a manner similar to the profile.run() function. | |
1256 | Namespaces are internally managed to work correctly; profile.run |
|
1256 | Namespaces are internally managed to work correctly; profile.run | |
1257 | cannot be used in IPython because it makes certain assumptions about |
|
1257 | cannot be used in IPython because it makes certain assumptions about | |
1258 | namespaces which do not hold under IPython. |
|
1258 | namespaces which do not hold under IPython. | |
1259 |
|
1259 | |||
1260 | Options: |
|
1260 | Options: | |
1261 |
|
1261 | |||
1262 | -l <limit>: you can place restrictions on what or how much of the |
|
1262 | -l <limit>: you can place restrictions on what or how much of the | |
1263 | profile gets printed. The limit value can be: |
|
1263 | profile gets printed. The limit value can be: | |
1264 |
|
1264 | |||
1265 | * A string: only information for function names containing this string |
|
1265 | * A string: only information for function names containing this string | |
1266 | is printed. |
|
1266 | is printed. | |
1267 |
|
1267 | |||
1268 | * An integer: only these many lines are printed. |
|
1268 | * An integer: only these many lines are printed. | |
1269 |
|
1269 | |||
1270 | * A float (between 0 and 1): this fraction of the report is printed |
|
1270 | * A float (between 0 and 1): this fraction of the report is printed | |
1271 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1271 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
1272 |
|
1272 | |||
1273 | You can combine several limits with repeated use of the option. For |
|
1273 | You can combine several limits with repeated use of the option. For | |
1274 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1274 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
1275 | information about class constructors. |
|
1275 | information about class constructors. | |
1276 |
|
1276 | |||
1277 | -r: return the pstats.Stats object generated by the profiling. This |
|
1277 | -r: return the pstats.Stats object generated by the profiling. This | |
1278 | object has all the information about the profile in it, and you can |
|
1278 | object has all the information about the profile in it, and you can | |
1279 | later use it for further analysis or in other functions. |
|
1279 | later use it for further analysis or in other functions. | |
1280 |
|
1280 | |||
1281 | -s <key>: sort profile by given key. You can provide more than one key |
|
1281 | -s <key>: sort profile by given key. You can provide more than one key | |
1282 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1282 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1283 | default sorting key is 'time'. |
|
1283 | default sorting key is 'time'. | |
1284 |
|
1284 | |||
1285 | The following is copied verbatim from the profile documentation |
|
1285 | The following is copied verbatim from the profile documentation | |
1286 | referenced below: |
|
1286 | referenced below: | |
1287 |
|
1287 | |||
1288 | When more than one key is provided, additional keys are used as |
|
1288 | When more than one key is provided, additional keys are used as | |
1289 | secondary criteria when the there is equality in all keys selected |
|
1289 | secondary criteria when the there is equality in all keys selected | |
1290 | before them. |
|
1290 | before them. | |
1291 |
|
1291 | |||
1292 | Abbreviations can be used for any key names, as long as the |
|
1292 | Abbreviations can be used for any key names, as long as the | |
1293 | abbreviation is unambiguous. The following are the keys currently |
|
1293 | abbreviation is unambiguous. The following are the keys currently | |
1294 | defined: |
|
1294 | defined: | |
1295 |
|
1295 | |||
1296 | Valid Arg Meaning\\ |
|
1296 | Valid Arg Meaning\\ | |
1297 | "calls" call count\\ |
|
1297 | "calls" call count\\ | |
1298 | "cumulative" cumulative time\\ |
|
1298 | "cumulative" cumulative time\\ | |
1299 | "file" file name\\ |
|
1299 | "file" file name\\ | |
1300 | "module" file name\\ |
|
1300 | "module" file name\\ | |
1301 | "pcalls" primitive call count\\ |
|
1301 | "pcalls" primitive call count\\ | |
1302 | "line" line number\\ |
|
1302 | "line" line number\\ | |
1303 | "name" function name\\ |
|
1303 | "name" function name\\ | |
1304 | "nfl" name/file/line\\ |
|
1304 | "nfl" name/file/line\\ | |
1305 | "stdname" standard name\\ |
|
1305 | "stdname" standard name\\ | |
1306 | "time" internal time |
|
1306 | "time" internal time | |
1307 |
|
1307 | |||
1308 | Note that all sorts on statistics are in descending order (placing |
|
1308 | Note that all sorts on statistics are in descending order (placing | |
1309 | most time consuming items first), where as name, file, and line number |
|
1309 | most time consuming items first), where as name, file, and line number | |
1310 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1310 | searches are in ascending order (i.e., alphabetical). The subtle | |
1311 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1311 | distinction between "nfl" and "stdname" is that the standard name is a | |
1312 | sort of the name as printed, which means that the embedded line |
|
1312 | sort of the name as printed, which means that the embedded line | |
1313 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1313 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1314 | would (if the file names were the same) appear in the string order |
|
1314 | would (if the file names were the same) appear in the string order | |
1315 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1315 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1316 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1316 | line numbers. In fact, sort_stats("nfl") is the same as | |
1317 | sort_stats("name", "file", "line"). |
|
1317 | sort_stats("name", "file", "line"). | |
1318 |
|
1318 | |||
1319 | -T <filename>: save profile results as shown on screen to a text |
|
1319 | -T <filename>: save profile results as shown on screen to a text | |
1320 | file. The profile is still shown on screen. |
|
1320 | file. The profile is still shown on screen. | |
1321 |
|
1321 | |||
1322 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1322 | -D <filename>: save (via dump_stats) profile statistics to given | |
1323 | filename. This data is in a format understod by the pstats module, and |
|
1323 | filename. This data is in a format understod by the pstats module, and | |
1324 | is generated by a call to the dump_stats() method of profile |
|
1324 | is generated by a call to the dump_stats() method of profile | |
1325 | objects. The profile is still shown on screen. |
|
1325 | objects. The profile is still shown on screen. | |
1326 |
|
1326 | |||
1327 | If you want to run complete programs under the profiler's control, use |
|
1327 | If you want to run complete programs under the profiler's control, use | |
1328 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1328 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1329 | contains profiler specific options as described here. |
|
1329 | contains profiler specific options as described here. | |
1330 |
|
1330 | |||
1331 | You can read the complete documentation for the profile module with:\\ |
|
1331 | You can read the complete documentation for the profile module with:\\ | |
1332 | In [1]: import profile; profile.help() """ |
|
1332 | In [1]: import profile; profile.help() """ | |
1333 |
|
1333 | |||
1334 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1334 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1335 | # protect user quote marks |
|
1335 | # protect user quote marks | |
1336 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1336 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") | |
1337 |
|
1337 | |||
1338 | if user_mode: # regular user call |
|
1338 | if user_mode: # regular user call | |
1339 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1339 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', | |
1340 | list_all=1) |
|
1340 | list_all=1) | |
1341 | namespace = self.shell.user_ns |
|
1341 | namespace = self.shell.user_ns | |
1342 | else: # called to run a program by %run -p |
|
1342 | else: # called to run a program by %run -p | |
1343 | try: |
|
1343 | try: | |
1344 | filename = get_py_filename(arg_lst[0]) |
|
1344 | filename = get_py_filename(arg_lst[0]) | |
1345 | except IOError,msg: |
|
1345 | except IOError,msg: | |
1346 | error(msg) |
|
1346 | error(msg) | |
1347 | return |
|
1347 | return | |
1348 |
|
1348 | |||
1349 | arg_str = 'execfile(filename,prog_ns)' |
|
1349 | arg_str = 'execfile(filename,prog_ns)' | |
1350 | namespace = locals() |
|
1350 | namespace = locals() | |
1351 |
|
1351 | |||
1352 | opts.merge(opts_def) |
|
1352 | opts.merge(opts_def) | |
1353 |
|
1353 | |||
1354 | prof = profile.Profile() |
|
1354 | prof = profile.Profile() | |
1355 | try: |
|
1355 | try: | |
1356 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1356 | prof = prof.runctx(arg_str,namespace,namespace) | |
1357 | sys_exit = '' |
|
1357 | sys_exit = '' | |
1358 | except SystemExit: |
|
1358 | except SystemExit: | |
1359 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1359 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1360 |
|
1360 | |||
1361 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1361 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1362 |
|
1362 | |||
1363 | lims = opts.l |
|
1363 | lims = opts.l | |
1364 | if lims: |
|
1364 | if lims: | |
1365 | lims = [] # rebuild lims with ints/floats/strings |
|
1365 | lims = [] # rebuild lims with ints/floats/strings | |
1366 | for lim in opts.l: |
|
1366 | for lim in opts.l: | |
1367 | try: |
|
1367 | try: | |
1368 | lims.append(int(lim)) |
|
1368 | lims.append(int(lim)) | |
1369 | except ValueError: |
|
1369 | except ValueError: | |
1370 | try: |
|
1370 | try: | |
1371 | lims.append(float(lim)) |
|
1371 | lims.append(float(lim)) | |
1372 | except ValueError: |
|
1372 | except ValueError: | |
1373 | lims.append(lim) |
|
1373 | lims.append(lim) | |
1374 |
|
1374 | |||
1375 | # Trap output. |
|
1375 | # Trap output. | |
1376 | stdout_trap = StringIO() |
|
1376 | stdout_trap = StringIO() | |
1377 |
|
1377 | |||
1378 | if hasattr(stats,'stream'): |
|
1378 | if hasattr(stats,'stream'): | |
1379 | # In newer versions of python, the stats object has a 'stream' |
|
1379 | # In newer versions of python, the stats object has a 'stream' | |
1380 | # attribute to write into. |
|
1380 | # attribute to write into. | |
1381 | stats.stream = stdout_trap |
|
1381 | stats.stream = stdout_trap | |
1382 | stats.print_stats(*lims) |
|
1382 | stats.print_stats(*lims) | |
1383 | else: |
|
1383 | else: | |
1384 | # For older versions, we manually redirect stdout during printing |
|
1384 | # For older versions, we manually redirect stdout during printing | |
1385 | sys_stdout = sys.stdout |
|
1385 | sys_stdout = sys.stdout | |
1386 | try: |
|
1386 | try: | |
1387 | sys.stdout = stdout_trap |
|
1387 | sys.stdout = stdout_trap | |
1388 | stats.print_stats(*lims) |
|
1388 | stats.print_stats(*lims) | |
1389 | finally: |
|
1389 | finally: | |
1390 | sys.stdout = sys_stdout |
|
1390 | sys.stdout = sys_stdout | |
1391 |
|
1391 | |||
1392 | output = stdout_trap.getvalue() |
|
1392 | output = stdout_trap.getvalue() | |
1393 | output = output.rstrip() |
|
1393 | output = output.rstrip() | |
1394 |
|
1394 | |||
1395 | page(output,screen_lines=self.shell.rc.screen_length) |
|
1395 | page(output,screen_lines=self.shell.rc.screen_length) | |
1396 | print sys_exit, |
|
1396 | print sys_exit, | |
1397 |
|
1397 | |||
1398 | dump_file = opts.D[0] |
|
1398 | dump_file = opts.D[0] | |
1399 | text_file = opts.T[0] |
|
1399 | text_file = opts.T[0] | |
1400 | if dump_file: |
|
1400 | if dump_file: | |
1401 | prof.dump_stats(dump_file) |
|
1401 | prof.dump_stats(dump_file) | |
1402 | print '\n*** Profile stats marshalled to file',\ |
|
1402 | print '\n*** Profile stats marshalled to file',\ | |
1403 | `dump_file`+'.',sys_exit |
|
1403 | `dump_file`+'.',sys_exit | |
1404 | if text_file: |
|
1404 | if text_file: | |
1405 | pfile = file(text_file,'w') |
|
1405 | pfile = file(text_file,'w') | |
1406 | pfile.write(output) |
|
1406 | pfile.write(output) | |
1407 | pfile.close() |
|
1407 | pfile.close() | |
1408 | print '\n*** Profile printout saved to text file',\ |
|
1408 | print '\n*** Profile printout saved to text file',\ | |
1409 | `text_file`+'.',sys_exit |
|
1409 | `text_file`+'.',sys_exit | |
1410 |
|
1410 | |||
1411 | if opts.has_key('r'): |
|
1411 | if opts.has_key('r'): | |
1412 | return stats |
|
1412 | return stats | |
1413 | else: |
|
1413 | else: | |
1414 | return None |
|
1414 | return None | |
1415 |
|
1415 | |||
1416 | def magic_run(self, parameter_s ='',runner=None): |
|
1416 | def magic_run(self, parameter_s ='',runner=None): | |
1417 | """Run the named file inside IPython as a program. |
|
1417 | """Run the named file inside IPython as a program. | |
1418 |
|
1418 | |||
1419 | Usage:\\ |
|
1419 | Usage:\\ | |
1420 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1420 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
1421 |
|
1421 | |||
1422 | Parameters after the filename are passed as command-line arguments to |
|
1422 | Parameters after the filename are passed as command-line arguments to | |
1423 | the program (put in sys.argv). Then, control returns to IPython's |
|
1423 | the program (put in sys.argv). Then, control returns to IPython's | |
1424 | prompt. |
|
1424 | prompt. | |
1425 |
|
1425 | |||
1426 | This is similar to running at a system prompt:\\ |
|
1426 | This is similar to running at a system prompt:\\ | |
1427 | $ python file args\\ |
|
1427 | $ python file args\\ | |
1428 | but with the advantage of giving you IPython's tracebacks, and of |
|
1428 | but with the advantage of giving you IPython's tracebacks, and of | |
1429 | loading all variables into your interactive namespace for further use |
|
1429 | loading all variables into your interactive namespace for further use | |
1430 | (unless -p is used, see below). |
|
1430 | (unless -p is used, see below). | |
1431 |
|
1431 | |||
1432 | The file is executed in a namespace initially consisting only of |
|
1432 | The file is executed in a namespace initially consisting only of | |
1433 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1433 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
1434 | sees its environment as if it were being run as a stand-alone program |
|
1434 | sees its environment as if it were being run as a stand-alone program | |
1435 | (except for sharing global objects such as previously imported |
|
1435 | (except for sharing global objects such as previously imported | |
1436 | modules). But after execution, the IPython interactive namespace gets |
|
1436 | modules). But after execution, the IPython interactive namespace gets | |
1437 | updated with all variables defined in the program (except for __name__ |
|
1437 | updated with all variables defined in the program (except for __name__ | |
1438 | and sys.argv). This allows for very convenient loading of code for |
|
1438 | and sys.argv). This allows for very convenient loading of code for | |
1439 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1439 | interactive work, while giving each program a 'clean sheet' to run in. | |
1440 |
|
1440 | |||
1441 | Options: |
|
1441 | Options: | |
1442 |
|
1442 | |||
1443 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1443 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
1444 | without extension (as python does under import). This allows running |
|
1444 | without extension (as python does under import). This allows running | |
1445 | scripts and reloading the definitions in them without calling code |
|
1445 | scripts and reloading the definitions in them without calling code | |
1446 | protected by an ' if __name__ == "__main__" ' clause. |
|
1446 | protected by an ' if __name__ == "__main__" ' clause. | |
1447 |
|
1447 | |||
1448 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1448 | -i: run the file in IPython's namespace instead of an empty one. This | |
1449 | is useful if you are experimenting with code written in a text editor |
|
1449 | is useful if you are experimenting with code written in a text editor | |
1450 | which depends on variables defined interactively. |
|
1450 | which depends on variables defined interactively. | |
1451 |
|
1451 | |||
1452 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1452 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
1453 | being run. This is particularly useful if IPython is being used to |
|
1453 | being run. This is particularly useful if IPython is being used to | |
1454 | run unittests, which always exit with a sys.exit() call. In such |
|
1454 | run unittests, which always exit with a sys.exit() call. In such | |
1455 | cases you are interested in the output of the test results, not in |
|
1455 | cases you are interested in the output of the test results, not in | |
1456 | seeing a traceback of the unittest module. |
|
1456 | seeing a traceback of the unittest module. | |
1457 |
|
1457 | |||
1458 | -t: print timing information at the end of the run. IPython will give |
|
1458 | -t: print timing information at the end of the run. IPython will give | |
1459 | you an estimated CPU time consumption for your script, which under |
|
1459 | you an estimated CPU time consumption for your script, which under | |
1460 | Unix uses the resource module to avoid the wraparound problems of |
|
1460 | Unix uses the resource module to avoid the wraparound problems of | |
1461 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1461 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
1462 | is also given (for Windows platforms this is reported as 0.0). |
|
1462 | is also given (for Windows platforms this is reported as 0.0). | |
1463 |
|
1463 | |||
1464 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1464 | If -t is given, an additional -N<N> option can be given, where <N> | |
1465 | must be an integer indicating how many times you want the script to |
|
1465 | must be an integer indicating how many times you want the script to | |
1466 | run. The final timing report will include total and per run results. |
|
1466 | run. The final timing report will include total and per run results. | |
1467 |
|
1467 | |||
1468 | For example (testing the script uniq_stable.py): |
|
1468 | For example (testing the script uniq_stable.py): | |
1469 |
|
1469 | |||
1470 | In [1]: run -t uniq_stable |
|
1470 | In [1]: run -t uniq_stable | |
1471 |
|
1471 | |||
1472 | IPython CPU timings (estimated):\\ |
|
1472 | IPython CPU timings (estimated):\\ | |
1473 | User : 0.19597 s.\\ |
|
1473 | User : 0.19597 s.\\ | |
1474 | System: 0.0 s.\\ |
|
1474 | System: 0.0 s.\\ | |
1475 |
|
1475 | |||
1476 | In [2]: run -t -N5 uniq_stable |
|
1476 | In [2]: run -t -N5 uniq_stable | |
1477 |
|
1477 | |||
1478 | IPython CPU timings (estimated):\\ |
|
1478 | IPython CPU timings (estimated):\\ | |
1479 | Total runs performed: 5\\ |
|
1479 | Total runs performed: 5\\ | |
1480 | Times : Total Per run\\ |
|
1480 | Times : Total Per run\\ | |
1481 | User : 0.910862 s, 0.1821724 s.\\ |
|
1481 | User : 0.910862 s, 0.1821724 s.\\ | |
1482 | System: 0.0 s, 0.0 s. |
|
1482 | System: 0.0 s, 0.0 s. | |
1483 |
|
1483 | |||
1484 | -d: run your program under the control of pdb, the Python debugger. |
|
1484 | -d: run your program under the control of pdb, the Python debugger. | |
1485 | This allows you to execute your program step by step, watch variables, |
|
1485 | This allows you to execute your program step by step, watch variables, | |
1486 | etc. Internally, what IPython does is similar to calling: |
|
1486 | etc. Internally, what IPython does is similar to calling: | |
1487 |
|
1487 | |||
1488 | pdb.run('execfile("YOURFILENAME")') |
|
1488 | pdb.run('execfile("YOURFILENAME")') | |
1489 |
|
1489 | |||
1490 | with a breakpoint set on line 1 of your file. You can change the line |
|
1490 | with a breakpoint set on line 1 of your file. You can change the line | |
1491 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1491 | number for this automatic breakpoint to be <N> by using the -bN option | |
1492 | (where N must be an integer). For example: |
|
1492 | (where N must be an integer). For example: | |
1493 |
|
1493 | |||
1494 | %run -d -b40 myscript |
|
1494 | %run -d -b40 myscript | |
1495 |
|
1495 | |||
1496 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1496 | will set the first breakpoint at line 40 in myscript.py. Note that | |
1497 | the first breakpoint must be set on a line which actually does |
|
1497 | the first breakpoint must be set on a line which actually does | |
1498 | something (not a comment or docstring) for it to stop execution. |
|
1498 | something (not a comment or docstring) for it to stop execution. | |
1499 |
|
1499 | |||
1500 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1500 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
1501 | first enter 'c' (without qoutes) to start execution up to the first |
|
1501 | first enter 'c' (without qoutes) to start execution up to the first | |
1502 | breakpoint. |
|
1502 | breakpoint. | |
1503 |
|
1503 | |||
1504 | Entering 'help' gives information about the use of the debugger. You |
|
1504 | Entering 'help' gives information about the use of the debugger. You | |
1505 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1505 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
1506 | at a prompt. |
|
1506 | at a prompt. | |
1507 |
|
1507 | |||
1508 | -p: run program under the control of the Python profiler module (which |
|
1508 | -p: run program under the control of the Python profiler module (which | |
1509 | prints a detailed report of execution times, function calls, etc). |
|
1509 | prints a detailed report of execution times, function calls, etc). | |
1510 |
|
1510 | |||
1511 | You can pass other options after -p which affect the behavior of the |
|
1511 | You can pass other options after -p which affect the behavior of the | |
1512 | profiler itself. See the docs for %prun for details. |
|
1512 | profiler itself. See the docs for %prun for details. | |
1513 |
|
1513 | |||
1514 | In this mode, the program's variables do NOT propagate back to the |
|
1514 | In this mode, the program's variables do NOT propagate back to the | |
1515 | IPython interactive namespace (because they remain in the namespace |
|
1515 | IPython interactive namespace (because they remain in the namespace | |
1516 | where the profiler executes them). |
|
1516 | where the profiler executes them). | |
1517 |
|
1517 | |||
1518 | Internally this triggers a call to %prun, see its documentation for |
|
1518 | Internally this triggers a call to %prun, see its documentation for | |
1519 | details on the options available specifically for profiling. |
|
1519 | details on the options available specifically for profiling. | |
1520 |
|
1520 | |||
1521 | There is one special usage for which the text above doesn't apply: |
|
1521 | There is one special usage for which the text above doesn't apply: | |
1522 | if the filename ends with .ipy, the file is run as ipython script, |
|
1522 | if the filename ends with .ipy, the file is run as ipython script, | |
1523 | just as if the commands were written on IPython prompt. |
|
1523 | just as if the commands were written on IPython prompt. | |
1524 | """ |
|
1524 | """ | |
1525 |
|
1525 | |||
1526 | # get arguments and set sys.argv for program to be run. |
|
1526 | # get arguments and set sys.argv for program to be run. | |
1527 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1527 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', | |
1528 | mode='list',list_all=1) |
|
1528 | mode='list',list_all=1) | |
1529 |
|
1529 | |||
1530 | try: |
|
1530 | try: | |
1531 | filename = get_py_filename(arg_lst[0]) |
|
1531 | filename = get_py_filename(arg_lst[0]) | |
1532 | except IndexError: |
|
1532 | except IndexError: | |
1533 | warn('you must provide at least a filename.') |
|
1533 | warn('you must provide at least a filename.') | |
1534 | print '\n%run:\n',OInspect.getdoc(self.magic_run) |
|
1534 | print '\n%run:\n',OInspect.getdoc(self.magic_run) | |
1535 | return |
|
1535 | return | |
1536 | except IOError,msg: |
|
1536 | except IOError,msg: | |
1537 | error(msg) |
|
1537 | error(msg) | |
1538 | return |
|
1538 | return | |
1539 |
|
1539 | |||
1540 | if filename.lower().endswith('.ipy'): |
|
1540 | if filename.lower().endswith('.ipy'): | |
1541 | self.api.runlines(open(filename).read()) |
|
1541 | self.api.runlines(open(filename).read()) | |
1542 | return |
|
1542 | return | |
1543 |
|
1543 | |||
1544 | # Control the response to exit() calls made by the script being run |
|
1544 | # Control the response to exit() calls made by the script being run | |
1545 | exit_ignore = opts.has_key('e') |
|
1545 | exit_ignore = opts.has_key('e') | |
1546 |
|
1546 | |||
1547 | # Make sure that the running script gets a proper sys.argv as if it |
|
1547 | # Make sure that the running script gets a proper sys.argv as if it | |
1548 | # were run from a system shell. |
|
1548 | # were run from a system shell. | |
1549 | save_argv = sys.argv # save it for later restoring |
|
1549 | save_argv = sys.argv # save it for later restoring | |
1550 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1550 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename | |
1551 |
|
1551 | |||
1552 | if opts.has_key('i'): |
|
1552 | if opts.has_key('i'): | |
1553 | # Run in user's interactive namespace |
|
1553 | # Run in user's interactive namespace | |
1554 | prog_ns = self.shell.user_ns |
|
1554 | prog_ns = self.shell.user_ns | |
1555 | __name__save = self.shell.user_ns['__name__'] |
|
1555 | __name__save = self.shell.user_ns['__name__'] | |
1556 | prog_ns['__name__'] = '__main__' |
|
1556 | prog_ns['__name__'] = '__main__' | |
1557 | main_mod = FakeModule(prog_ns) |
|
1557 | main_mod = FakeModule(prog_ns) | |
1558 | else: |
|
1558 | else: | |
1559 | # Run in a fresh, empty namespace |
|
1559 | # Run in a fresh, empty namespace | |
1560 | if opts.has_key('n'): |
|
1560 | if opts.has_key('n'): | |
1561 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1561 | name = os.path.splitext(os.path.basename(filename))[0] | |
1562 | else: |
|
1562 | else: | |
1563 | name = '__main__' |
|
1563 | name = '__main__' | |
1564 | main_mod = FakeModule() |
|
1564 | main_mod = FakeModule() | |
1565 | prog_ns = main_mod.__dict__ |
|
1565 | prog_ns = main_mod.__dict__ | |
1566 | prog_ns['__name__'] = name |
|
1566 | prog_ns['__name__'] = name | |
1567 | # The shell MUST hold a reference to main_mod so after %run exits, |
|
1567 | # The shell MUST hold a reference to main_mod so after %run exits, | |
1568 | # the python deletion mechanism doesn't zero it out (leaving |
|
1568 | # the python deletion mechanism doesn't zero it out (leaving | |
1569 | # dangling references) |
|
1569 | # dangling references) | |
1570 | self.shell._user_main_modules.append(main_mod) |
|
1570 | self.shell._user_main_modules.append(main_mod) | |
1571 |
|
1571 | |||
1572 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1572 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must | |
1573 | # set the __file__ global in the script's namespace |
|
1573 | # set the __file__ global in the script's namespace | |
1574 | prog_ns['__file__'] = filename |
|
1574 | prog_ns['__file__'] = filename | |
1575 |
|
1575 | |||
1576 | # pickle fix. See iplib for an explanation. But we need to make sure |
|
1576 | # pickle fix. See iplib for an explanation. But we need to make sure | |
1577 | # that, if we overwrite __main__, we replace it at the end |
|
1577 | # that, if we overwrite __main__, we replace it at the end | |
1578 | if prog_ns['__name__'] == '__main__': |
|
1578 | if prog_ns['__name__'] == '__main__': | |
1579 | restore_main = sys.modules['__main__'] |
|
1579 | restore_main = sys.modules['__main__'] | |
1580 | else: |
|
1580 | else: | |
1581 | restore_main = False |
|
1581 | restore_main = False | |
1582 |
|
1582 | |||
1583 | sys.modules[prog_ns['__name__']] = main_mod |
|
1583 | sys.modules[prog_ns['__name__']] = main_mod | |
1584 |
|
1584 | |||
1585 | stats = None |
|
1585 | stats = None | |
1586 | try: |
|
1586 | try: | |
1587 | self.shell.savehist() |
|
1587 | self.shell.savehist() | |
1588 |
|
1588 | |||
1589 | if opts.has_key('p'): |
|
1589 | if opts.has_key('p'): | |
1590 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1590 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) | |
1591 | else: |
|
1591 | else: | |
1592 | if opts.has_key('d'): |
|
1592 | if opts.has_key('d'): | |
1593 | deb = Debugger.Pdb(self.shell.rc.colors) |
|
1593 | deb = Debugger.Pdb(self.shell.rc.colors) | |
1594 | # reset Breakpoint state, which is moronically kept |
|
1594 | # reset Breakpoint state, which is moronically kept | |
1595 | # in a class |
|
1595 | # in a class | |
1596 | bdb.Breakpoint.next = 1 |
|
1596 | bdb.Breakpoint.next = 1 | |
1597 | bdb.Breakpoint.bplist = {} |
|
1597 | bdb.Breakpoint.bplist = {} | |
1598 | bdb.Breakpoint.bpbynumber = [None] |
|
1598 | bdb.Breakpoint.bpbynumber = [None] | |
1599 | # Set an initial breakpoint to stop execution |
|
1599 | # Set an initial breakpoint to stop execution | |
1600 | maxtries = 10 |
|
1600 | maxtries = 10 | |
1601 | bp = int(opts.get('b',[1])[0]) |
|
1601 | bp = int(opts.get('b',[1])[0]) | |
1602 | checkline = deb.checkline(filename,bp) |
|
1602 | checkline = deb.checkline(filename,bp) | |
1603 | if not checkline: |
|
1603 | if not checkline: | |
1604 | for bp in range(bp+1,bp+maxtries+1): |
|
1604 | for bp in range(bp+1,bp+maxtries+1): | |
1605 | if deb.checkline(filename,bp): |
|
1605 | if deb.checkline(filename,bp): | |
1606 | break |
|
1606 | break | |
1607 | else: |
|
1607 | else: | |
1608 | msg = ("\nI failed to find a valid line to set " |
|
1608 | msg = ("\nI failed to find a valid line to set " | |
1609 | "a breakpoint\n" |
|
1609 | "a breakpoint\n" | |
1610 | "after trying up to line: %s.\n" |
|
1610 | "after trying up to line: %s.\n" | |
1611 | "Please set a valid breakpoint manually " |
|
1611 | "Please set a valid breakpoint manually " | |
1612 | "with the -b option." % bp) |
|
1612 | "with the -b option." % bp) | |
1613 | error(msg) |
|
1613 | error(msg) | |
1614 | return |
|
1614 | return | |
1615 | # if we find a good linenumber, set the breakpoint |
|
1615 | # if we find a good linenumber, set the breakpoint | |
1616 | deb.do_break('%s:%s' % (filename,bp)) |
|
1616 | deb.do_break('%s:%s' % (filename,bp)) | |
1617 | # Start file run |
|
1617 | # Start file run | |
1618 | print "NOTE: Enter 'c' at the", |
|
1618 | print "NOTE: Enter 'c' at the", | |
1619 | print "%s prompt to start your script." % deb.prompt |
|
1619 | print "%s prompt to start your script." % deb.prompt | |
1620 | try: |
|
1620 | try: | |
1621 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1621 | deb.run('execfile("%s")' % filename,prog_ns) | |
1622 |
|
1622 | |||
1623 | except: |
|
1623 | except: | |
1624 | etype, value, tb = sys.exc_info() |
|
1624 | etype, value, tb = sys.exc_info() | |
1625 | # Skip three frames in the traceback: the %run one, |
|
1625 | # Skip three frames in the traceback: the %run one, | |
1626 | # one inside bdb.py, and the command-line typed by the |
|
1626 | # one inside bdb.py, and the command-line typed by the | |
1627 | # user (run by exec in pdb itself). |
|
1627 | # user (run by exec in pdb itself). | |
1628 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1628 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) | |
1629 | else: |
|
1629 | else: | |
1630 | if runner is None: |
|
1630 | if runner is None: | |
1631 | runner = self.shell.safe_execfile |
|
1631 | runner = self.shell.safe_execfile | |
1632 | if opts.has_key('t'): |
|
1632 | if opts.has_key('t'): | |
1633 | # timed execution |
|
1633 | # timed execution | |
1634 | try: |
|
1634 | try: | |
1635 | nruns = int(opts['N'][0]) |
|
1635 | nruns = int(opts['N'][0]) | |
1636 | if nruns < 1: |
|
1636 | if nruns < 1: | |
1637 | error('Number of runs must be >=1') |
|
1637 | error('Number of runs must be >=1') | |
1638 | return |
|
1638 | return | |
1639 | except (KeyError): |
|
1639 | except (KeyError): | |
1640 | nruns = 1 |
|
1640 | nruns = 1 | |
1641 | if nruns == 1: |
|
1641 | if nruns == 1: | |
1642 | t0 = clock2() |
|
1642 | t0 = clock2() | |
1643 | runner(filename,prog_ns,prog_ns, |
|
1643 | runner(filename,prog_ns,prog_ns, | |
1644 | exit_ignore=exit_ignore) |
|
1644 | exit_ignore=exit_ignore) | |
1645 | t1 = clock2() |
|
1645 | t1 = clock2() | |
1646 | t_usr = t1[0]-t0[0] |
|
1646 | t_usr = t1[0]-t0[0] | |
1647 | t_sys = t1[1]-t1[1] |
|
1647 | t_sys = t1[1]-t1[1] | |
1648 | print "\nIPython CPU timings (estimated):" |
|
1648 | print "\nIPython CPU timings (estimated):" | |
1649 | print " User : %10s s." % t_usr |
|
1649 | print " User : %10s s." % t_usr | |
1650 | print " System: %10s s." % t_sys |
|
1650 | print " System: %10s s." % t_sys | |
1651 | else: |
|
1651 | else: | |
1652 | runs = range(nruns) |
|
1652 | runs = range(nruns) | |
1653 | t0 = clock2() |
|
1653 | t0 = clock2() | |
1654 | for nr in runs: |
|
1654 | for nr in runs: | |
1655 | runner(filename,prog_ns,prog_ns, |
|
1655 | runner(filename,prog_ns,prog_ns, | |
1656 | exit_ignore=exit_ignore) |
|
1656 | exit_ignore=exit_ignore) | |
1657 | t1 = clock2() |
|
1657 | t1 = clock2() | |
1658 | t_usr = t1[0]-t0[0] |
|
1658 | t_usr = t1[0]-t0[0] | |
1659 | t_sys = t1[1]-t1[1] |
|
1659 | t_sys = t1[1]-t1[1] | |
1660 | print "\nIPython CPU timings (estimated):" |
|
1660 | print "\nIPython CPU timings (estimated):" | |
1661 | print "Total runs performed:",nruns |
|
1661 | print "Total runs performed:",nruns | |
1662 | print " Times : %10s %10s" % ('Total','Per run') |
|
1662 | print " Times : %10s %10s" % ('Total','Per run') | |
1663 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1663 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) | |
1664 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1664 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) | |
1665 |
|
1665 | |||
1666 | else: |
|
1666 | else: | |
1667 | # regular execution |
|
1667 | # regular execution | |
1668 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1668 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1669 | if opts.has_key('i'): |
|
1669 | if opts.has_key('i'): | |
1670 | self.shell.user_ns['__name__'] = __name__save |
|
1670 | self.shell.user_ns['__name__'] = __name__save | |
1671 | else: |
|
1671 | else: | |
1672 | # update IPython interactive namespace |
|
1672 | # update IPython interactive namespace | |
1673 | del prog_ns['__name__'] |
|
1673 | del prog_ns['__name__'] | |
1674 | self.shell.user_ns.update(prog_ns) |
|
1674 | self.shell.user_ns.update(prog_ns) | |
1675 | finally: |
|
1675 | finally: | |
1676 | sys.argv = save_argv |
|
1676 | sys.argv = save_argv | |
1677 | if restore_main: |
|
1677 | if restore_main: | |
1678 | sys.modules['__main__'] = restore_main |
|
1678 | sys.modules['__main__'] = restore_main | |
1679 | self.shell.reloadhist() |
|
1679 | self.shell.reloadhist() | |
1680 |
|
1680 | |||
1681 | return stats |
|
1681 | return stats | |
1682 |
|
1682 | |||
1683 | def magic_runlog(self, parameter_s =''): |
|
1683 | def magic_runlog(self, parameter_s =''): | |
1684 | """Run files as logs. |
|
1684 | """Run files as logs. | |
1685 |
|
1685 | |||
1686 | Usage:\\ |
|
1686 | Usage:\\ | |
1687 | %runlog file1 file2 ... |
|
1687 | %runlog file1 file2 ... | |
1688 |
|
1688 | |||
1689 | Run the named files (treating them as log files) in sequence inside |
|
1689 | Run the named files (treating them as log files) in sequence inside | |
1690 | the interpreter, and return to the prompt. This is much slower than |
|
1690 | the interpreter, and return to the prompt. This is much slower than | |
1691 | %run because each line is executed in a try/except block, but it |
|
1691 | %run because each line is executed in a try/except block, but it | |
1692 | allows running files with syntax errors in them. |
|
1692 | allows running files with syntax errors in them. | |
1693 |
|
1693 | |||
1694 | Normally IPython will guess when a file is one of its own logfiles, so |
|
1694 | Normally IPython will guess when a file is one of its own logfiles, so | |
1695 | you can typically use %run even for logs. This shorthand allows you to |
|
1695 | you can typically use %run even for logs. This shorthand allows you to | |
1696 | force any file to be treated as a log file.""" |
|
1696 | force any file to be treated as a log file.""" | |
1697 |
|
1697 | |||
1698 | for f in parameter_s.split(): |
|
1698 | for f in parameter_s.split(): | |
1699 | self.shell.safe_execfile(f,self.shell.user_ns, |
|
1699 | self.shell.safe_execfile(f,self.shell.user_ns, | |
1700 | self.shell.user_ns,islog=1) |
|
1700 | self.shell.user_ns,islog=1) | |
1701 |
|
1701 | |||
1702 | def magic_timeit(self, parameter_s =''): |
|
1702 | def magic_timeit(self, parameter_s =''): | |
1703 | """Time execution of a Python statement or expression |
|
1703 | """Time execution of a Python statement or expression | |
1704 |
|
1704 | |||
1705 | Usage:\\ |
|
1705 | Usage:\\ | |
1706 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1706 | %timeit [-n<N> -r<R> [-t|-c]] statement | |
1707 |
|
1707 | |||
1708 | Time execution of a Python statement or expression using the timeit |
|
1708 | Time execution of a Python statement or expression using the timeit | |
1709 | module. |
|
1709 | module. | |
1710 |
|
1710 | |||
1711 | Options: |
|
1711 | Options: | |
1712 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1712 | -n<N>: execute the given statement <N> times in a loop. If this value | |
1713 | is not given, a fitting value is chosen. |
|
1713 | is not given, a fitting value is chosen. | |
1714 |
|
1714 | |||
1715 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1715 | -r<R>: repeat the loop iteration <R> times and take the best result. | |
1716 | Default: 3 |
|
1716 | Default: 3 | |
1717 |
|
1717 | |||
1718 | -t: use time.time to measure the time, which is the default on Unix. |
|
1718 | -t: use time.time to measure the time, which is the default on Unix. | |
1719 | This function measures wall time. |
|
1719 | This function measures wall time. | |
1720 |
|
1720 | |||
1721 | -c: use time.clock to measure the time, which is the default on |
|
1721 | -c: use time.clock to measure the time, which is the default on | |
1722 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1722 | Windows and measures wall time. On Unix, resource.getrusage is used | |
1723 | instead and returns the CPU user time. |
|
1723 | instead and returns the CPU user time. | |
1724 |
|
1724 | |||
1725 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1725 | -p<P>: use a precision of <P> digits to display the timing result. | |
1726 | Default: 3 |
|
1726 | Default: 3 | |
1727 |
|
1727 | |||
1728 |
|
1728 | |||
1729 | Examples:\\ |
|
1729 | Examples:\\ | |
1730 | In [1]: %timeit pass |
|
1730 | In [1]: %timeit pass | |
1731 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1731 | 10000000 loops, best of 3: 53.3 ns per loop | |
1732 |
|
1732 | |||
1733 | In [2]: u = None |
|
1733 | In [2]: u = None | |
1734 |
|
1734 | |||
1735 | In [3]: %timeit u is None |
|
1735 | In [3]: %timeit u is None | |
1736 | 10000000 loops, best of 3: 184 ns per loop |
|
1736 | 10000000 loops, best of 3: 184 ns per loop | |
1737 |
|
1737 | |||
1738 | In [4]: %timeit -r 4 u == None |
|
1738 | In [4]: %timeit -r 4 u == None | |
1739 | 1000000 loops, best of 4: 242 ns per loop |
|
1739 | 1000000 loops, best of 4: 242 ns per loop | |
1740 |
|
1740 | |||
1741 | In [5]: import time |
|
1741 | In [5]: import time | |
1742 |
|
1742 | |||
1743 | In [6]: %timeit -n1 time.sleep(2) |
|
1743 | In [6]: %timeit -n1 time.sleep(2) | |
1744 | 1 loops, best of 3: 2 s per loop |
|
1744 | 1 loops, best of 3: 2 s per loop | |
1745 |
|
1745 | |||
1746 |
|
1746 | |||
1747 | The times reported by %timeit will be slightly higher than those |
|
1747 | The times reported by %timeit will be slightly higher than those | |
1748 | reported by the timeit.py script when variables are accessed. This is |
|
1748 | reported by the timeit.py script when variables are accessed. This is | |
1749 | due to the fact that %timeit executes the statement in the namespace |
|
1749 | due to the fact that %timeit executes the statement in the namespace | |
1750 | of the shell, compared with timeit.py, which uses a single setup |
|
1750 | of the shell, compared with timeit.py, which uses a single setup | |
1751 | statement to import function or create variables. Generally, the bias |
|
1751 | statement to import function or create variables. Generally, the bias | |
1752 | does not matter as long as results from timeit.py are not mixed with |
|
1752 | does not matter as long as results from timeit.py are not mixed with | |
1753 | those from %timeit.""" |
|
1753 | those from %timeit.""" | |
1754 |
|
1754 | |||
1755 | import timeit |
|
1755 | import timeit | |
1756 | import math |
|
1756 | import math | |
1757 |
|
1757 | |||
1758 | units = ["s", "ms", "\xc2\xb5s", "ns"] |
|
1758 | units = ["s", "ms", "\xc2\xb5s", "ns"] | |
1759 | scaling = [1, 1e3, 1e6, 1e9] |
|
1759 | scaling = [1, 1e3, 1e6, 1e9] | |
1760 |
|
1760 | |||
1761 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1761 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', | |
1762 | posix=False) |
|
1762 | posix=False) | |
1763 | if stmt == "": |
|
1763 | if stmt == "": | |
1764 | return |
|
1764 | return | |
1765 | timefunc = timeit.default_timer |
|
1765 | timefunc = timeit.default_timer | |
1766 | number = int(getattr(opts, "n", 0)) |
|
1766 | number = int(getattr(opts, "n", 0)) | |
1767 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1767 | repeat = int(getattr(opts, "r", timeit.default_repeat)) | |
1768 | precision = int(getattr(opts, "p", 3)) |
|
1768 | precision = int(getattr(opts, "p", 3)) | |
1769 | if hasattr(opts, "t"): |
|
1769 | if hasattr(opts, "t"): | |
1770 | timefunc = time.time |
|
1770 | timefunc = time.time | |
1771 | if hasattr(opts, "c"): |
|
1771 | if hasattr(opts, "c"): | |
1772 | timefunc = clock |
|
1772 | timefunc = clock | |
1773 |
|
1773 | |||
1774 | timer = timeit.Timer(timer=timefunc) |
|
1774 | timer = timeit.Timer(timer=timefunc) | |
1775 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1775 | # this code has tight coupling to the inner workings of timeit.Timer, | |
1776 | # but is there a better way to achieve that the code stmt has access |
|
1776 | # but is there a better way to achieve that the code stmt has access | |
1777 | # to the shell namespace? |
|
1777 | # to the shell namespace? | |
1778 |
|
1778 | |||
1779 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1779 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), | |
1780 | 'setup': "pass"} |
|
1780 | 'setup': "pass"} | |
1781 | # Track compilation time so it can be reported if too long |
|
1781 | # Track compilation time so it can be reported if too long | |
1782 | # Minimum time above which compilation time will be reported |
|
1782 | # Minimum time above which compilation time will be reported | |
1783 | tc_min = 0.1 |
|
1783 | tc_min = 0.1 | |
1784 |
|
1784 | |||
1785 | t0 = clock() |
|
1785 | t0 = clock() | |
1786 | code = compile(src, "<magic-timeit>", "exec") |
|
1786 | code = compile(src, "<magic-timeit>", "exec") | |
1787 | tc = clock()-t0 |
|
1787 | tc = clock()-t0 | |
1788 |
|
1788 | |||
1789 | ns = {} |
|
1789 | ns = {} | |
1790 | exec code in self.shell.user_ns, ns |
|
1790 | exec code in self.shell.user_ns, ns | |
1791 | timer.inner = ns["inner"] |
|
1791 | timer.inner = ns["inner"] | |
1792 |
|
1792 | |||
1793 | if number == 0: |
|
1793 | if number == 0: | |
1794 | # determine number so that 0.2 <= total time < 2.0 |
|
1794 | # determine number so that 0.2 <= total time < 2.0 | |
1795 | number = 1 |
|
1795 | number = 1 | |
1796 | for i in range(1, 10): |
|
1796 | for i in range(1, 10): | |
1797 | number *= 10 |
|
1797 | number *= 10 | |
1798 | if timer.timeit(number) >= 0.2: |
|
1798 | if timer.timeit(number) >= 0.2: | |
1799 | break |
|
1799 | break | |
1800 |
|
1800 | |||
1801 | best = min(timer.repeat(repeat, number)) / number |
|
1801 | best = min(timer.repeat(repeat, number)) / number | |
1802 |
|
1802 | |||
1803 | if best > 0.0: |
|
1803 | if best > 0.0: | |
1804 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1804 | order = min(-int(math.floor(math.log10(best)) // 3), 3) | |
1805 | else: |
|
1805 | else: | |
1806 | order = 3 |
|
1806 | order = 3 | |
1807 | print "%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1807 | print "%d loops, best of %d: %.*g %s per loop" % (number, repeat, | |
1808 | precision, |
|
1808 | precision, | |
1809 | best * scaling[order], |
|
1809 | best * scaling[order], | |
1810 | units[order]) |
|
1810 | units[order]) | |
1811 | if tc > tc_min: |
|
1811 | if tc > tc_min: | |
1812 | print "Compiler time: %.2f s" % tc |
|
1812 | print "Compiler time: %.2f s" % tc | |
1813 |
|
1813 | |||
1814 | def magic_time(self,parameter_s = ''): |
|
1814 | def magic_time(self,parameter_s = ''): | |
1815 | """Time execution of a Python statement or expression. |
|
1815 | """Time execution of a Python statement or expression. | |
1816 |
|
1816 | |||
1817 | The CPU and wall clock times are printed, and the value of the |
|
1817 | The CPU and wall clock times are printed, and the value of the | |
1818 | expression (if any) is returned. Note that under Win32, system time |
|
1818 | expression (if any) is returned. Note that under Win32, system time | |
1819 | is always reported as 0, since it can not be measured. |
|
1819 | is always reported as 0, since it can not be measured. | |
1820 |
|
1820 | |||
1821 | This function provides very basic timing functionality. In Python |
|
1821 | This function provides very basic timing functionality. In Python | |
1822 | 2.3, the timeit module offers more control and sophistication, so this |
|
1822 | 2.3, the timeit module offers more control and sophistication, so this | |
1823 | could be rewritten to use it (patches welcome). |
|
1823 | could be rewritten to use it (patches welcome). | |
1824 |
|
1824 | |||
1825 | Some examples: |
|
1825 | Some examples: | |
1826 |
|
1826 | |||
1827 | In [1]: time 2**128 |
|
1827 | In [1]: time 2**128 | |
1828 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1828 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1829 | Wall time: 0.00 |
|
1829 | Wall time: 0.00 | |
1830 | Out[1]: 340282366920938463463374607431768211456L |
|
1830 | Out[1]: 340282366920938463463374607431768211456L | |
1831 |
|
1831 | |||
1832 | In [2]: n = 1000000 |
|
1832 | In [2]: n = 1000000 | |
1833 |
|
1833 | |||
1834 | In [3]: time sum(range(n)) |
|
1834 | In [3]: time sum(range(n)) | |
1835 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1835 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
1836 | Wall time: 1.37 |
|
1836 | Wall time: 1.37 | |
1837 | Out[3]: 499999500000L |
|
1837 | Out[3]: 499999500000L | |
1838 |
|
1838 | |||
1839 | In [4]: time print 'hello world' |
|
1839 | In [4]: time print 'hello world' | |
1840 | hello world |
|
1840 | hello world | |
1841 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1841 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1842 | Wall time: 0.00 |
|
1842 | Wall time: 0.00 | |
1843 |
|
1843 | |||
1844 | Note that the time needed by Python to compile the given expression |
|
1844 | Note that the time needed by Python to compile the given expression | |
1845 | will be reported if it is more than 0.1s. In this example, the |
|
1845 | will be reported if it is more than 0.1s. In this example, the | |
1846 | actual exponentiation is done by Python at compilation time, so while |
|
1846 | actual exponentiation is done by Python at compilation time, so while | |
1847 | the expression can take a noticeable amount of time to compute, that |
|
1847 | the expression can take a noticeable amount of time to compute, that | |
1848 | time is purely due to the compilation: |
|
1848 | time is purely due to the compilation: | |
1849 |
|
1849 | |||
1850 | In [5]: time 3**9999; |
|
1850 | In [5]: time 3**9999; | |
1851 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1851 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1852 | Wall time: 0.00 s |
|
1852 | Wall time: 0.00 s | |
1853 |
|
1853 | |||
1854 | In [6]: time 3**999999; |
|
1854 | In [6]: time 3**999999; | |
1855 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1855 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1856 | Wall time: 0.00 s |
|
1856 | Wall time: 0.00 s | |
1857 | Compiler : 0.78 s |
|
1857 | Compiler : 0.78 s | |
1858 | """ |
|
1858 | """ | |
1859 |
|
1859 | |||
1860 | # fail immediately if the given expression can't be compiled |
|
1860 | # fail immediately if the given expression can't be compiled | |
1861 |
|
1861 | |||
1862 | expr = self.shell.prefilter(parameter_s,False) |
|
1862 | expr = self.shell.prefilter(parameter_s,False) | |
1863 |
|
1863 | |||
1864 | # Minimum time above which compilation time will be reported |
|
1864 | # Minimum time above which compilation time will be reported | |
1865 | tc_min = 0.1 |
|
1865 | tc_min = 0.1 | |
1866 |
|
1866 | |||
1867 | try: |
|
1867 | try: | |
1868 | mode = 'eval' |
|
1868 | mode = 'eval' | |
1869 | t0 = clock() |
|
1869 | t0 = clock() | |
1870 | code = compile(expr,'<timed eval>',mode) |
|
1870 | code = compile(expr,'<timed eval>',mode) | |
1871 | tc = clock()-t0 |
|
1871 | tc = clock()-t0 | |
1872 | except SyntaxError: |
|
1872 | except SyntaxError: | |
1873 | mode = 'exec' |
|
1873 | mode = 'exec' | |
1874 | t0 = clock() |
|
1874 | t0 = clock() | |
1875 | code = compile(expr,'<timed exec>',mode) |
|
1875 | code = compile(expr,'<timed exec>',mode) | |
1876 | tc = clock()-t0 |
|
1876 | tc = clock()-t0 | |
1877 | # skew measurement as little as possible |
|
1877 | # skew measurement as little as possible | |
1878 | glob = self.shell.user_ns |
|
1878 | glob = self.shell.user_ns | |
1879 | clk = clock2 |
|
1879 | clk = clock2 | |
1880 | wtime = time.time |
|
1880 | wtime = time.time | |
1881 | # time execution |
|
1881 | # time execution | |
1882 | wall_st = wtime() |
|
1882 | wall_st = wtime() | |
1883 | if mode=='eval': |
|
1883 | if mode=='eval': | |
1884 | st = clk() |
|
1884 | st = clk() | |
1885 | out = eval(code,glob) |
|
1885 | out = eval(code,glob) | |
1886 | end = clk() |
|
1886 | end = clk() | |
1887 | else: |
|
1887 | else: | |
1888 | st = clk() |
|
1888 | st = clk() | |
1889 | exec code in glob |
|
1889 | exec code in glob | |
1890 | end = clk() |
|
1890 | end = clk() | |
1891 | out = None |
|
1891 | out = None | |
1892 | wall_end = wtime() |
|
1892 | wall_end = wtime() | |
1893 | # Compute actual times and report |
|
1893 | # Compute actual times and report | |
1894 | wall_time = wall_end-wall_st |
|
1894 | wall_time = wall_end-wall_st | |
1895 | cpu_user = end[0]-st[0] |
|
1895 | cpu_user = end[0]-st[0] | |
1896 | cpu_sys = end[1]-st[1] |
|
1896 | cpu_sys = end[1]-st[1] | |
1897 | cpu_tot = cpu_user+cpu_sys |
|
1897 | cpu_tot = cpu_user+cpu_sys | |
1898 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1898 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
1899 | (cpu_user,cpu_sys,cpu_tot) |
|
1899 | (cpu_user,cpu_sys,cpu_tot) | |
1900 | print "Wall time: %.2f s" % wall_time |
|
1900 | print "Wall time: %.2f s" % wall_time | |
1901 | if tc > tc_min: |
|
1901 | if tc > tc_min: | |
1902 | print "Compiler : %.2f s" % tc |
|
1902 | print "Compiler : %.2f s" % tc | |
1903 | return out |
|
1903 | return out | |
1904 |
|
1904 | |||
1905 | def magic_macro(self,parameter_s = ''): |
|
1905 | def magic_macro(self,parameter_s = ''): | |
1906 | """Define a set of input lines as a macro for future re-execution. |
|
1906 | """Define a set of input lines as a macro for future re-execution. | |
1907 |
|
1907 | |||
1908 | Usage:\\ |
|
1908 | Usage:\\ | |
1909 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1909 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... | |
1910 |
|
1910 | |||
1911 | Options: |
|
1911 | Options: | |
1912 |
|
1912 | |||
1913 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1913 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1914 | so that magics are loaded in their transformed version to valid |
|
1914 | so that magics are loaded in their transformed version to valid | |
1915 | Python. If this option is given, the raw input as typed as the |
|
1915 | Python. If this option is given, the raw input as typed as the | |
1916 | command line is used instead. |
|
1916 | command line is used instead. | |
1917 |
|
1917 | |||
1918 | This will define a global variable called `name` which is a string |
|
1918 | This will define a global variable called `name` which is a string | |
1919 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1919 | made of joining the slices and lines you specify (n1,n2,... numbers | |
1920 | above) from your input history into a single string. This variable |
|
1920 | above) from your input history into a single string. This variable | |
1921 | acts like an automatic function which re-executes those lines as if |
|
1921 | acts like an automatic function which re-executes those lines as if | |
1922 | you had typed them. You just type 'name' at the prompt and the code |
|
1922 | you had typed them. You just type 'name' at the prompt and the code | |
1923 | executes. |
|
1923 | executes. | |
1924 |
|
1924 | |||
1925 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
1925 | The notation for indicating number ranges is: n1-n2 means 'use line | |
1926 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
1926 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means | |
1927 | using the lines numbered 5,6 and 7. |
|
1927 | using the lines numbered 5,6 and 7. | |
1928 |
|
1928 | |||
1929 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1929 | Note: as a 'hidden' feature, you can also use traditional python slice | |
1930 | notation, where N:M means numbers N through M-1. |
|
1930 | notation, where N:M means numbers N through M-1. | |
1931 |
|
1931 | |||
1932 | For example, if your history contains (%hist prints it): |
|
1932 | For example, if your history contains (%hist prints it): | |
1933 |
|
1933 | |||
1934 | 44: x=1\\ |
|
1934 | 44: x=1\\ | |
1935 | 45: y=3\\ |
|
1935 | 45: y=3\\ | |
1936 | 46: z=x+y\\ |
|
1936 | 46: z=x+y\\ | |
1937 | 47: print x\\ |
|
1937 | 47: print x\\ | |
1938 | 48: a=5\\ |
|
1938 | 48: a=5\\ | |
1939 | 49: print 'x',x,'y',y\\ |
|
1939 | 49: print 'x',x,'y',y\\ | |
1940 |
|
1940 | |||
1941 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1941 | you can create a macro with lines 44 through 47 (included) and line 49 | |
1942 | called my_macro with: |
|
1942 | called my_macro with: | |
1943 |
|
1943 | |||
1944 | In [51]: %macro my_macro 44-47 49 |
|
1944 | In [51]: %macro my_macro 44-47 49 | |
1945 |
|
1945 | |||
1946 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1946 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
1947 | in one pass. |
|
1947 | in one pass. | |
1948 |
|
1948 | |||
1949 | You don't need to give the line-numbers in order, and any given line |
|
1949 | You don't need to give the line-numbers in order, and any given line | |
1950 | number can appear multiple times. You can assemble macros with any |
|
1950 | number can appear multiple times. You can assemble macros with any | |
1951 | lines from your input history in any order. |
|
1951 | lines from your input history in any order. | |
1952 |
|
1952 | |||
1953 | The macro is a simple object which holds its value in an attribute, |
|
1953 | The macro is a simple object which holds its value in an attribute, | |
1954 | but IPython's display system checks for macros and executes them as |
|
1954 | but IPython's display system checks for macros and executes them as | |
1955 | code instead of printing them when you type their name. |
|
1955 | code instead of printing them when you type their name. | |
1956 |
|
1956 | |||
1957 | You can view a macro's contents by explicitly printing it with: |
|
1957 | You can view a macro's contents by explicitly printing it with: | |
1958 |
|
1958 | |||
1959 | 'print macro_name'. |
|
1959 | 'print macro_name'. | |
1960 |
|
1960 | |||
1961 | For one-off cases which DON'T contain magic function calls in them you |
|
1961 | For one-off cases which DON'T contain magic function calls in them you | |
1962 | can obtain similar results by explicitly executing slices from your |
|
1962 | can obtain similar results by explicitly executing slices from your | |
1963 | input history with: |
|
1963 | input history with: | |
1964 |
|
1964 | |||
1965 | In [60]: exec In[44:48]+In[49]""" |
|
1965 | In [60]: exec In[44:48]+In[49]""" | |
1966 |
|
1966 | |||
1967 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
1967 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
1968 | if not args: |
|
1968 | if not args: | |
1969 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] |
|
1969 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] | |
1970 | macs.sort() |
|
1970 | macs.sort() | |
1971 | return macs |
|
1971 | return macs | |
1972 | if len(args) == 1: |
|
1972 | if len(args) == 1: | |
1973 | raise UsageError( |
|
1973 | raise UsageError( | |
1974 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
1974 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") | |
1975 | name,ranges = args[0], args[1:] |
|
1975 | name,ranges = args[0], args[1:] | |
1976 |
|
1976 | |||
1977 | #print 'rng',ranges # dbg |
|
1977 | #print 'rng',ranges # dbg | |
1978 | lines = self.extract_input_slices(ranges,opts.has_key('r')) |
|
1978 | lines = self.extract_input_slices(ranges,opts.has_key('r')) | |
1979 | macro = Macro(lines) |
|
1979 | macro = Macro(lines) | |
1980 | self.shell.user_ns.update({name:macro}) |
|
1980 | self.shell.user_ns.update({name:macro}) | |
1981 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
1981 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
1982 | print 'Macro contents:' |
|
1982 | print 'Macro contents:' | |
1983 | print macro, |
|
1983 | print macro, | |
1984 |
|
1984 | |||
1985 | def magic_save(self,parameter_s = ''): |
|
1985 | def magic_save(self,parameter_s = ''): | |
1986 | """Save a set of lines to a given filename. |
|
1986 | """Save a set of lines to a given filename. | |
1987 |
|
1987 | |||
1988 | Usage:\\ |
|
1988 | Usage:\\ | |
1989 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
1989 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
1990 |
|
1990 | |||
1991 | Options: |
|
1991 | Options: | |
1992 |
|
1992 | |||
1993 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1993 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1994 | so that magics are loaded in their transformed version to valid |
|
1994 | so that magics are loaded in their transformed version to valid | |
1995 | Python. If this option is given, the raw input as typed as the |
|
1995 | Python. If this option is given, the raw input as typed as the | |
1996 | command line is used instead. |
|
1996 | command line is used instead. | |
1997 |
|
1997 | |||
1998 | This function uses the same syntax as %macro for line extraction, but |
|
1998 | This function uses the same syntax as %macro for line extraction, but | |
1999 | instead of creating a macro it saves the resulting string to the |
|
1999 | instead of creating a macro it saves the resulting string to the | |
2000 | filename you specify. |
|
2000 | filename you specify. | |
2001 |
|
2001 | |||
2002 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2002 | It adds a '.py' extension to the file if you don't do so yourself, and | |
2003 | it asks for confirmation before overwriting existing files.""" |
|
2003 | it asks for confirmation before overwriting existing files.""" | |
2004 |
|
2004 | |||
2005 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2005 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2006 | fname,ranges = args[0], args[1:] |
|
2006 | fname,ranges = args[0], args[1:] | |
2007 | if not fname.endswith('.py'): |
|
2007 | if not fname.endswith('.py'): | |
2008 | fname += '.py' |
|
2008 | fname += '.py' | |
2009 | if os.path.isfile(fname): |
|
2009 | if os.path.isfile(fname): | |
2010 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2010 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
2011 | if ans.lower() not in ['y','yes']: |
|
2011 | if ans.lower() not in ['y','yes']: | |
2012 | print 'Operation cancelled.' |
|
2012 | print 'Operation cancelled.' | |
2013 | return |
|
2013 | return | |
2014 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) |
|
2014 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) | |
2015 | f = file(fname,'w') |
|
2015 | f = file(fname,'w') | |
2016 | f.write(cmds) |
|
2016 | f.write(cmds) | |
2017 | f.close() |
|
2017 | f.close() | |
2018 | print 'The following commands were written to file `%s`:' % fname |
|
2018 | print 'The following commands were written to file `%s`:' % fname | |
2019 | print cmds |
|
2019 | print cmds | |
2020 |
|
2020 | |||
2021 | def _edit_macro(self,mname,macro): |
|
2021 | def _edit_macro(self,mname,macro): | |
2022 | """open an editor with the macro data in a file""" |
|
2022 | """open an editor with the macro data in a file""" | |
2023 | filename = self.shell.mktempfile(macro.value) |
|
2023 | filename = self.shell.mktempfile(macro.value) | |
2024 | self.shell.hooks.editor(filename) |
|
2024 | self.shell.hooks.editor(filename) | |
2025 |
|
2025 | |||
2026 | # and make a new macro object, to replace the old one |
|
2026 | # and make a new macro object, to replace the old one | |
2027 | mfile = open(filename) |
|
2027 | mfile = open(filename) | |
2028 | mvalue = mfile.read() |
|
2028 | mvalue = mfile.read() | |
2029 | mfile.close() |
|
2029 | mfile.close() | |
2030 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2030 | self.shell.user_ns[mname] = Macro(mvalue) | |
2031 |
|
2031 | |||
2032 | def magic_ed(self,parameter_s=''): |
|
2032 | def magic_ed(self,parameter_s=''): | |
2033 | """Alias to %edit.""" |
|
2033 | """Alias to %edit.""" | |
2034 | return self.magic_edit(parameter_s) |
|
2034 | return self.magic_edit(parameter_s) | |
2035 |
|
2035 | |||
2036 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2036 | def magic_edit(self,parameter_s='',last_call=['','']): | |
2037 | """Bring up an editor and execute the resulting code. |
|
2037 | """Bring up an editor and execute the resulting code. | |
2038 |
|
2038 | |||
2039 | Usage: |
|
2039 | Usage: | |
2040 | %edit [options] [args] |
|
2040 | %edit [options] [args] | |
2041 |
|
2041 | |||
2042 | %edit runs IPython's editor hook. The default version of this hook is |
|
2042 | %edit runs IPython's editor hook. The default version of this hook is | |
2043 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
2043 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
2044 | environment variable $EDITOR. If this isn't found, it will default to |
|
2044 | environment variable $EDITOR. If this isn't found, it will default to | |
2045 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
2045 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
2046 | docstring for how to change the editor hook. |
|
2046 | docstring for how to change the editor hook. | |
2047 |
|
2047 | |||
2048 | You can also set the value of this editor via the command line option |
|
2048 | You can also set the value of this editor via the command line option | |
2049 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
2049 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
2050 | specifically for IPython an editor different from your typical default |
|
2050 | specifically for IPython an editor different from your typical default | |
2051 | (and for Windows users who typically don't set environment variables). |
|
2051 | (and for Windows users who typically don't set environment variables). | |
2052 |
|
2052 | |||
2053 | This command allows you to conveniently edit multi-line code right in |
|
2053 | This command allows you to conveniently edit multi-line code right in | |
2054 | your IPython session. |
|
2054 | your IPython session. | |
2055 |
|
2055 | |||
2056 | If called without arguments, %edit opens up an empty editor with a |
|
2056 | If called without arguments, %edit opens up an empty editor with a | |
2057 | temporary file and will execute the contents of this file when you |
|
2057 | temporary file and will execute the contents of this file when you | |
2058 | close it (don't forget to save it!). |
|
2058 | close it (don't forget to save it!). | |
2059 |
|
2059 | |||
2060 |
|
2060 | |||
2061 | Options: |
|
2061 | Options: | |
2062 |
|
2062 | |||
2063 | -n <number>: open the editor at a specified line number. By default, |
|
2063 | -n <number>: open the editor at a specified line number. By default, | |
2064 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2064 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
2065 | you can configure this by providing your own modified hook if your |
|
2065 | you can configure this by providing your own modified hook if your | |
2066 | favorite editor supports line-number specifications with a different |
|
2066 | favorite editor supports line-number specifications with a different | |
2067 | syntax. |
|
2067 | syntax. | |
2068 |
|
2068 | |||
2069 | -p: this will call the editor with the same data as the previous time |
|
2069 | -p: this will call the editor with the same data as the previous time | |
2070 | it was used, regardless of how long ago (in your current session) it |
|
2070 | it was used, regardless of how long ago (in your current session) it | |
2071 | was. |
|
2071 | was. | |
2072 |
|
2072 | |||
2073 | -r: use 'raw' input. This option only applies to input taken from the |
|
2073 | -r: use 'raw' input. This option only applies to input taken from the | |
2074 | user's history. By default, the 'processed' history is used, so that |
|
2074 | user's history. By default, the 'processed' history is used, so that | |
2075 | magics are loaded in their transformed version to valid Python. If |
|
2075 | magics are loaded in their transformed version to valid Python. If | |
2076 | this option is given, the raw input as typed as the command line is |
|
2076 | this option is given, the raw input as typed as the command line is | |
2077 | used instead. When you exit the editor, it will be executed by |
|
2077 | used instead. When you exit the editor, it will be executed by | |
2078 | IPython's own processor. |
|
2078 | IPython's own processor. | |
2079 |
|
2079 | |||
2080 | -x: do not execute the edited code immediately upon exit. This is |
|
2080 | -x: do not execute the edited code immediately upon exit. This is | |
2081 | mainly useful if you are editing programs which need to be called with |
|
2081 | mainly useful if you are editing programs which need to be called with | |
2082 | command line arguments, which you can then do using %run. |
|
2082 | command line arguments, which you can then do using %run. | |
2083 |
|
2083 | |||
2084 |
|
2084 | |||
2085 | Arguments: |
|
2085 | Arguments: | |
2086 |
|
2086 | |||
2087 | If arguments are given, the following possibilites exist: |
|
2087 | If arguments are given, the following possibilites exist: | |
2088 |
|
2088 | |||
2089 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
2089 | - The arguments are numbers or pairs of colon-separated numbers (like | |
2090 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
2090 | 1 4:8 9). These are interpreted as lines of previous input to be | |
2091 | loaded into the editor. The syntax is the same of the %macro command. |
|
2091 | loaded into the editor. The syntax is the same of the %macro command. | |
2092 |
|
2092 | |||
2093 | - If the argument doesn't start with a number, it is evaluated as a |
|
2093 | - If the argument doesn't start with a number, it is evaluated as a | |
2094 | variable and its contents loaded into the editor. You can thus edit |
|
2094 | variable and its contents loaded into the editor. You can thus edit | |
2095 | any string which contains python code (including the result of |
|
2095 | any string which contains python code (including the result of | |
2096 | previous edits). |
|
2096 | previous edits). | |
2097 |
|
2097 | |||
2098 | - If the argument is the name of an object (other than a string), |
|
2098 | - If the argument is the name of an object (other than a string), | |
2099 | IPython will try to locate the file where it was defined and open the |
|
2099 | IPython will try to locate the file where it was defined and open the | |
2100 | editor at the point where it is defined. You can use `%edit function` |
|
2100 | editor at the point where it is defined. You can use `%edit function` | |
2101 | to load an editor exactly at the point where 'function' is defined, |
|
2101 | to load an editor exactly at the point where 'function' is defined, | |
2102 | edit it and have the file be executed automatically. |
|
2102 | edit it and have the file be executed automatically. | |
2103 |
|
2103 | |||
2104 | If the object is a macro (see %macro for details), this opens up your |
|
2104 | If the object is a macro (see %macro for details), this opens up your | |
2105 | specified editor with a temporary file containing the macro's data. |
|
2105 | specified editor with a temporary file containing the macro's data. | |
2106 | Upon exit, the macro is reloaded with the contents of the file. |
|
2106 | Upon exit, the macro is reloaded with the contents of the file. | |
2107 |
|
2107 | |||
2108 | Note: opening at an exact line is only supported under Unix, and some |
|
2108 | Note: opening at an exact line is only supported under Unix, and some | |
2109 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2109 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
2110 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2110 | '+NUMBER' parameter necessary for this feature. Good editors like | |
2111 | (X)Emacs, vi, jed, pico and joe all do. |
|
2111 | (X)Emacs, vi, jed, pico and joe all do. | |
2112 |
|
2112 | |||
2113 | - If the argument is not found as a variable, IPython will look for a |
|
2113 | - If the argument is not found as a variable, IPython will look for a | |
2114 | file with that name (adding .py if necessary) and load it into the |
|
2114 | file with that name (adding .py if necessary) and load it into the | |
2115 | editor. It will execute its contents with execfile() when you exit, |
|
2115 | editor. It will execute its contents with execfile() when you exit, | |
2116 | loading any code in the file into your interactive namespace. |
|
2116 | loading any code in the file into your interactive namespace. | |
2117 |
|
2117 | |||
2118 | After executing your code, %edit will return as output the code you |
|
2118 | After executing your code, %edit will return as output the code you | |
2119 | typed in the editor (except when it was an existing file). This way |
|
2119 | typed in the editor (except when it was an existing file). This way | |
2120 | you can reload the code in further invocations of %edit as a variable, |
|
2120 | you can reload the code in further invocations of %edit as a variable, | |
2121 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2121 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
2122 | the output. |
|
2122 | the output. | |
2123 |
|
2123 | |||
2124 | Note that %edit is also available through the alias %ed. |
|
2124 | Note that %edit is also available through the alias %ed. | |
2125 |
|
2125 | |||
2126 | This is an example of creating a simple function inside the editor and |
|
2126 | This is an example of creating a simple function inside the editor and | |
2127 | then modifying it. First, start up the editor: |
|
2127 | then modifying it. First, start up the editor: | |
2128 |
|
2128 | |||
2129 | In [1]: ed\\ |
|
2129 | In [1]: ed\\ | |
2130 | Editing... done. Executing edited code...\\ |
|
2130 | Editing... done. Executing edited code...\\ | |
2131 | Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n' |
|
2131 | Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n' | |
2132 |
|
2132 | |||
2133 | We can then call the function foo(): |
|
2133 | We can then call the function foo(): | |
2134 |
|
2134 | |||
2135 | In [2]: foo()\\ |
|
2135 | In [2]: foo()\\ | |
2136 | foo() was defined in an editing session |
|
2136 | foo() was defined in an editing session | |
2137 |
|
2137 | |||
2138 | Now we edit foo. IPython automatically loads the editor with the |
|
2138 | Now we edit foo. IPython automatically loads the editor with the | |
2139 | (temporary) file where foo() was previously defined: |
|
2139 | (temporary) file where foo() was previously defined: | |
2140 |
|
2140 | |||
2141 | In [3]: ed foo\\ |
|
2141 | In [3]: ed foo\\ | |
2142 | Editing... done. Executing edited code... |
|
2142 | Editing... done. Executing edited code... | |
2143 |
|
2143 | |||
2144 | And if we call foo() again we get the modified version: |
|
2144 | And if we call foo() again we get the modified version: | |
2145 |
|
2145 | |||
2146 | In [4]: foo()\\ |
|
2146 | In [4]: foo()\\ | |
2147 | foo() has now been changed! |
|
2147 | foo() has now been changed! | |
2148 |
|
2148 | |||
2149 | Here is an example of how to edit a code snippet successive |
|
2149 | Here is an example of how to edit a code snippet successive | |
2150 | times. First we call the editor: |
|
2150 | times. First we call the editor: | |
2151 |
|
2151 | |||
2152 | In [8]: ed\\ |
|
2152 | In [8]: ed\\ | |
2153 | Editing... done. Executing edited code...\\ |
|
2153 | Editing... done. Executing edited code...\\ | |
2154 | hello\\ |
|
2154 | hello\\ | |
2155 | Out[8]: "print 'hello'\\n" |
|
2155 | Out[8]: "print 'hello'\\n" | |
2156 |
|
2156 | |||
2157 | Now we call it again with the previous output (stored in _): |
|
2157 | Now we call it again with the previous output (stored in _): | |
2158 |
|
2158 | |||
2159 | In [9]: ed _\\ |
|
2159 | In [9]: ed _\\ | |
2160 | Editing... done. Executing edited code...\\ |
|
2160 | Editing... done. Executing edited code...\\ | |
2161 | hello world\\ |
|
2161 | hello world\\ | |
2162 | Out[9]: "print 'hello world'\\n" |
|
2162 | Out[9]: "print 'hello world'\\n" | |
2163 |
|
2163 | |||
2164 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2164 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
2165 |
|
2165 | |||
2166 | In [10]: ed _8\\ |
|
2166 | In [10]: ed _8\\ | |
2167 | Editing... done. Executing edited code...\\ |
|
2167 | Editing... done. Executing edited code...\\ | |
2168 | hello again\\ |
|
2168 | hello again\\ | |
2169 | Out[10]: "print 'hello again'\\n" |
|
2169 | Out[10]: "print 'hello again'\\n" | |
2170 |
|
2170 | |||
2171 |
|
2171 | |||
2172 | Changing the default editor hook: |
|
2172 | Changing the default editor hook: | |
2173 |
|
2173 | |||
2174 | If you wish to write your own editor hook, you can put it in a |
|
2174 | If you wish to write your own editor hook, you can put it in a | |
2175 | configuration file which you load at startup time. The default hook |
|
2175 | configuration file which you load at startup time. The default hook | |
2176 | is defined in the IPython.hooks module, and you can use that as a |
|
2176 | is defined in the IPython.hooks module, and you can use that as a | |
2177 | starting example for further modifications. That file also has |
|
2177 | starting example for further modifications. That file also has | |
2178 | general instructions on how to set a new hook for use once you've |
|
2178 | general instructions on how to set a new hook for use once you've | |
2179 | defined it.""" |
|
2179 | defined it.""" | |
2180 |
|
2180 | |||
2181 | # FIXME: This function has become a convoluted mess. It needs a |
|
2181 | # FIXME: This function has become a convoluted mess. It needs a | |
2182 | # ground-up rewrite with clean, simple logic. |
|
2182 | # ground-up rewrite with clean, simple logic. | |
2183 |
|
2183 | |||
2184 | def make_filename(arg): |
|
2184 | def make_filename(arg): | |
2185 | "Make a filename from the given args" |
|
2185 | "Make a filename from the given args" | |
2186 | try: |
|
2186 | try: | |
2187 | filename = get_py_filename(arg) |
|
2187 | filename = get_py_filename(arg) | |
2188 | except IOError: |
|
2188 | except IOError: | |
2189 | if args.endswith('.py'): |
|
2189 | if args.endswith('.py'): | |
2190 | filename = arg |
|
2190 | filename = arg | |
2191 | else: |
|
2191 | else: | |
2192 | filename = None |
|
2192 | filename = None | |
2193 | return filename |
|
2193 | return filename | |
2194 |
|
2194 | |||
2195 | # custom exceptions |
|
2195 | # custom exceptions | |
2196 | class DataIsObject(Exception): pass |
|
2196 | class DataIsObject(Exception): pass | |
2197 |
|
2197 | |||
2198 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2198 | opts,args = self.parse_options(parameter_s,'prxn:') | |
2199 | # Set a few locals from the options for convenience: |
|
2199 | # Set a few locals from the options for convenience: | |
2200 | opts_p = opts.has_key('p') |
|
2200 | opts_p = opts.has_key('p') | |
2201 | opts_r = opts.has_key('r') |
|
2201 | opts_r = opts.has_key('r') | |
2202 |
|
2202 | |||
2203 | # Default line number value |
|
2203 | # Default line number value | |
2204 | lineno = opts.get('n',None) |
|
2204 | lineno = opts.get('n',None) | |
2205 |
|
2205 | |||
2206 | if opts_p: |
|
2206 | if opts_p: | |
2207 | args = '_%s' % last_call[0] |
|
2207 | args = '_%s' % last_call[0] | |
2208 | if not self.shell.user_ns.has_key(args): |
|
2208 | if not self.shell.user_ns.has_key(args): | |
2209 | args = last_call[1] |
|
2209 | args = last_call[1] | |
2210 |
|
2210 | |||
2211 | # use last_call to remember the state of the previous call, but don't |
|
2211 | # use last_call to remember the state of the previous call, but don't | |
2212 | # let it be clobbered by successive '-p' calls. |
|
2212 | # let it be clobbered by successive '-p' calls. | |
2213 | try: |
|
2213 | try: | |
2214 | last_call[0] = self.shell.outputcache.prompt_count |
|
2214 | last_call[0] = self.shell.outputcache.prompt_count | |
2215 | if not opts_p: |
|
2215 | if not opts_p: | |
2216 | last_call[1] = parameter_s |
|
2216 | last_call[1] = parameter_s | |
2217 | except: |
|
2217 | except: | |
2218 | pass |
|
2218 | pass | |
2219 |
|
2219 | |||
2220 | # by default this is done with temp files, except when the given |
|
2220 | # by default this is done with temp files, except when the given | |
2221 | # arg is a filename |
|
2221 | # arg is a filename | |
2222 | use_temp = 1 |
|
2222 | use_temp = 1 | |
2223 |
|
2223 | |||
2224 | if re.match(r'\d',args): |
|
2224 | if re.match(r'\d',args): | |
2225 | # Mode where user specifies ranges of lines, like in %macro. |
|
2225 | # Mode where user specifies ranges of lines, like in %macro. | |
2226 | # This means that you can't edit files whose names begin with |
|
2226 | # This means that you can't edit files whose names begin with | |
2227 | # numbers this way. Tough. |
|
2227 | # numbers this way. Tough. | |
2228 | ranges = args.split() |
|
2228 | ranges = args.split() | |
2229 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
2229 | data = ''.join(self.extract_input_slices(ranges,opts_r)) | |
2230 | elif args.endswith('.py'): |
|
2230 | elif args.endswith('.py'): | |
2231 | filename = make_filename(args) |
|
2231 | filename = make_filename(args) | |
2232 | data = '' |
|
2232 | data = '' | |
2233 | use_temp = 0 |
|
2233 | use_temp = 0 | |
2234 | elif args: |
|
2234 | elif args: | |
2235 | try: |
|
2235 | try: | |
2236 | # Load the parameter given as a variable. If not a string, |
|
2236 | # Load the parameter given as a variable. If not a string, | |
2237 | # process it as an object instead (below) |
|
2237 | # process it as an object instead (below) | |
2238 |
|
2238 | |||
2239 | #print '*** args',args,'type',type(args) # dbg |
|
2239 | #print '*** args',args,'type',type(args) # dbg | |
2240 | data = eval(args,self.shell.user_ns) |
|
2240 | data = eval(args,self.shell.user_ns) | |
2241 | if not type(data) in StringTypes: |
|
2241 | if not type(data) in StringTypes: | |
2242 | raise DataIsObject |
|
2242 | raise DataIsObject | |
2243 |
|
2243 | |||
2244 | except (NameError,SyntaxError): |
|
2244 | except (NameError,SyntaxError): | |
2245 | # given argument is not a variable, try as a filename |
|
2245 | # given argument is not a variable, try as a filename | |
2246 | filename = make_filename(args) |
|
2246 | filename = make_filename(args) | |
2247 | if filename is None: |
|
2247 | if filename is None: | |
2248 | warn("Argument given (%s) can't be found as a variable " |
|
2248 | warn("Argument given (%s) can't be found as a variable " | |
2249 | "or as a filename." % args) |
|
2249 | "or as a filename." % args) | |
2250 | return |
|
2250 | return | |
2251 |
|
2251 | |||
2252 | data = '' |
|
2252 | data = '' | |
2253 | use_temp = 0 |
|
2253 | use_temp = 0 | |
2254 | except DataIsObject: |
|
2254 | except DataIsObject: | |
2255 |
|
2255 | |||
2256 | # macros have a special edit function |
|
2256 | # macros have a special edit function | |
2257 | if isinstance(data,Macro): |
|
2257 | if isinstance(data,Macro): | |
2258 | self._edit_macro(args,data) |
|
2258 | self._edit_macro(args,data) | |
2259 | return |
|
2259 | return | |
2260 |
|
2260 | |||
2261 | # For objects, try to edit the file where they are defined |
|
2261 | # For objects, try to edit the file where they are defined | |
2262 | try: |
|
2262 | try: | |
2263 | filename = inspect.getabsfile(data) |
|
2263 | filename = inspect.getabsfile(data) | |
2264 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2264 | if 'fakemodule' in filename.lower() and inspect.isclass(data): | |
2265 | # class created by %edit? Try to find source |
|
2265 | # class created by %edit? Try to find source | |
2266 | # by looking for method definitions instead, the |
|
2266 | # by looking for method definitions instead, the | |
2267 | # __module__ in those classes is FakeModule. |
|
2267 | # __module__ in those classes is FakeModule. | |
2268 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2268 | attrs = [getattr(data, aname) for aname in dir(data)] | |
2269 | for attr in attrs: |
|
2269 | for attr in attrs: | |
2270 | if not inspect.ismethod(attr): |
|
2270 | if not inspect.ismethod(attr): | |
2271 | continue |
|
2271 | continue | |
2272 | filename = inspect.getabsfile(attr) |
|
2272 | filename = inspect.getabsfile(attr) | |
2273 | if filename and 'fakemodule' not in filename.lower(): |
|
2273 | if filename and 'fakemodule' not in filename.lower(): | |
2274 | # change the attribute to be the edit target instead |
|
2274 | # change the attribute to be the edit target instead | |
2275 | data = attr |
|
2275 | data = attr | |
2276 | break |
|
2276 | break | |
2277 |
|
2277 | |||
2278 | datafile = 1 |
|
2278 | datafile = 1 | |
2279 | except TypeError: |
|
2279 | except TypeError: | |
2280 | filename = make_filename(args) |
|
2280 | filename = make_filename(args) | |
2281 | datafile = 1 |
|
2281 | datafile = 1 | |
2282 | warn('Could not find file where `%s` is defined.\n' |
|
2282 | warn('Could not find file where `%s` is defined.\n' | |
2283 | 'Opening a file named `%s`' % (args,filename)) |
|
2283 | 'Opening a file named `%s`' % (args,filename)) | |
2284 | # Now, make sure we can actually read the source (if it was in |
|
2284 | # Now, make sure we can actually read the source (if it was in | |
2285 | # a temp file it's gone by now). |
|
2285 | # a temp file it's gone by now). | |
2286 | if datafile: |
|
2286 | if datafile: | |
2287 | try: |
|
2287 | try: | |
2288 | if lineno is None: |
|
2288 | if lineno is None: | |
2289 | lineno = inspect.getsourcelines(data)[1] |
|
2289 | lineno = inspect.getsourcelines(data)[1] | |
2290 | except IOError: |
|
2290 | except IOError: | |
2291 | filename = make_filename(args) |
|
2291 | filename = make_filename(args) | |
2292 | if filename is None: |
|
2292 | if filename is None: | |
2293 | warn('The file `%s` where `%s` was defined cannot ' |
|
2293 | warn('The file `%s` where `%s` was defined cannot ' | |
2294 | 'be read.' % (filename,data)) |
|
2294 | 'be read.' % (filename,data)) | |
2295 | return |
|
2295 | return | |
2296 | use_temp = 0 |
|
2296 | use_temp = 0 | |
2297 | else: |
|
2297 | else: | |
2298 | data = '' |
|
2298 | data = '' | |
2299 |
|
2299 | |||
2300 | if use_temp: |
|
2300 | if use_temp: | |
2301 | filename = self.shell.mktempfile(data) |
|
2301 | filename = self.shell.mktempfile(data) | |
2302 | print 'IPython will make a temporary file named:',filename |
|
2302 | print 'IPython will make a temporary file named:',filename | |
2303 |
|
2303 | |||
2304 | # do actual editing here |
|
2304 | # do actual editing here | |
2305 | print 'Editing...', |
|
2305 | print 'Editing...', | |
2306 | sys.stdout.flush() |
|
2306 | sys.stdout.flush() | |
2307 | self.shell.hooks.editor(filename,lineno) |
|
2307 | self.shell.hooks.editor(filename,lineno) | |
2308 | if opts.has_key('x'): # -x prevents actual execution |
|
2308 | if opts.has_key('x'): # -x prevents actual execution | |
2309 |
|
2309 | |||
2310 | else: |
|
2310 | else: | |
2311 | print 'done. Executing edited code...' |
|
2311 | print 'done. Executing edited code...' | |
2312 | if opts_r: |
|
2312 | if opts_r: | |
2313 | self.shell.runlines(file_read(filename)) |
|
2313 | self.shell.runlines(file_read(filename)) | |
2314 | else: |
|
2314 | else: | |
2315 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2315 | self.shell.safe_execfile(filename,self.shell.user_ns, | |
2316 | self.shell.user_ns) |
|
2316 | self.shell.user_ns) | |
2317 | if use_temp: |
|
2317 | if use_temp: | |
2318 | try: |
|
2318 | try: | |
2319 | return open(filename).read() |
|
2319 | return open(filename).read() | |
2320 | except IOError,msg: |
|
2320 | except IOError,msg: | |
2321 | if msg.filename == filename: |
|
2321 | if msg.filename == filename: | |
2322 | warn('File not found. Did you forget to save?') |
|
2322 | warn('File not found. Did you forget to save?') | |
2323 | return |
|
2323 | return | |
2324 | else: |
|
2324 | else: | |
2325 | self.shell.showtraceback() |
|
2325 | self.shell.showtraceback() | |
2326 |
|
2326 | |||
2327 | def magic_xmode(self,parameter_s = ''): |
|
2327 | def magic_xmode(self,parameter_s = ''): | |
2328 | """Switch modes for the exception handlers. |
|
2328 | """Switch modes for the exception handlers. | |
2329 |
|
2329 | |||
2330 | Valid modes: Plain, Context and Verbose. |
|
2330 | Valid modes: Plain, Context and Verbose. | |
2331 |
|
2331 | |||
2332 | If called without arguments, acts as a toggle.""" |
|
2332 | If called without arguments, acts as a toggle.""" | |
2333 |
|
2333 | |||
2334 | def xmode_switch_err(name): |
|
2334 | def xmode_switch_err(name): | |
2335 | warn('Error changing %s exception modes.\n%s' % |
|
2335 | warn('Error changing %s exception modes.\n%s' % | |
2336 | (name,sys.exc_info()[1])) |
|
2336 | (name,sys.exc_info()[1])) | |
2337 |
|
2337 | |||
2338 | shell = self.shell |
|
2338 | shell = self.shell | |
2339 | new_mode = parameter_s.strip().capitalize() |
|
2339 | new_mode = parameter_s.strip().capitalize() | |
2340 | try: |
|
2340 | try: | |
2341 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2341 | shell.InteractiveTB.set_mode(mode=new_mode) | |
2342 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2342 | print 'Exception reporting mode:',shell.InteractiveTB.mode | |
2343 | except: |
|
2343 | except: | |
2344 | xmode_switch_err('user') |
|
2344 | xmode_switch_err('user') | |
2345 |
|
2345 | |||
2346 | # threaded shells use a special handler in sys.excepthook |
|
2346 | # threaded shells use a special handler in sys.excepthook | |
2347 | if shell.isthreaded: |
|
2347 | if shell.isthreaded: | |
2348 | try: |
|
2348 | try: | |
2349 | shell.sys_excepthook.set_mode(mode=new_mode) |
|
2349 | shell.sys_excepthook.set_mode(mode=new_mode) | |
2350 | except: |
|
2350 | except: | |
2351 | xmode_switch_err('threaded') |
|
2351 | xmode_switch_err('threaded') | |
2352 |
|
2352 | |||
2353 | def magic_colors(self,parameter_s = ''): |
|
2353 | def magic_colors(self,parameter_s = ''): | |
2354 | """Switch color scheme for prompts, info system and exception handlers. |
|
2354 | """Switch color scheme for prompts, info system and exception handlers. | |
2355 |
|
2355 | |||
2356 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2356 | Currently implemented schemes: NoColor, Linux, LightBG. | |
2357 |
|
2357 | |||
2358 | Color scheme names are not case-sensitive.""" |
|
2358 | Color scheme names are not case-sensitive.""" | |
2359 |
|
2359 | |||
2360 | def color_switch_err(name): |
|
2360 | def color_switch_err(name): | |
2361 | warn('Error changing %s color schemes.\n%s' % |
|
2361 | warn('Error changing %s color schemes.\n%s' % | |
2362 | (name,sys.exc_info()[1])) |
|
2362 | (name,sys.exc_info()[1])) | |
2363 |
|
2363 | |||
2364 |
|
2364 | |||
2365 | new_scheme = parameter_s.strip() |
|
2365 | new_scheme = parameter_s.strip() | |
2366 | if not new_scheme: |
|
2366 | if not new_scheme: | |
2367 | raise UsageError( |
|
2367 | raise UsageError( | |
2368 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2368 | "%colors: you must specify a color scheme. See '%colors?'") | |
2369 | return |
|
2369 | return | |
2370 | # local shortcut |
|
2370 | # local shortcut | |
2371 | shell = self.shell |
|
2371 | shell = self.shell | |
2372 |
|
2372 | |||
2373 | import IPython.rlineimpl as readline |
|
2373 | import IPython.rlineimpl as readline | |
2374 |
|
2374 | |||
2375 | if not readline.have_readline and sys.platform == "win32": |
|
2375 | if not readline.have_readline and sys.platform == "win32": | |
2376 | msg = """\ |
|
2376 | msg = """\ | |
2377 | Proper color support under MS Windows requires the pyreadline library. |
|
2377 | Proper color support under MS Windows requires the pyreadline library. | |
2378 | You can find it at: |
|
2378 | You can find it at: | |
2379 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2379 | http://ipython.scipy.org/moin/PyReadline/Intro | |
2380 | Gary's readline needs the ctypes module, from: |
|
2380 | Gary's readline needs the ctypes module, from: | |
2381 | http://starship.python.net/crew/theller/ctypes |
|
2381 | http://starship.python.net/crew/theller/ctypes | |
2382 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2382 | (Note that ctypes is already part of Python versions 2.5 and newer). | |
2383 |
|
2383 | |||
2384 | Defaulting color scheme to 'NoColor'""" |
|
2384 | Defaulting color scheme to 'NoColor'""" | |
2385 | new_scheme = 'NoColor' |
|
2385 | new_scheme = 'NoColor' | |
2386 | warn(msg) |
|
2386 | warn(msg) | |
2387 |
|
2387 | |||
2388 | # readline option is 0 |
|
2388 | # readline option is 0 | |
2389 | if not shell.has_readline: |
|
2389 | if not shell.has_readline: | |
2390 | new_scheme = 'NoColor' |
|
2390 | new_scheme = 'NoColor' | |
2391 |
|
2391 | |||
2392 | # Set prompt colors |
|
2392 | # Set prompt colors | |
2393 | try: |
|
2393 | try: | |
2394 | shell.outputcache.set_colors(new_scheme) |
|
2394 | shell.outputcache.set_colors(new_scheme) | |
2395 | except: |
|
2395 | except: | |
2396 | color_switch_err('prompt') |
|
2396 | color_switch_err('prompt') | |
2397 | else: |
|
2397 | else: | |
2398 | shell.rc.colors = \ |
|
2398 | shell.rc.colors = \ | |
2399 | shell.outputcache.color_table.active_scheme_name |
|
2399 | shell.outputcache.color_table.active_scheme_name | |
2400 | # Set exception colors |
|
2400 | # Set exception colors | |
2401 | try: |
|
2401 | try: | |
2402 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2402 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
2403 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2403 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
2404 | except: |
|
2404 | except: | |
2405 | color_switch_err('exception') |
|
2405 | color_switch_err('exception') | |
2406 |
|
2406 | |||
2407 | # threaded shells use a verbose traceback in sys.excepthook |
|
2407 | # threaded shells use a verbose traceback in sys.excepthook | |
2408 | if shell.isthreaded: |
|
2408 | if shell.isthreaded: | |
2409 | try: |
|
2409 | try: | |
2410 | shell.sys_excepthook.set_colors(scheme=new_scheme) |
|
2410 | shell.sys_excepthook.set_colors(scheme=new_scheme) | |
2411 | except: |
|
2411 | except: | |
2412 | color_switch_err('system exception handler') |
|
2412 | color_switch_err('system exception handler') | |
2413 |
|
2413 | |||
2414 | # Set info (for 'object?') colors |
|
2414 | # Set info (for 'object?') colors | |
2415 | if shell.rc.color_info: |
|
2415 | if shell.rc.color_info: | |
2416 | try: |
|
2416 | try: | |
2417 | shell.inspector.set_active_scheme(new_scheme) |
|
2417 | shell.inspector.set_active_scheme(new_scheme) | |
2418 | except: |
|
2418 | except: | |
2419 | color_switch_err('object inspector') |
|
2419 | color_switch_err('object inspector') | |
2420 | else: |
|
2420 | else: | |
2421 | shell.inspector.set_active_scheme('NoColor') |
|
2421 | shell.inspector.set_active_scheme('NoColor') | |
2422 |
|
2422 | |||
2423 | def magic_color_info(self,parameter_s = ''): |
|
2423 | def magic_color_info(self,parameter_s = ''): | |
2424 | """Toggle color_info. |
|
2424 | """Toggle color_info. | |
2425 |
|
2425 | |||
2426 | The color_info configuration parameter controls whether colors are |
|
2426 | The color_info configuration parameter controls whether colors are | |
2427 | used for displaying object details (by things like %psource, %pfile or |
|
2427 | used for displaying object details (by things like %psource, %pfile or | |
2428 | the '?' system). This function toggles this value with each call. |
|
2428 | the '?' system). This function toggles this value with each call. | |
2429 |
|
2429 | |||
2430 | Note that unless you have a fairly recent pager (less works better |
|
2430 | Note that unless you have a fairly recent pager (less works better | |
2431 | than more) in your system, using colored object information displays |
|
2431 | than more) in your system, using colored object information displays | |
2432 | will not work properly. Test it and see.""" |
|
2432 | will not work properly. Test it and see.""" | |
2433 |
|
2433 | |||
2434 | self.shell.rc.color_info = 1 - self.shell.rc.color_info |
|
2434 | self.shell.rc.color_info = 1 - self.shell.rc.color_info | |
2435 | self.magic_colors(self.shell.rc.colors) |
|
2435 | self.magic_colors(self.shell.rc.colors) | |
2436 | print 'Object introspection functions have now coloring:', |
|
2436 | print 'Object introspection functions have now coloring:', | |
2437 | print ['OFF','ON'][self.shell.rc.color_info] |
|
2437 | print ['OFF','ON'][self.shell.rc.color_info] | |
2438 |
|
2438 | |||
2439 | def magic_Pprint(self, parameter_s=''): |
|
2439 | def magic_Pprint(self, parameter_s=''): | |
2440 | """Toggle pretty printing on/off.""" |
|
2440 | """Toggle pretty printing on/off.""" | |
2441 |
|
2441 | |||
2442 | self.shell.rc.pprint = 1 - self.shell.rc.pprint |
|
2442 | self.shell.rc.pprint = 1 - self.shell.rc.pprint | |
2443 | print 'Pretty printing has been turned', \ |
|
2443 | print 'Pretty printing has been turned', \ | |
2444 | ['OFF','ON'][self.shell.rc.pprint] |
|
2444 | ['OFF','ON'][self.shell.rc.pprint] | |
2445 |
|
2445 | |||
2446 | def magic_exit(self, parameter_s=''): |
|
2446 | def magic_exit(self, parameter_s=''): | |
2447 | """Exit IPython, confirming if configured to do so. |
|
2447 | """Exit IPython, confirming if configured to do so. | |
2448 |
|
2448 | |||
2449 | You can configure whether IPython asks for confirmation upon exit by |
|
2449 | You can configure whether IPython asks for confirmation upon exit by | |
2450 | setting the confirm_exit flag in the ipythonrc file.""" |
|
2450 | setting the confirm_exit flag in the ipythonrc file.""" | |
2451 |
|
2451 | |||
2452 | self.shell.exit() |
|
2452 | self.shell.exit() | |
2453 |
|
2453 | |||
2454 | def magic_quit(self, parameter_s=''): |
|
2454 | def magic_quit(self, parameter_s=''): | |
2455 | """Exit IPython, confirming if configured to do so (like %exit)""" |
|
2455 | """Exit IPython, confirming if configured to do so (like %exit)""" | |
2456 |
|
2456 | |||
2457 | self.shell.exit() |
|
2457 | self.shell.exit() | |
2458 |
|
2458 | |||
2459 | def magic_Exit(self, parameter_s=''): |
|
2459 | def magic_Exit(self, parameter_s=''): | |
2460 | """Exit IPython without confirmation.""" |
|
2460 | """Exit IPython without confirmation.""" | |
2461 |
|
2461 | |||
2462 | self.shell.exit_now = True |
|
2462 | self.shell.exit_now = True | |
2463 |
|
2463 | |||
2464 | #...................................................................... |
|
2464 | #...................................................................... | |
2465 | # Functions to implement unix shell-type things |
|
2465 | # Functions to implement unix shell-type things | |
2466 |
|
2466 | |||
2467 | def magic_alias(self, parameter_s = ''): |
|
2467 | def magic_alias(self, parameter_s = ''): | |
2468 | """Define an alias for a system command. |
|
2468 | """Define an alias for a system command. | |
2469 |
|
2469 | |||
2470 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2470 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
2471 |
|
2471 | |||
2472 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2472 | Then, typing 'alias_name params' will execute the system command 'cmd | |
2473 | params' (from your underlying operating system). |
|
2473 | params' (from your underlying operating system). | |
2474 |
|
2474 | |||
2475 | Aliases have lower precedence than magic functions and Python normal |
|
2475 | Aliases have lower precedence than magic functions and Python normal | |
2476 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2476 | variables, so if 'foo' is both a Python variable and an alias, the | |
2477 | alias can not be executed until 'del foo' removes the Python variable. |
|
2477 | alias can not be executed until 'del foo' removes the Python variable. | |
2478 |
|
2478 | |||
2479 | You can use the %l specifier in an alias definition to represent the |
|
2479 | You can use the %l specifier in an alias definition to represent the | |
2480 | whole line when the alias is called. For example: |
|
2480 | whole line when the alias is called. For example: | |
2481 |
|
2481 | |||
2482 | In [2]: alias all echo "Input in brackets: <%l>"\\ |
|
2482 | In [2]: alias all echo "Input in brackets: <%l>"\\ | |
2483 | In [3]: all hello world\\ |
|
2483 | In [3]: all hello world\\ | |
2484 | Input in brackets: <hello world> |
|
2484 | Input in brackets: <hello world> | |
2485 |
|
2485 | |||
2486 | You can also define aliases with parameters using %s specifiers (one |
|
2486 | You can also define aliases with parameters using %s specifiers (one | |
2487 | per parameter): |
|
2487 | per parameter): | |
2488 |
|
2488 | |||
2489 | In [1]: alias parts echo first %s second %s\\ |
|
2489 | In [1]: alias parts echo first %s second %s\\ | |
2490 | In [2]: %parts A B\\ |
|
2490 | In [2]: %parts A B\\ | |
2491 | first A second B\\ |
|
2491 | first A second B\\ | |
2492 | In [3]: %parts A\\ |
|
2492 | In [3]: %parts A\\ | |
2493 | Incorrect number of arguments: 2 expected.\\ |
|
2493 | Incorrect number of arguments: 2 expected.\\ | |
2494 | parts is an alias to: 'echo first %s second %s' |
|
2494 | parts is an alias to: 'echo first %s second %s' | |
2495 |
|
2495 | |||
2496 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2496 | Note that %l and %s are mutually exclusive. You can only use one or | |
2497 | the other in your aliases. |
|
2497 | the other in your aliases. | |
2498 |
|
2498 | |||
2499 | Aliases expand Python variables just like system calls using ! or !! |
|
2499 | Aliases expand Python variables just like system calls using ! or !! | |
2500 | do: all expressions prefixed with '$' get expanded. For details of |
|
2500 | do: all expressions prefixed with '$' get expanded. For details of | |
2501 | the semantic rules, see PEP-215: |
|
2501 | the semantic rules, see PEP-215: | |
2502 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2502 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
2503 | IPython for variable expansion. If you want to access a true shell |
|
2503 | IPython for variable expansion. If you want to access a true shell | |
2504 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2504 | variable, an extra $ is necessary to prevent its expansion by IPython: | |
2505 |
|
2505 | |||
2506 | In [6]: alias show echo\\ |
|
2506 | In [6]: alias show echo\\ | |
2507 | In [7]: PATH='A Python string'\\ |
|
2507 | In [7]: PATH='A Python string'\\ | |
2508 | In [8]: show $PATH\\ |
|
2508 | In [8]: show $PATH\\ | |
2509 | A Python string\\ |
|
2509 | A Python string\\ | |
2510 | In [9]: show $$PATH\\ |
|
2510 | In [9]: show $$PATH\\ | |
2511 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2511 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
2512 |
|
2512 | |||
2513 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2513 | You can use the alias facility to acess all of $PATH. See the %rehash | |
2514 | and %rehashx functions, which automatically create aliases for the |
|
2514 | and %rehashx functions, which automatically create aliases for the | |
2515 | contents of your $PATH. |
|
2515 | contents of your $PATH. | |
2516 |
|
2516 | |||
2517 | If called with no parameters, %alias prints the current alias table.""" |
|
2517 | If called with no parameters, %alias prints the current alias table.""" | |
2518 |
|
2518 | |||
2519 | par = parameter_s.strip() |
|
2519 | par = parameter_s.strip() | |
2520 | if not par: |
|
2520 | if not par: | |
2521 | stored = self.db.get('stored_aliases', {} ) |
|
2521 | stored = self.db.get('stored_aliases', {} ) | |
2522 | atab = self.shell.alias_table |
|
2522 | atab = self.shell.alias_table | |
2523 | aliases = atab.keys() |
|
2523 | aliases = atab.keys() | |
2524 | aliases.sort() |
|
2524 | aliases.sort() | |
2525 | res = [] |
|
2525 | res = [] | |
2526 | showlast = [] |
|
2526 | showlast = [] | |
2527 | for alias in aliases: |
|
2527 | for alias in aliases: | |
2528 | special = False |
|
2528 | special = False | |
2529 | try: |
|
2529 | try: | |
2530 | tgt = atab[alias][1] |
|
2530 | tgt = atab[alias][1] | |
2531 | except (TypeError, AttributeError): |
|
2531 | except (TypeError, AttributeError): | |
2532 | # unsubscriptable? probably a callable |
|
2532 | # unsubscriptable? probably a callable | |
2533 | tgt = atab[alias] |
|
2533 | tgt = atab[alias] | |
2534 | special = True |
|
2534 | special = True | |
2535 | # 'interesting' aliases |
|
2535 | # 'interesting' aliases | |
2536 | if (alias in stored or |
|
2536 | if (alias in stored or | |
2537 | special or |
|
2537 | special or | |
2538 | alias.lower() != os.path.splitext(tgt)[0].lower() or |
|
2538 | alias.lower() != os.path.splitext(tgt)[0].lower() or | |
2539 | ' ' in tgt): |
|
2539 | ' ' in tgt): | |
2540 | showlast.append((alias, tgt)) |
|
2540 | showlast.append((alias, tgt)) | |
2541 | else: |
|
2541 | else: | |
2542 | res.append((alias, tgt )) |
|
2542 | res.append((alias, tgt )) | |
2543 |
|
2543 | |||
2544 | # show most interesting aliases last |
|
2544 | # show most interesting aliases last | |
2545 | res.extend(showlast) |
|
2545 | res.extend(showlast) | |
2546 | print "Total number of aliases:",len(aliases) |
|
2546 | print "Total number of aliases:",len(aliases) | |
2547 | return res |
|
2547 | return res | |
2548 | try: |
|
2548 | try: | |
2549 | alias,cmd = par.split(None,1) |
|
2549 | alias,cmd = par.split(None,1) | |
2550 | except: |
|
2550 | except: | |
2551 | print OInspect.getdoc(self.magic_alias) |
|
2551 | print OInspect.getdoc(self.magic_alias) | |
2552 | else: |
|
2552 | else: | |
2553 | nargs = cmd.count('%s') |
|
2553 | nargs = cmd.count('%s') | |
2554 | if nargs>0 and cmd.find('%l')>=0: |
|
2554 | if nargs>0 and cmd.find('%l')>=0: | |
2555 | error('The %s and %l specifiers are mutually exclusive ' |
|
2555 | error('The %s and %l specifiers are mutually exclusive ' | |
2556 | 'in alias definitions.') |
|
2556 | 'in alias definitions.') | |
2557 | else: # all looks OK |
|
2557 | else: # all looks OK | |
2558 | self.shell.alias_table[alias] = (nargs,cmd) |
|
2558 | self.shell.alias_table[alias] = (nargs,cmd) | |
2559 | self.shell.alias_table_validate(verbose=0) |
|
2559 | self.shell.alias_table_validate(verbose=0) | |
2560 | # end magic_alias |
|
2560 | # end magic_alias | |
2561 |
|
2561 | |||
2562 | def magic_unalias(self, parameter_s = ''): |
|
2562 | def magic_unalias(self, parameter_s = ''): | |
2563 | """Remove an alias""" |
|
2563 | """Remove an alias""" | |
2564 |
|
2564 | |||
2565 | aname = parameter_s.strip() |
|
2565 | aname = parameter_s.strip() | |
2566 | if aname in self.shell.alias_table: |
|
2566 | if aname in self.shell.alias_table: | |
2567 | del self.shell.alias_table[aname] |
|
2567 | del self.shell.alias_table[aname] | |
2568 | stored = self.db.get('stored_aliases', {} ) |
|
2568 | stored = self.db.get('stored_aliases', {} ) | |
2569 | if aname in stored: |
|
2569 | if aname in stored: | |
2570 | print "Removing %stored alias",aname |
|
2570 | print "Removing %stored alias",aname | |
2571 | del stored[aname] |
|
2571 | del stored[aname] | |
2572 | self.db['stored_aliases'] = stored |
|
2572 | self.db['stored_aliases'] = stored | |
2573 |
|
2573 | |||
2574 |
|
2574 | |||
2575 | def magic_rehashx(self, parameter_s = ''): |
|
2575 | def magic_rehashx(self, parameter_s = ''): | |
2576 | """Update the alias table with all executable files in $PATH. |
|
2576 | """Update the alias table with all executable files in $PATH. | |
2577 |
|
2577 | |||
2578 | This version explicitly checks that every entry in $PATH is a file |
|
2578 | This version explicitly checks that every entry in $PATH is a file | |
2579 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2579 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2580 |
|
2580 | |||
2581 | Under Windows, it checks executability as a match agains a |
|
2581 | Under Windows, it checks executability as a match agains a | |
2582 | '|'-separated string of extensions, stored in the IPython config |
|
2582 | '|'-separated string of extensions, stored in the IPython config | |
2583 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2583 | variable win_exec_ext. This defaults to 'exe|com|bat'. | |
2584 |
|
2584 | |||
2585 | This function also resets the root module cache of module completer, |
|
2585 | This function also resets the root module cache of module completer, | |
2586 | used on slow filesystems. |
|
2586 | used on slow filesystems. | |
2587 | """ |
|
2587 | """ | |
2588 |
|
2588 | |||
2589 |
|
2589 | |||
2590 | ip = self.api |
|
2590 | ip = self.api | |
2591 |
|
2591 | |||
2592 | # for the benefit of module completer in ipy_completers.py |
|
2592 | # for the benefit of module completer in ipy_completers.py | |
2593 | del ip.db['rootmodules'] |
|
2593 | del ip.db['rootmodules'] | |
2594 |
|
2594 | |||
2595 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2595 | path = [os.path.abspath(os.path.expanduser(p)) for p in | |
2596 | os.environ.get('PATH','').split(os.pathsep)] |
|
2596 | os.environ.get('PATH','').split(os.pathsep)] | |
2597 | path = filter(os.path.isdir,path) |
|
2597 | path = filter(os.path.isdir,path) | |
2598 |
|
2598 | |||
2599 | alias_table = self.shell.alias_table |
|
2599 | alias_table = self.shell.alias_table | |
2600 | syscmdlist = [] |
|
2600 | syscmdlist = [] | |
2601 | if os.name == 'posix': |
|
2601 | if os.name == 'posix': | |
2602 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2602 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2603 | os.access(fname,os.X_OK) |
|
2603 | os.access(fname,os.X_OK) | |
2604 | else: |
|
2604 | else: | |
2605 |
|
2605 | |||
2606 | try: |
|
2606 | try: | |
2607 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2607 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2608 | except KeyError: |
|
2608 | except KeyError: | |
2609 | winext = 'exe|com|bat|py' |
|
2609 | winext = 'exe|com|bat|py' | |
2610 | if 'py' not in winext: |
|
2610 | if 'py' not in winext: | |
2611 | winext += '|py' |
|
2611 | winext += '|py' | |
2612 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2612 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2613 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2613 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2614 | savedir = os.getcwd() |
|
2614 | savedir = os.getcwd() | |
2615 | try: |
|
2615 | try: | |
2616 | # write the whole loop for posix/Windows so we don't have an if in |
|
2616 | # write the whole loop for posix/Windows so we don't have an if in | |
2617 | # the innermost part |
|
2617 | # the innermost part | |
2618 | if os.name == 'posix': |
|
2618 | if os.name == 'posix': | |
2619 | for pdir in path: |
|
2619 | for pdir in path: | |
2620 | os.chdir(pdir) |
|
2620 | os.chdir(pdir) | |
2621 | for ff in os.listdir(pdir): |
|
2621 | for ff in os.listdir(pdir): | |
2622 | if isexec(ff) and ff not in self.shell.no_alias: |
|
2622 | if isexec(ff) and ff not in self.shell.no_alias: | |
2623 | # each entry in the alias table must be (N,name), |
|
2623 | # each entry in the alias table must be (N,name), | |
2624 | # where N is the number of positional arguments of the |
|
2624 | # where N is the number of positional arguments of the | |
2625 | # alias. |
|
2625 | # alias. | |
2626 | alias_table[ff] = (0,ff) |
|
2626 | alias_table[ff] = (0,ff) | |
2627 | syscmdlist.append(ff) |
|
2627 | syscmdlist.append(ff) | |
2628 | else: |
|
2628 | else: | |
2629 | for pdir in path: |
|
2629 | for pdir in path: | |
2630 | os.chdir(pdir) |
|
2630 | os.chdir(pdir) | |
2631 | for ff in os.listdir(pdir): |
|
2631 | for ff in os.listdir(pdir): | |
2632 | base, ext = os.path.splitext(ff) |
|
2632 | base, ext = os.path.splitext(ff) | |
2633 | if isexec(ff) and base.lower() not in self.shell.no_alias: |
|
2633 | if isexec(ff) and base.lower() not in self.shell.no_alias: | |
2634 | if ext.lower() == '.exe': |
|
2634 | if ext.lower() == '.exe': | |
2635 | ff = base |
|
2635 | ff = base | |
2636 | alias_table[base.lower()] = (0,ff) |
|
2636 | alias_table[base.lower()] = (0,ff) | |
2637 | syscmdlist.append(ff) |
|
2637 | syscmdlist.append(ff) | |
2638 | # Make sure the alias table doesn't contain keywords or builtins |
|
2638 | # Make sure the alias table doesn't contain keywords or builtins | |
2639 | self.shell.alias_table_validate() |
|
2639 | self.shell.alias_table_validate() | |
2640 | # Call again init_auto_alias() so we get 'rm -i' and other |
|
2640 | # Call again init_auto_alias() so we get 'rm -i' and other | |
2641 | # modified aliases since %rehashx will probably clobber them |
|
2641 | # modified aliases since %rehashx will probably clobber them | |
2642 |
|
2642 | |||
2643 | # no, we don't want them. if %rehashx clobbers them, good, |
|
2643 | # no, we don't want them. if %rehashx clobbers them, good, | |
2644 | # we'll probably get better versions |
|
2644 | # we'll probably get better versions | |
2645 | # self.shell.init_auto_alias() |
|
2645 | # self.shell.init_auto_alias() | |
2646 | db = ip.db |
|
2646 | db = ip.db | |
2647 | db['syscmdlist'] = syscmdlist |
|
2647 | db['syscmdlist'] = syscmdlist | |
2648 | finally: |
|
2648 | finally: | |
2649 | os.chdir(savedir) |
|
2649 | os.chdir(savedir) | |
2650 |
|
2650 | |||
2651 | def magic_pwd(self, parameter_s = ''): |
|
2651 | def magic_pwd(self, parameter_s = ''): | |
2652 | """Return the current working directory path.""" |
|
2652 | """Return the current working directory path.""" | |
2653 | return os.getcwd() |
|
2653 | return os.getcwd() | |
2654 |
|
2654 | |||
2655 | def magic_cd(self, parameter_s=''): |
|
2655 | def magic_cd(self, parameter_s=''): | |
2656 | """Change the current working directory. |
|
2656 | """Change the current working directory. | |
2657 |
|
2657 | |||
2658 | This command automatically maintains an internal list of directories |
|
2658 | This command automatically maintains an internal list of directories | |
2659 | you visit during your IPython session, in the variable _dh. The |
|
2659 | you visit during your IPython session, in the variable _dh. The | |
2660 | command %dhist shows this history nicely formatted. You can also |
|
2660 | command %dhist shows this history nicely formatted. You can also | |
2661 | do 'cd -<tab>' to see directory history conveniently. |
|
2661 | do 'cd -<tab>' to see directory history conveniently. | |
2662 |
|
2662 | |||
2663 | Usage: |
|
2663 | Usage: | |
2664 |
|
2664 | |||
2665 | cd 'dir': changes to directory 'dir'. |
|
2665 | cd 'dir': changes to directory 'dir'. | |
2666 |
|
2666 | |||
2667 | cd -: changes to the last visited directory. |
|
2667 | cd -: changes to the last visited directory. | |
2668 |
|
2668 | |||
2669 | cd -<n>: changes to the n-th directory in the directory history. |
|
2669 | cd -<n>: changes to the n-th directory in the directory history. | |
2670 |
|
2670 | |||
2671 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2671 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
2672 | (note: cd <bookmark_name> is enough if there is no |
|
2672 | (note: cd <bookmark_name> is enough if there is no | |
2673 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2673 | directory <bookmark_name>, but a bookmark with the name exists.) | |
2674 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2674 | 'cd -b <tab>' allows you to tab-complete bookmark names. | |
2675 |
|
2675 | |||
2676 | Options: |
|
2676 | Options: | |
2677 |
|
2677 | |||
2678 | -q: quiet. Do not print the working directory after the cd command is |
|
2678 | -q: quiet. Do not print the working directory after the cd command is | |
2679 | executed. By default IPython's cd command does print this directory, |
|
2679 | executed. By default IPython's cd command does print this directory, | |
2680 | since the default prompts do not display path information. |
|
2680 | since the default prompts do not display path information. | |
2681 |
|
2681 | |||
2682 | Note that !cd doesn't work for this purpose because the shell where |
|
2682 | Note that !cd doesn't work for this purpose because the shell where | |
2683 | !command runs is immediately discarded after executing 'command'.""" |
|
2683 | !command runs is immediately discarded after executing 'command'.""" | |
2684 |
|
2684 | |||
2685 | parameter_s = parameter_s.strip() |
|
2685 | parameter_s = parameter_s.strip() | |
2686 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2686 | #bkms = self.shell.persist.get("bookmarks",{}) | |
2687 |
|
2687 | |||
2688 | oldcwd = os.getcwd() |
|
2688 | oldcwd = os.getcwd() | |
2689 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2689 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
2690 | # jump in directory history by number |
|
2690 | # jump in directory history by number | |
2691 | if numcd: |
|
2691 | if numcd: | |
2692 | nn = int(numcd.group(2)) |
|
2692 | nn = int(numcd.group(2)) | |
2693 | try: |
|
2693 | try: | |
2694 | ps = self.shell.user_ns['_dh'][nn] |
|
2694 | ps = self.shell.user_ns['_dh'][nn] | |
2695 | except IndexError: |
|
2695 | except IndexError: | |
2696 | print 'The requested directory does not exist in history.' |
|
2696 | print 'The requested directory does not exist in history.' | |
2697 | return |
|
2697 | return | |
2698 | else: |
|
2698 | else: | |
2699 | opts = {} |
|
2699 | opts = {} | |
2700 | else: |
|
2700 | else: | |
2701 | #turn all non-space-escaping backslashes to slashes, |
|
2701 | #turn all non-space-escaping backslashes to slashes, | |
2702 | # for c:\windows\directory\names\ |
|
2702 | # for c:\windows\directory\names\ | |
2703 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2703 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) | |
2704 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2704 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
2705 | # jump to previous |
|
2705 | # jump to previous | |
2706 | if ps == '-': |
|
2706 | if ps == '-': | |
2707 | try: |
|
2707 | try: | |
2708 | ps = self.shell.user_ns['_dh'][-2] |
|
2708 | ps = self.shell.user_ns['_dh'][-2] | |
2709 | except IndexError: |
|
2709 | except IndexError: | |
2710 | raise UsageError('%cd -: No previous directory to change to.') |
|
2710 | raise UsageError('%cd -: No previous directory to change to.') | |
2711 | # jump to bookmark if needed |
|
2711 | # jump to bookmark if needed | |
2712 | else: |
|
2712 | else: | |
2713 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2713 | if not os.path.isdir(ps) or opts.has_key('b'): | |
2714 | bkms = self.db.get('bookmarks', {}) |
|
2714 | bkms = self.db.get('bookmarks', {}) | |
2715 |
|
2715 | |||
2716 | if bkms.has_key(ps): |
|
2716 | if bkms.has_key(ps): | |
2717 | target = bkms[ps] |
|
2717 | target = bkms[ps] | |
2718 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2718 | print '(bookmark:%s) -> %s' % (ps,target) | |
2719 | ps = target |
|
2719 | ps = target | |
2720 | else: |
|
2720 | else: | |
2721 | if opts.has_key('b'): |
|
2721 | if opts.has_key('b'): | |
2722 | raise UsageError("Bookmark '%s' not found. " |
|
2722 | raise UsageError("Bookmark '%s' not found. " | |
2723 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2723 | "Use '%%bookmark -l' to see your bookmarks." % ps) | |
2724 |
|
2724 | |||
2725 | # at this point ps should point to the target dir |
|
2725 | # at this point ps should point to the target dir | |
2726 | if ps: |
|
2726 | if ps: | |
2727 | try: |
|
2727 | try: | |
2728 | os.chdir(os.path.expanduser(ps)) |
|
2728 | os.chdir(os.path.expanduser(ps)) | |
2729 | if self.shell.rc.term_title: |
|
2729 | if self.shell.rc.term_title: | |
2730 | #print 'set term title:',self.shell.rc.term_title # dbg |
|
2730 | #print 'set term title:',self.shell.rc.term_title # dbg | |
2731 | ttitle = 'IPy ' + abbrev_cwd() |
|
2731 | ttitle = 'IPy ' + abbrev_cwd() | |
2732 | platutils.set_term_title(ttitle) |
|
2732 | platutils.set_term_title(ttitle) | |
2733 | except OSError: |
|
2733 | except OSError: | |
2734 | print sys.exc_info()[1] |
|
2734 | print sys.exc_info()[1] | |
2735 | else: |
|
2735 | else: | |
2736 | cwd = os.getcwd() |
|
2736 | cwd = os.getcwd() | |
2737 | dhist = self.shell.user_ns['_dh'] |
|
2737 | dhist = self.shell.user_ns['_dh'] | |
2738 | if oldcwd != cwd: |
|
2738 | if oldcwd != cwd: | |
2739 | dhist.append(cwd) |
|
2739 | dhist.append(cwd) | |
2740 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2740 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2741 |
|
2741 | |||
2742 | else: |
|
2742 | else: | |
2743 | os.chdir(self.shell.home_dir) |
|
2743 | os.chdir(self.shell.home_dir) | |
2744 | if self.shell.rc.term_title: |
|
2744 | if self.shell.rc.term_title: | |
2745 | platutils.set_term_title("IPy ~") |
|
2745 | platutils.set_term_title("IPy ~") | |
2746 | cwd = os.getcwd() |
|
2746 | cwd = os.getcwd() | |
2747 | dhist = self.shell.user_ns['_dh'] |
|
2747 | dhist = self.shell.user_ns['_dh'] | |
2748 |
|
2748 | |||
2749 | if oldcwd != cwd: |
|
2749 | if oldcwd != cwd: | |
2750 | dhist.append(cwd) |
|
2750 | dhist.append(cwd) | |
2751 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2751 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2752 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2752 | if not 'q' in opts and self.shell.user_ns['_dh']: | |
2753 | print self.shell.user_ns['_dh'][-1] |
|
2753 | print self.shell.user_ns['_dh'][-1] | |
2754 |
|
2754 | |||
2755 |
|
2755 | |||
2756 | def magic_env(self, parameter_s=''): |
|
2756 | def magic_env(self, parameter_s=''): | |
2757 | """List environment variables.""" |
|
2757 | """List environment variables.""" | |
2758 |
|
2758 | |||
2759 | return os.environ.data |
|
2759 | return os.environ.data | |
2760 |
|
2760 | |||
2761 | def magic_pushd(self, parameter_s=''): |
|
2761 | def magic_pushd(self, parameter_s=''): | |
2762 | """Place the current dir on stack and change directory. |
|
2762 | """Place the current dir on stack and change directory. | |
2763 |
|
2763 | |||
2764 | Usage:\\ |
|
2764 | Usage:\\ | |
2765 | %pushd ['dirname'] |
|
2765 | %pushd ['dirname'] | |
2766 | """ |
|
2766 | """ | |
2767 |
|
2767 | |||
2768 | dir_s = self.shell.dir_stack |
|
2768 | dir_s = self.shell.dir_stack | |
2769 | tgt = os.path.expanduser(parameter_s) |
|
2769 | tgt = os.path.expanduser(parameter_s) | |
2770 | cwd = os.getcwd().replace(self.home_dir,'~') |
|
2770 | cwd = os.getcwd().replace(self.home_dir,'~') | |
2771 | if tgt: |
|
2771 | if tgt: | |
2772 | self.magic_cd(parameter_s) |
|
2772 | self.magic_cd(parameter_s) | |
2773 | dir_s.insert(0,cwd) |
|
2773 | dir_s.insert(0,cwd) | |
2774 | return self.magic_dirs() |
|
2774 | return self.magic_dirs() | |
2775 |
|
2775 | |||
2776 | def magic_popd(self, parameter_s=''): |
|
2776 | def magic_popd(self, parameter_s=''): | |
2777 | """Change to directory popped off the top of the stack. |
|
2777 | """Change to directory popped off the top of the stack. | |
2778 | """ |
|
2778 | """ | |
2779 | if not self.shell.dir_stack: |
|
2779 | if not self.shell.dir_stack: | |
2780 | raise UsageError("%popd on empty stack") |
|
2780 | raise UsageError("%popd on empty stack") | |
2781 | top = self.shell.dir_stack.pop(0) |
|
2781 | top = self.shell.dir_stack.pop(0) | |
2782 | self.magic_cd(top) |
|
2782 | self.magic_cd(top) | |
2783 | print "popd ->",top |
|
2783 | print "popd ->",top | |
2784 |
|
2784 | |||
2785 | def magic_dirs(self, parameter_s=''): |
|
2785 | def magic_dirs(self, parameter_s=''): | |
2786 | """Return the current directory stack.""" |
|
2786 | """Return the current directory stack.""" | |
2787 |
|
2787 | |||
2788 | return self.shell.dir_stack |
|
2788 | return self.shell.dir_stack | |
2789 |
|
2789 | |||
2790 | def magic_dhist(self, parameter_s=''): |
|
2790 | def magic_dhist(self, parameter_s=''): | |
2791 | """Print your history of visited directories. |
|
2791 | """Print your history of visited directories. | |
2792 |
|
2792 | |||
2793 | %dhist -> print full history\\ |
|
2793 | %dhist -> print full history\\ | |
2794 | %dhist n -> print last n entries only\\ |
|
2794 | %dhist n -> print last n entries only\\ | |
2795 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2795 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
2796 |
|
2796 | |||
2797 | This history is automatically maintained by the %cd command, and |
|
2797 | This history is automatically maintained by the %cd command, and | |
2798 | always available as the global list variable _dh. You can use %cd -<n> |
|
2798 | always available as the global list variable _dh. You can use %cd -<n> | |
2799 | to go to directory number <n>. |
|
2799 | to go to directory number <n>. | |
2800 |
|
2800 | |||
2801 | Note that most of time, you should view directory history by entering |
|
2801 | Note that most of time, you should view directory history by entering | |
2802 | cd -<TAB>. |
|
2802 | cd -<TAB>. | |
2803 |
|
2803 | |||
2804 | """ |
|
2804 | """ | |
2805 |
|
2805 | |||
2806 | dh = self.shell.user_ns['_dh'] |
|
2806 | dh = self.shell.user_ns['_dh'] | |
2807 | if parameter_s: |
|
2807 | if parameter_s: | |
2808 | try: |
|
2808 | try: | |
2809 | args = map(int,parameter_s.split()) |
|
2809 | args = map(int,parameter_s.split()) | |
2810 | except: |
|
2810 | except: | |
2811 | self.arg_err(Magic.magic_dhist) |
|
2811 | self.arg_err(Magic.magic_dhist) | |
2812 | return |
|
2812 | return | |
2813 | if len(args) == 1: |
|
2813 | if len(args) == 1: | |
2814 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2814 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
2815 | elif len(args) == 2: |
|
2815 | elif len(args) == 2: | |
2816 | ini,fin = args |
|
2816 | ini,fin = args | |
2817 | else: |
|
2817 | else: | |
2818 | self.arg_err(Magic.magic_dhist) |
|
2818 | self.arg_err(Magic.magic_dhist) | |
2819 | return |
|
2819 | return | |
2820 | else: |
|
2820 | else: | |
2821 | ini,fin = 0,len(dh) |
|
2821 | ini,fin = 0,len(dh) | |
2822 | nlprint(dh, |
|
2822 | nlprint(dh, | |
2823 | header = 'Directory history (kept in _dh)', |
|
2823 | header = 'Directory history (kept in _dh)', | |
2824 | start=ini,stop=fin) |
|
2824 | start=ini,stop=fin) | |
2825 |
|
2825 | |||
2826 |
|
2826 | |||
2827 | def magic_sc(self, parameter_s=''): |
|
2827 | def magic_sc(self, parameter_s=''): | |
2828 | """Shell capture - execute a shell command and capture its output. |
|
2828 | """Shell capture - execute a shell command and capture its output. | |
2829 |
|
2829 | |||
2830 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2830 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
2831 |
|
2831 | |||
2832 | You should use the form 'var = !command' instead. Example: |
|
2832 | You should use the form 'var = !command' instead. Example: | |
2833 |
|
2833 | |||
2834 | "%sc -l myfiles = ls ~" should now be written as |
|
2834 | "%sc -l myfiles = ls ~" should now be written as | |
2835 |
|
2835 | |||
2836 | "myfiles = !ls ~" |
|
2836 | "myfiles = !ls ~" | |
2837 |
|
2837 | |||
2838 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2838 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
2839 | below. |
|
2839 | below. | |
2840 |
|
2840 | |||
2841 | -- |
|
2841 | -- | |
2842 | %sc [options] varname=command |
|
2842 | %sc [options] varname=command | |
2843 |
|
2843 | |||
2844 | IPython will run the given command using commands.getoutput(), and |
|
2844 | IPython will run the given command using commands.getoutput(), and | |
2845 | will then update the user's interactive namespace with a variable |
|
2845 | will then update the user's interactive namespace with a variable | |
2846 | called varname, containing the value of the call. Your command can |
|
2846 | called varname, containing the value of the call. Your command can | |
2847 | contain shell wildcards, pipes, etc. |
|
2847 | contain shell wildcards, pipes, etc. | |
2848 |
|
2848 | |||
2849 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2849 | The '=' sign in the syntax is mandatory, and the variable name you | |
2850 | supply must follow Python's standard conventions for valid names. |
|
2850 | supply must follow Python's standard conventions for valid names. | |
2851 |
|
2851 | |||
2852 | (A special format without variable name exists for internal use) |
|
2852 | (A special format without variable name exists for internal use) | |
2853 |
|
2853 | |||
2854 | Options: |
|
2854 | Options: | |
2855 |
|
2855 | |||
2856 | -l: list output. Split the output on newlines into a list before |
|
2856 | -l: list output. Split the output on newlines into a list before | |
2857 | assigning it to the given variable. By default the output is stored |
|
2857 | assigning it to the given variable. By default the output is stored | |
2858 | as a single string. |
|
2858 | as a single string. | |
2859 |
|
2859 | |||
2860 | -v: verbose. Print the contents of the variable. |
|
2860 | -v: verbose. Print the contents of the variable. | |
2861 |
|
2861 | |||
2862 | In most cases you should not need to split as a list, because the |
|
2862 | In most cases you should not need to split as a list, because the | |
2863 | returned value is a special type of string which can automatically |
|
2863 | returned value is a special type of string which can automatically | |
2864 | provide its contents either as a list (split on newlines) or as a |
|
2864 | provide its contents either as a list (split on newlines) or as a | |
2865 | space-separated string. These are convenient, respectively, either |
|
2865 | space-separated string. These are convenient, respectively, either | |
2866 | for sequential processing or to be passed to a shell command. |
|
2866 | for sequential processing or to be passed to a shell command. | |
2867 |
|
2867 | |||
2868 | For example: |
|
2868 | For example: | |
2869 |
|
2869 | |||
2870 | # Capture into variable a |
|
2870 | # Capture into variable a | |
2871 | In [9]: sc a=ls *py |
|
2871 | In [9]: sc a=ls *py | |
2872 |
|
2872 | |||
2873 | # a is a string with embedded newlines |
|
2873 | # a is a string with embedded newlines | |
2874 | In [10]: a |
|
2874 | In [10]: a | |
2875 | Out[10]: 'setup.py\nwin32_manual_post_install.py' |
|
2875 | Out[10]: 'setup.py\nwin32_manual_post_install.py' | |
2876 |
|
2876 | |||
2877 | # which can be seen as a list: |
|
2877 | # which can be seen as a list: | |
2878 | In [11]: a.l |
|
2878 | In [11]: a.l | |
2879 | Out[11]: ['setup.py', 'win32_manual_post_install.py'] |
|
2879 | Out[11]: ['setup.py', 'win32_manual_post_install.py'] | |
2880 |
|
2880 | |||
2881 | # or as a whitespace-separated string: |
|
2881 | # or as a whitespace-separated string: | |
2882 | In [12]: a.s |
|
2882 | In [12]: a.s | |
2883 | Out[12]: 'setup.py win32_manual_post_install.py' |
|
2883 | Out[12]: 'setup.py win32_manual_post_install.py' | |
2884 |
|
2884 | |||
2885 | # a.s is useful to pass as a single command line: |
|
2885 | # a.s is useful to pass as a single command line: | |
2886 | In [13]: !wc -l $a.s |
|
2886 | In [13]: !wc -l $a.s | |
2887 | 146 setup.py |
|
2887 | 146 setup.py | |
2888 | 130 win32_manual_post_install.py |
|
2888 | 130 win32_manual_post_install.py | |
2889 | 276 total |
|
2889 | 276 total | |
2890 |
|
2890 | |||
2891 | # while the list form is useful to loop over: |
|
2891 | # while the list form is useful to loop over: | |
2892 | In [14]: for f in a.l: |
|
2892 | In [14]: for f in a.l: | |
2893 | ....: !wc -l $f |
|
2893 | ....: !wc -l $f | |
2894 | ....: |
|
2894 | ....: | |
2895 | 146 setup.py |
|
2895 | 146 setup.py | |
2896 | 130 win32_manual_post_install.py |
|
2896 | 130 win32_manual_post_install.py | |
2897 |
|
2897 | |||
2898 | Similiarly, the lists returned by the -l option are also special, in |
|
2898 | Similiarly, the lists returned by the -l option are also special, in | |
2899 | the sense that you can equally invoke the .s attribute on them to |
|
2899 | the sense that you can equally invoke the .s attribute on them to | |
2900 | automatically get a whitespace-separated string from their contents: |
|
2900 | automatically get a whitespace-separated string from their contents: | |
2901 |
|
2901 | |||
2902 | In [1]: sc -l b=ls *py |
|
2902 | In [1]: sc -l b=ls *py | |
2903 |
|
2903 | |||
2904 | In [2]: b |
|
2904 | In [2]: b | |
2905 | Out[2]: ['setup.py', 'win32_manual_post_install.py'] |
|
2905 | Out[2]: ['setup.py', 'win32_manual_post_install.py'] | |
2906 |
|
2906 | |||
2907 | In [3]: b.s |
|
2907 | In [3]: b.s | |
2908 | Out[3]: 'setup.py win32_manual_post_install.py' |
|
2908 | Out[3]: 'setup.py win32_manual_post_install.py' | |
2909 |
|
2909 | |||
2910 | In summary, both the lists and strings used for ouptut capture have |
|
2910 | In summary, both the lists and strings used for ouptut capture have | |
2911 | the following special attributes: |
|
2911 | the following special attributes: | |
2912 |
|
2912 | |||
2913 | .l (or .list) : value as list. |
|
2913 | .l (or .list) : value as list. | |
2914 | .n (or .nlstr): value as newline-separated string. |
|
2914 | .n (or .nlstr): value as newline-separated string. | |
2915 | .s (or .spstr): value as space-separated string. |
|
2915 | .s (or .spstr): value as space-separated string. | |
2916 | """ |
|
2916 | """ | |
2917 |
|
2917 | |||
2918 | opts,args = self.parse_options(parameter_s,'lv') |
|
2918 | opts,args = self.parse_options(parameter_s,'lv') | |
2919 | # Try to get a variable name and command to run |
|
2919 | # Try to get a variable name and command to run | |
2920 | try: |
|
2920 | try: | |
2921 | # the variable name must be obtained from the parse_options |
|
2921 | # the variable name must be obtained from the parse_options | |
2922 | # output, which uses shlex.split to strip options out. |
|
2922 | # output, which uses shlex.split to strip options out. | |
2923 | var,_ = args.split('=',1) |
|
2923 | var,_ = args.split('=',1) | |
2924 | var = var.strip() |
|
2924 | var = var.strip() | |
2925 | # But the the command has to be extracted from the original input |
|
2925 | # But the the command has to be extracted from the original input | |
2926 | # parameter_s, not on what parse_options returns, to avoid the |
|
2926 | # parameter_s, not on what parse_options returns, to avoid the | |
2927 | # quote stripping which shlex.split performs on it. |
|
2927 | # quote stripping which shlex.split performs on it. | |
2928 | _,cmd = parameter_s.split('=',1) |
|
2928 | _,cmd = parameter_s.split('=',1) | |
2929 | except ValueError: |
|
2929 | except ValueError: | |
2930 | var,cmd = '','' |
|
2930 | var,cmd = '','' | |
2931 | # If all looks ok, proceed |
|
2931 | # If all looks ok, proceed | |
2932 | out,err = self.shell.getoutputerror(cmd) |
|
2932 | out,err = self.shell.getoutputerror(cmd) | |
2933 | if err: |
|
2933 | if err: | |
2934 | print >> Term.cerr,err |
|
2934 | print >> Term.cerr,err | |
2935 | if opts.has_key('l'): |
|
2935 | if opts.has_key('l'): | |
2936 | out = SList(out.split('\n')) |
|
2936 | out = SList(out.split('\n')) | |
2937 | else: |
|
2937 | else: | |
2938 | out = LSString(out) |
|
2938 | out = LSString(out) | |
2939 | if opts.has_key('v'): |
|
2939 | if opts.has_key('v'): | |
2940 | print '%s ==\n%s' % (var,pformat(out)) |
|
2940 | print '%s ==\n%s' % (var,pformat(out)) | |
2941 | if var: |
|
2941 | if var: | |
2942 | self.shell.user_ns.update({var:out}) |
|
2942 | self.shell.user_ns.update({var:out}) | |
2943 | else: |
|
2943 | else: | |
2944 | return out |
|
2944 | return out | |
2945 |
|
2945 | |||
2946 | def magic_sx(self, parameter_s=''): |
|
2946 | def magic_sx(self, parameter_s=''): | |
2947 | """Shell execute - run a shell command and capture its output. |
|
2947 | """Shell execute - run a shell command and capture its output. | |
2948 |
|
2948 | |||
2949 | %sx command |
|
2949 | %sx command | |
2950 |
|
2950 | |||
2951 | IPython will run the given command using commands.getoutput(), and |
|
2951 | IPython will run the given command using commands.getoutput(), and | |
2952 | return the result formatted as a list (split on '\\n'). Since the |
|
2952 | return the result formatted as a list (split on '\\n'). Since the | |
2953 | output is _returned_, it will be stored in ipython's regular output |
|
2953 | output is _returned_, it will be stored in ipython's regular output | |
2954 | cache Out[N] and in the '_N' automatic variables. |
|
2954 | cache Out[N] and in the '_N' automatic variables. | |
2955 |
|
2955 | |||
2956 | Notes: |
|
2956 | Notes: | |
2957 |
|
2957 | |||
2958 | 1) If an input line begins with '!!', then %sx is automatically |
|
2958 | 1) If an input line begins with '!!', then %sx is automatically | |
2959 | invoked. That is, while: |
|
2959 | invoked. That is, while: | |
2960 | !ls |
|
2960 | !ls | |
2961 | causes ipython to simply issue system('ls'), typing |
|
2961 | causes ipython to simply issue system('ls'), typing | |
2962 | !!ls |
|
2962 | !!ls | |
2963 | is a shorthand equivalent to: |
|
2963 | is a shorthand equivalent to: | |
2964 | %sx ls |
|
2964 | %sx ls | |
2965 |
|
2965 | |||
2966 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
2966 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
2967 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
2967 | like '%sc -l'. The reason for this is to make it as easy as possible | |
2968 | to process line-oriented shell output via further python commands. |
|
2968 | to process line-oriented shell output via further python commands. | |
2969 | %sc is meant to provide much finer control, but requires more |
|
2969 | %sc is meant to provide much finer control, but requires more | |
2970 | typing. |
|
2970 | typing. | |
2971 |
|
2971 | |||
2972 | 3) Just like %sc -l, this is a list with special attributes: |
|
2972 | 3) Just like %sc -l, this is a list with special attributes: | |
2973 |
|
2973 | |||
2974 | .l (or .list) : value as list. |
|
2974 | .l (or .list) : value as list. | |
2975 | .n (or .nlstr): value as newline-separated string. |
|
2975 | .n (or .nlstr): value as newline-separated string. | |
2976 | .s (or .spstr): value as whitespace-separated string. |
|
2976 | .s (or .spstr): value as whitespace-separated string. | |
2977 |
|
2977 | |||
2978 | This is very useful when trying to use such lists as arguments to |
|
2978 | This is very useful when trying to use such lists as arguments to | |
2979 | system commands.""" |
|
2979 | system commands.""" | |
2980 |
|
2980 | |||
2981 | if parameter_s: |
|
2981 | if parameter_s: | |
2982 | out,err = self.shell.getoutputerror(parameter_s) |
|
2982 | out,err = self.shell.getoutputerror(parameter_s) | |
2983 | if err: |
|
2983 | if err: | |
2984 | print >> Term.cerr,err |
|
2984 | print >> Term.cerr,err | |
2985 | return SList(out.split('\n')) |
|
2985 | return SList(out.split('\n')) | |
2986 |
|
2986 | |||
2987 | def magic_bg(self, parameter_s=''): |
|
2987 | def magic_bg(self, parameter_s=''): | |
2988 | """Run a job in the background, in a separate thread. |
|
2988 | """Run a job in the background, in a separate thread. | |
2989 |
|
2989 | |||
2990 | For example, |
|
2990 | For example, | |
2991 |
|
2991 | |||
2992 | %bg myfunc(x,y,z=1) |
|
2992 | %bg myfunc(x,y,z=1) | |
2993 |
|
2993 | |||
2994 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the |
|
2994 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the | |
2995 | execution starts, a message will be printed indicating the job |
|
2995 | execution starts, a message will be printed indicating the job | |
2996 | number. If your job number is 5, you can use |
|
2996 | number. If your job number is 5, you can use | |
2997 |
|
2997 | |||
2998 | myvar = jobs.result(5) or myvar = jobs[5].result |
|
2998 | myvar = jobs.result(5) or myvar = jobs[5].result | |
2999 |
|
2999 | |||
3000 | to assign this result to variable 'myvar'. |
|
3000 | to assign this result to variable 'myvar'. | |
3001 |
|
3001 | |||
3002 | IPython has a job manager, accessible via the 'jobs' object. You can |
|
3002 | IPython has a job manager, accessible via the 'jobs' object. You can | |
3003 | type jobs? to get more information about it, and use jobs.<TAB> to see |
|
3003 | type jobs? to get more information about it, and use jobs.<TAB> to see | |
3004 | its attributes. All attributes not starting with an underscore are |
|
3004 | its attributes. All attributes not starting with an underscore are | |
3005 | meant for public use. |
|
3005 | meant for public use. | |
3006 |
|
3006 | |||
3007 | In particular, look at the jobs.new() method, which is used to create |
|
3007 | In particular, look at the jobs.new() method, which is used to create | |
3008 | new jobs. This magic %bg function is just a convenience wrapper |
|
3008 | new jobs. This magic %bg function is just a convenience wrapper | |
3009 | around jobs.new(), for expression-based jobs. If you want to create a |
|
3009 | around jobs.new(), for expression-based jobs. If you want to create a | |
3010 | new job with an explicit function object and arguments, you must call |
|
3010 | new job with an explicit function object and arguments, you must call | |
3011 | jobs.new() directly. |
|
3011 | jobs.new() directly. | |
3012 |
|
3012 | |||
3013 | The jobs.new docstring also describes in detail several important |
|
3013 | The jobs.new docstring also describes in detail several important | |
3014 | caveats associated with a thread-based model for background job |
|
3014 | caveats associated with a thread-based model for background job | |
3015 | execution. Type jobs.new? for details. |
|
3015 | execution. Type jobs.new? for details. | |
3016 |
|
3016 | |||
3017 | You can check the status of all jobs with jobs.status(). |
|
3017 | You can check the status of all jobs with jobs.status(). | |
3018 |
|
3018 | |||
3019 | The jobs variable is set by IPython into the Python builtin namespace. |
|
3019 | The jobs variable is set by IPython into the Python builtin namespace. | |
3020 | If you ever declare a variable named 'jobs', you will shadow this |
|
3020 | If you ever declare a variable named 'jobs', you will shadow this | |
3021 | name. You can either delete your global jobs variable to regain |
|
3021 | name. You can either delete your global jobs variable to regain | |
3022 | access to the job manager, or make a new name and assign it manually |
|
3022 | access to the job manager, or make a new name and assign it manually | |
3023 | to the manager (stored in IPython's namespace). For example, to |
|
3023 | to the manager (stored in IPython's namespace). For example, to | |
3024 | assign the job manager to the Jobs name, use: |
|
3024 | assign the job manager to the Jobs name, use: | |
3025 |
|
3025 | |||
3026 | Jobs = __builtins__.jobs""" |
|
3026 | Jobs = __builtins__.jobs""" | |
3027 |
|
3027 | |||
3028 | self.shell.jobs.new(parameter_s,self.shell.user_ns) |
|
3028 | self.shell.jobs.new(parameter_s,self.shell.user_ns) | |
3029 |
|
3029 | |||
3030 | def magic_r(self, parameter_s=''): |
|
3030 | def magic_r(self, parameter_s=''): | |
3031 | """Repeat previous input. |
|
3031 | """Repeat previous input. | |
3032 |
|
3032 | |||
3033 | Note: Consider using the more powerfull %rep instead! |
|
3033 | Note: Consider using the more powerfull %rep instead! | |
3034 |
|
3034 | |||
3035 | If given an argument, repeats the previous command which starts with |
|
3035 | If given an argument, repeats the previous command which starts with | |
3036 | the same string, otherwise it just repeats the previous input. |
|
3036 | the same string, otherwise it just repeats the previous input. | |
3037 |
|
3037 | |||
3038 | Shell escaped commands (with ! as first character) are not recognized |
|
3038 | Shell escaped commands (with ! as first character) are not recognized | |
3039 | by this system, only pure python code and magic commands. |
|
3039 | by this system, only pure python code and magic commands. | |
3040 | """ |
|
3040 | """ | |
3041 |
|
3041 | |||
3042 | start = parameter_s.strip() |
|
3042 | start = parameter_s.strip() | |
3043 | esc_magic = self.shell.ESC_MAGIC |
|
3043 | esc_magic = self.shell.ESC_MAGIC | |
3044 | # Identify magic commands even if automagic is on (which means |
|
3044 | # Identify magic commands even if automagic is on (which means | |
3045 | # the in-memory version is different from that typed by the user). |
|
3045 | # the in-memory version is different from that typed by the user). | |
3046 | if self.shell.rc.automagic: |
|
3046 | if self.shell.rc.automagic: | |
3047 | start_magic = esc_magic+start |
|
3047 | start_magic = esc_magic+start | |
3048 | else: |
|
3048 | else: | |
3049 | start_magic = start |
|
3049 | start_magic = start | |
3050 | # Look through the input history in reverse |
|
3050 | # Look through the input history in reverse | |
3051 | for n in range(len(self.shell.input_hist)-2,0,-1): |
|
3051 | for n in range(len(self.shell.input_hist)-2,0,-1): | |
3052 | input = self.shell.input_hist[n] |
|
3052 | input = self.shell.input_hist[n] | |
3053 | # skip plain 'r' lines so we don't recurse to infinity |
|
3053 | # skip plain 'r' lines so we don't recurse to infinity | |
3054 | if input != '_ip.magic("r")\n' and \ |
|
3054 | if input != '_ip.magic("r")\n' and \ | |
3055 | (input.startswith(start) or input.startswith(start_magic)): |
|
3055 | (input.startswith(start) or input.startswith(start_magic)): | |
3056 | #print 'match',`input` # dbg |
|
3056 | #print 'match',`input` # dbg | |
3057 | print 'Executing:',input, |
|
3057 | print 'Executing:',input, | |
3058 | self.shell.runlines(input) |
|
3058 | self.shell.runlines(input) | |
3059 | return |
|
3059 | return | |
3060 | print 'No previous input matching `%s` found.' % start |
|
3060 | print 'No previous input matching `%s` found.' % start | |
3061 |
|
3061 | |||
3062 |
|
3062 | |||
3063 | def magic_bookmark(self, parameter_s=''): |
|
3063 | def magic_bookmark(self, parameter_s=''): | |
3064 | """Manage IPython's bookmark system. |
|
3064 | """Manage IPython's bookmark system. | |
3065 |
|
3065 | |||
3066 | %bookmark <name> - set bookmark to current dir |
|
3066 | %bookmark <name> - set bookmark to current dir | |
3067 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3067 | %bookmark <name> <dir> - set bookmark to <dir> | |
3068 | %bookmark -l - list all bookmarks |
|
3068 | %bookmark -l - list all bookmarks | |
3069 | %bookmark -d <name> - remove bookmark |
|
3069 | %bookmark -d <name> - remove bookmark | |
3070 | %bookmark -r - remove all bookmarks |
|
3070 | %bookmark -r - remove all bookmarks | |
3071 |
|
3071 | |||
3072 | You can later on access a bookmarked folder with: |
|
3072 | You can later on access a bookmarked folder with: | |
3073 | %cd -b <name> |
|
3073 | %cd -b <name> | |
3074 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3074 | or simply '%cd <name>' if there is no directory called <name> AND | |
3075 | there is such a bookmark defined. |
|
3075 | there is such a bookmark defined. | |
3076 |
|
3076 | |||
3077 | Your bookmarks persist through IPython sessions, but they are |
|
3077 | Your bookmarks persist through IPython sessions, but they are | |
3078 | associated with each profile.""" |
|
3078 | associated with each profile.""" | |
3079 |
|
3079 | |||
3080 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3080 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
3081 | if len(args) > 2: |
|
3081 | if len(args) > 2: | |
3082 | raise UsageError("%bookmark: too many arguments") |
|
3082 | raise UsageError("%bookmark: too many arguments") | |
3083 |
|
3083 | |||
3084 | bkms = self.db.get('bookmarks',{}) |
|
3084 | bkms = self.db.get('bookmarks',{}) | |
3085 |
|
3085 | |||
3086 | if opts.has_key('d'): |
|
3086 | if opts.has_key('d'): | |
3087 | try: |
|
3087 | try: | |
3088 | todel = args[0] |
|
3088 | todel = args[0] | |
3089 | except IndexError: |
|
3089 | except IndexError: | |
3090 | raise UsageError( |
|
3090 | raise UsageError( | |
3091 | "%bookmark -d: must provide a bookmark to delete") |
|
3091 | "%bookmark -d: must provide a bookmark to delete") | |
3092 | else: |
|
3092 | else: | |
3093 | try: |
|
3093 | try: | |
3094 | del bkms[todel] |
|
3094 | del bkms[todel] | |
3095 | except KeyError: |
|
3095 | except KeyError: | |
3096 | raise UsageError( |
|
3096 | raise UsageError( | |
3097 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3097 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) | |
3098 |
|
3098 | |||
3099 | elif opts.has_key('r'): |
|
3099 | elif opts.has_key('r'): | |
3100 | bkms = {} |
|
3100 | bkms = {} | |
3101 | elif opts.has_key('l'): |
|
3101 | elif opts.has_key('l'): | |
3102 | bks = bkms.keys() |
|
3102 | bks = bkms.keys() | |
3103 | bks.sort() |
|
3103 | bks.sort() | |
3104 | if bks: |
|
3104 | if bks: | |
3105 | size = max(map(len,bks)) |
|
3105 | size = max(map(len,bks)) | |
3106 | else: |
|
3106 | else: | |
3107 | size = 0 |
|
3107 | size = 0 | |
3108 | fmt = '%-'+str(size)+'s -> %s' |
|
3108 | fmt = '%-'+str(size)+'s -> %s' | |
3109 | print 'Current bookmarks:' |
|
3109 | print 'Current bookmarks:' | |
3110 | for bk in bks: |
|
3110 | for bk in bks: | |
3111 | print fmt % (bk,bkms[bk]) |
|
3111 | print fmt % (bk,bkms[bk]) | |
3112 | else: |
|
3112 | else: | |
3113 | if not args: |
|
3113 | if not args: | |
3114 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3114 | raise UsageError("%bookmark: You must specify the bookmark name") | |
3115 | elif len(args)==1: |
|
3115 | elif len(args)==1: | |
3116 | bkms[args[0]] = os.getcwd() |
|
3116 | bkms[args[0]] = os.getcwd() | |
3117 | elif len(args)==2: |
|
3117 | elif len(args)==2: | |
3118 | bkms[args[0]] = args[1] |
|
3118 | bkms[args[0]] = args[1] | |
3119 | self.db['bookmarks'] = bkms |
|
3119 | self.db['bookmarks'] = bkms | |
3120 |
|
3120 | |||
3121 | def magic_pycat(self, parameter_s=''): |
|
3121 | def magic_pycat(self, parameter_s=''): | |
3122 | """Show a syntax-highlighted file through a pager. |
|
3122 | """Show a syntax-highlighted file through a pager. | |
3123 |
|
3123 | |||
3124 | This magic is similar to the cat utility, but it will assume the file |
|
3124 | This magic is similar to the cat utility, but it will assume the file | |
3125 | to be Python source and will show it with syntax highlighting. """ |
|
3125 | to be Python source and will show it with syntax highlighting. """ | |
3126 |
|
3126 | |||
3127 | try: |
|
3127 | try: | |
3128 | filename = get_py_filename(parameter_s) |
|
3128 | filename = get_py_filename(parameter_s) | |
3129 | cont = file_read(filename) |
|
3129 | cont = file_read(filename) | |
3130 | except IOError: |
|
3130 | except IOError: | |
3131 | try: |
|
3131 | try: | |
3132 | cont = eval(parameter_s,self.user_ns) |
|
3132 | cont = eval(parameter_s,self.user_ns) | |
3133 | except NameError: |
|
3133 | except NameError: | |
3134 | cont = None |
|
3134 | cont = None | |
3135 | if cont is None: |
|
3135 | if cont is None: | |
3136 | print "Error: no such file or variable" |
|
3136 | print "Error: no such file or variable" | |
3137 | return |
|
3137 | return | |
3138 |
|
3138 | |||
3139 | page(self.shell.pycolorize(cont), |
|
3139 | page(self.shell.pycolorize(cont), | |
3140 | screen_lines=self.shell.rc.screen_length) |
|
3140 | screen_lines=self.shell.rc.screen_length) | |
3141 |
|
3141 | |||
3142 | def magic_cpaste(self, parameter_s=''): |
|
3142 | def magic_cpaste(self, parameter_s=''): | |
3143 | """Allows you to paste & execute a pre-formatted code block from clipboard |
|
3143 | """Allows you to paste & execute a pre-formatted code block from clipboard | |
3144 |
|
3144 | |||
3145 | You must terminate the block with '--' (two minus-signs) alone on the |
|
3145 | You must terminate the block with '--' (two minus-signs) alone on the | |
3146 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' |
|
3146 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' | |
3147 | is the new sentinel for this operation) |
|
3147 | is the new sentinel for this operation) | |
3148 |
|
3148 | |||
3149 | The block is dedented prior to execution to enable execution of method |
|
3149 | The block is dedented prior to execution to enable execution of method | |
3150 | definitions. '>' and '+' characters at the beginning of a line are |
|
3150 | definitions. '>' and '+' characters at the beginning of a line are | |
3151 |
ignored, to allow pasting directly from e-mails |
|
3151 | ignored, to allow pasting directly from e-mails, diff files and doctests. | |
3152 | executed block is also assigned to variable named 'pasted_block' for |
|
3152 | The executed block is also assigned to variable named 'pasted_block' for | |
3153 | later editing with '%edit pasted_block'. |
|
3153 | later editing with '%edit pasted_block'. | |
3154 |
|
3154 | |||
3155 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
3155 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. | |
3156 | This assigns the pasted block to variable 'foo' as string, without |
|
3156 | This assigns the pasted block to variable 'foo' as string, without | |
3157 |
dedenting or executing it |
|
3157 | dedenting or executing it (preceding >>> and + is still stripped) | |
3158 |
|
3158 | |||
3159 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
3159 | Do not be alarmed by garbled output on Windows (it's a readline bug). | |
3160 | Just press enter and type -- (and press enter again) and the block |
|
3160 | Just press enter and type -- (and press enter again) and the block | |
3161 | will be what was just pasted. |
|
3161 | will be what was just pasted. | |
3162 |
|
3162 | |||
3163 | IPython statements (magics, shell escapes) are not supported (yet). |
|
3163 | IPython statements (magics, shell escapes) are not supported (yet). | |
3164 | """ |
|
3164 | """ | |
3165 | opts,args = self.parse_options(parameter_s,'s:',mode='string') |
|
3165 | opts,args = self.parse_options(parameter_s,'s:',mode='string') | |
3166 | par = args.strip() |
|
3166 | par = args.strip() | |
3167 | sentinel = opts.get('s','--') |
|
3167 | sentinel = opts.get('s','--') | |
3168 |
|
3168 | |||
3169 | strip_from_start = [re.compile(e) for e in |
|
3169 | strip_from_start = [re.compile(e) for e in | |
3170 |
['^ |
|
3170 | [r'^\s*(\s?>)+',r'^\s*In \[\d+\]:',r'^\++']] | |
3171 | from IPython import iplib |
|
3171 | from IPython import iplib | |
3172 | lines = [] |
|
3172 | lines = [] | |
3173 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3173 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel | |
3174 | while 1: |
|
3174 | while 1: | |
3175 | l = iplib.raw_input_original(':') |
|
3175 | l = iplib.raw_input_original(':') | |
3176 | if l ==sentinel: |
|
3176 | if l ==sentinel: | |
3177 | break |
|
3177 | break | |
3178 |
|
3178 | |||
3179 | for pat in strip_from_start: |
|
3179 | for pat in strip_from_start: | |
3180 | l = pat.sub('',l) |
|
3180 | l = pat.sub('',l) | |
3181 | lines.append(l) |
|
3181 | lines.append(l) | |
3182 |
|
3182 | |||
3183 | block = "\n".join(lines) + '\n' |
|
3183 | block = "\n".join(lines) + '\n' | |
3184 | #print "block:\n",block |
|
3184 | #print "block:\n",block | |
3185 | if not par: |
|
3185 | if not par: | |
3186 | b = textwrap.dedent(block) |
|
3186 | b = textwrap.dedent(block) | |
3187 | exec b in self.user_ns |
|
3187 | exec b in self.user_ns | |
3188 | self.user_ns['pasted_block'] = b |
|
3188 | self.user_ns['pasted_block'] = b | |
3189 | else: |
|
3189 | else: | |
3190 | self.user_ns[par] = block |
|
3190 | self.user_ns[par] = block | |
3191 | print "Block assigned to '%s'" % par |
|
3191 | print "Block assigned to '%s'" % par | |
3192 |
|
3192 | |||
3193 | def magic_quickref(self,arg): |
|
3193 | def magic_quickref(self,arg): | |
3194 | """ Show a quick reference sheet """ |
|
3194 | """ Show a quick reference sheet """ | |
3195 | import IPython.usage |
|
3195 | import IPython.usage | |
3196 | qr = IPython.usage.quick_reference + self.magic_magic('-brief') |
|
3196 | qr = IPython.usage.quick_reference + self.magic_magic('-brief') | |
3197 |
|
3197 | |||
3198 | page(qr) |
|
3198 | page(qr) | |
3199 |
|
3199 | |||
3200 | def magic_upgrade(self,arg): |
|
3200 | def magic_upgrade(self,arg): | |
3201 | """ Upgrade your IPython installation |
|
3201 | """ Upgrade your IPython installation | |
3202 |
|
3202 | |||
3203 | This will copy the config files that don't yet exist in your |
|
3203 | This will copy the config files that don't yet exist in your | |
3204 | ipython dir from the system config dir. Use this after upgrading |
|
3204 | ipython dir from the system config dir. Use this after upgrading | |
3205 | IPython if you don't wish to delete your .ipython dir. |
|
3205 | IPython if you don't wish to delete your .ipython dir. | |
3206 |
|
3206 | |||
3207 | Call with -nolegacy to get rid of ipythonrc* files (recommended for |
|
3207 | Call with -nolegacy to get rid of ipythonrc* files (recommended for | |
3208 | new users) |
|
3208 | new users) | |
3209 |
|
3209 | |||
3210 | """ |
|
3210 | """ | |
3211 | ip = self.getapi() |
|
3211 | ip = self.getapi() | |
3212 | ipinstallation = path(IPython.__file__).dirname() |
|
3212 | ipinstallation = path(IPython.__file__).dirname() | |
3213 | upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py') |
|
3213 | upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py') | |
3214 | src_config = ipinstallation / 'UserConfig' |
|
3214 | src_config = ipinstallation / 'UserConfig' | |
3215 | userdir = path(ip.options.ipythondir) |
|
3215 | userdir = path(ip.options.ipythondir) | |
3216 | cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir) |
|
3216 | cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir) | |
3217 | print ">",cmd |
|
3217 | print ">",cmd | |
3218 | shell(cmd) |
|
3218 | shell(cmd) | |
3219 | if arg == '-nolegacy': |
|
3219 | if arg == '-nolegacy': | |
3220 | legacy = userdir.files('ipythonrc*') |
|
3220 | legacy = userdir.files('ipythonrc*') | |
3221 | print "Nuking legacy files:",legacy |
|
3221 | print "Nuking legacy files:",legacy | |
3222 |
|
3222 | |||
3223 | [p.remove() for p in legacy] |
|
3223 | [p.remove() for p in legacy] | |
3224 | suffix = (sys.platform == 'win32' and '.ini' or '') |
|
3224 | suffix = (sys.platform == 'win32' and '.ini' or '') | |
3225 | (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n') |
|
3225 | (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n') | |
3226 |
|
3226 | |||
3227 |
|
3227 | |||
3228 | def magic_doctest_mode(self,parameter_s=''): |
|
3228 | def magic_doctest_mode(self,parameter_s=''): | |
3229 | """Toggle doctest mode on and off. |
|
3229 | """Toggle doctest mode on and off. | |
3230 |
|
3230 | |||
3231 | This mode allows you to toggle the prompt behavior between normal |
|
3231 | This mode allows you to toggle the prompt behavior between normal | |
3232 | IPython prompts and ones that are as similar to the default IPython |
|
3232 | IPython prompts and ones that are as similar to the default IPython | |
3233 | interpreter as possible. |
|
3233 | interpreter as possible. | |
3234 |
|
3234 | |||
3235 | It also supports the pasting of code snippets that have leading '>>>' |
|
3235 | It also supports the pasting of code snippets that have leading '>>>' | |
3236 | and '...' prompts in them. This means that you can paste doctests from |
|
3236 | and '...' prompts in them. This means that you can paste doctests from | |
3237 | files or docstrings (even if they have leading whitespace), and the |
|
3237 | files or docstrings (even if they have leading whitespace), and the | |
3238 | code will execute correctly. You can then use '%history -tn' to see |
|
3238 | code will execute correctly. You can then use '%history -tn' to see | |
3239 | the translated history without line numbers; this will give you the |
|
3239 | the translated history without line numbers; this will give you the | |
3240 | input after removal of all the leading prompts and whitespace, which |
|
3240 | input after removal of all the leading prompts and whitespace, which | |
3241 | can be pasted back into an editor. |
|
3241 | can be pasted back into an editor. | |
3242 |
|
3242 | |||
3243 | With these features, you can switch into this mode easily whenever you |
|
3243 | With these features, you can switch into this mode easily whenever you | |
3244 | need to do testing and changes to doctests, without having to leave |
|
3244 | need to do testing and changes to doctests, without having to leave | |
3245 | your existing IPython session. |
|
3245 | your existing IPython session. | |
3246 | """ |
|
3246 | """ | |
3247 |
|
3247 | |||
3248 | # XXX - Fix this to have cleaner activate/deactivate calls. |
|
3248 | # XXX - Fix this to have cleaner activate/deactivate calls. | |
3249 | from IPython.Extensions import InterpreterPasteInput as ipaste |
|
3249 | from IPython.Extensions import InterpreterPasteInput as ipaste | |
3250 | from IPython.ipstruct import Struct |
|
3250 | from IPython.ipstruct import Struct | |
3251 |
|
3251 | |||
3252 | # Shorthands |
|
3252 | # Shorthands | |
3253 | shell = self.shell |
|
3253 | shell = self.shell | |
3254 | oc = shell.outputcache |
|
3254 | oc = shell.outputcache | |
3255 | rc = shell.rc |
|
3255 | rc = shell.rc | |
3256 | meta = shell.meta |
|
3256 | meta = shell.meta | |
3257 | # dstore is a data store kept in the instance metadata bag to track any |
|
3257 | # dstore is a data store kept in the instance metadata bag to track any | |
3258 | # changes we make, so we can undo them later. |
|
3258 | # changes we make, so we can undo them later. | |
3259 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3259 | dstore = meta.setdefault('doctest_mode',Struct()) | |
3260 | save_dstore = dstore.setdefault |
|
3260 | save_dstore = dstore.setdefault | |
3261 |
|
3261 | |||
3262 | # save a few values we'll need to recover later |
|
3262 | # save a few values we'll need to recover later | |
3263 | mode = save_dstore('mode',False) |
|
3263 | mode = save_dstore('mode',False) | |
3264 | save_dstore('rc_pprint',rc.pprint) |
|
3264 | save_dstore('rc_pprint',rc.pprint) | |
3265 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3265 | save_dstore('xmode',shell.InteractiveTB.mode) | |
3266 | save_dstore('rc_separate_out',rc.separate_out) |
|
3266 | save_dstore('rc_separate_out',rc.separate_out) | |
3267 | save_dstore('rc_separate_out2',rc.separate_out2) |
|
3267 | save_dstore('rc_separate_out2',rc.separate_out2) | |
3268 | save_dstore('rc_prompts_pad_left',rc.prompts_pad_left) |
|
3268 | save_dstore('rc_prompts_pad_left',rc.prompts_pad_left) | |
3269 |
|
3269 | |||
3270 | if mode == False: |
|
3270 | if mode == False: | |
3271 | # turn on |
|
3271 | # turn on | |
3272 | ipaste.activate_prefilter() |
|
3272 | ipaste.activate_prefilter() | |
3273 |
|
3273 | |||
3274 | oc.prompt1.p_template = '>>> ' |
|
3274 | oc.prompt1.p_template = '>>> ' | |
3275 | oc.prompt2.p_template = '... ' |
|
3275 | oc.prompt2.p_template = '... ' | |
3276 | oc.prompt_out.p_template = '' |
|
3276 | oc.prompt_out.p_template = '' | |
3277 |
|
3277 | |||
3278 | oc.output_sep = '' |
|
3278 | oc.output_sep = '' | |
3279 | oc.output_sep2 = '' |
|
3279 | oc.output_sep2 = '' | |
3280 |
|
3280 | |||
3281 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3281 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3282 | oc.prompt_out.pad_left = False |
|
3282 | oc.prompt_out.pad_left = False | |
3283 |
|
3283 | |||
3284 | rc.pprint = False |
|
3284 | rc.pprint = False | |
3285 |
|
3285 | |||
3286 | shell.magic_xmode('Plain') |
|
3286 | shell.magic_xmode('Plain') | |
3287 |
|
3287 | |||
3288 | else: |
|
3288 | else: | |
3289 | # turn off |
|
3289 | # turn off | |
3290 | ipaste.deactivate_prefilter() |
|
3290 | ipaste.deactivate_prefilter() | |
3291 |
|
3291 | |||
3292 | oc.prompt1.p_template = rc.prompt_in1 |
|
3292 | oc.prompt1.p_template = rc.prompt_in1 | |
3293 | oc.prompt2.p_template = rc.prompt_in2 |
|
3293 | oc.prompt2.p_template = rc.prompt_in2 | |
3294 | oc.prompt_out.p_template = rc.prompt_out |
|
3294 | oc.prompt_out.p_template = rc.prompt_out | |
3295 |
|
3295 | |||
3296 | oc.output_sep = dstore.rc_separate_out |
|
3296 | oc.output_sep = dstore.rc_separate_out | |
3297 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3297 | oc.output_sep2 = dstore.rc_separate_out2 | |
3298 |
|
3298 | |||
3299 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3299 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3300 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3300 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left | |
3301 |
|
3301 | |||
3302 | rc.pprint = dstore.rc_pprint |
|
3302 | rc.pprint = dstore.rc_pprint | |
3303 |
|
3303 | |||
3304 | shell.magic_xmode(dstore.xmode) |
|
3304 | shell.magic_xmode(dstore.xmode) | |
3305 |
|
3305 | |||
3306 | # Store new mode and inform |
|
3306 | # Store new mode and inform | |
3307 | dstore.mode = bool(1-int(mode)) |
|
3307 | dstore.mode = bool(1-int(mode)) | |
3308 | print 'Doctest mode is:', |
|
3308 | print 'Doctest mode is:', | |
3309 | print ['OFF','ON'][dstore.mode] |
|
3309 | print ['OFF','ON'][dstore.mode] | |
3310 |
|
3310 | |||
3311 | # end Magic |
|
3311 | # end Magic |
@@ -1,87 +1,89 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Release data for the IPython project. |
|
2 | """Release data for the IPython project. | |
3 |
|
3 | |||
4 | $Id: Release.py 3002 2008-02-01 07:17:00Z fperez $""" |
|
4 | $Id: Release.py 3002 2008-02-01 07:17:00Z fperez $""" | |
5 |
|
5 | |||
6 | #***************************************************************************** |
|
6 | #***************************************************************************** | |
7 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> |
|
7 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> | |
8 | # |
|
8 | # | |
9 | # Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and Nathaniel Gray |
|
9 | # Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and Nathaniel Gray | |
10 | # <n8gray@caltech.edu> |
|
10 | # <n8gray@caltech.edu> | |
11 | # |
|
11 | # | |
12 | # Distributed under the terms of the BSD License. The full license is in |
|
12 | # Distributed under the terms of the BSD License. The full license is in | |
13 | # the file COPYING, distributed as part of this software. |
|
13 | # the file COPYING, distributed as part of this software. | |
14 | #***************************************************************************** |
|
14 | #***************************************************************************** | |
15 |
|
15 | |||
16 | # Name of the package for release purposes. This is the name which labels |
|
16 | # Name of the package for release purposes. This is the name which labels | |
17 | # the tarballs and RPMs made by distutils, so it's best to lowercase it. |
|
17 | # the tarballs and RPMs made by distutils, so it's best to lowercase it. | |
18 | name = 'ipython' |
|
18 | name = 'ipython' | |
19 |
|
19 | |||
20 | # For versions with substrings (like 0.6.16.svn), use an extra . to separate |
|
20 | # For versions with substrings (like 0.6.16.svn), use an extra . to separate | |
21 | # the new substring. We have to avoid using either dashes or underscores, |
|
21 | # the new substring. We have to avoid using either dashes or underscores, | |
22 | # because bdist_rpm does not accept dashes (an RPM) convention, and |
|
22 | # because bdist_rpm does not accept dashes (an RPM) convention, and | |
23 | # bdist_deb does not accept underscores (a Debian convention). |
|
23 | # bdist_deb does not accept underscores (a Debian convention). | |
24 |
|
24 | |||
25 |
revision = '1 |
|
25 | revision = '117' | |
26 | branch = 'ipython' |
|
26 | branch = 'ipython' | |
27 |
|
27 | |||
28 | if branch == 'ipython': |
|
28 | if branch == 'ipython': | |
29 | version = '0.8.3.bzr.r' + revision |
|
29 | version = '0.8.3.bzr.r' + revision | |
30 | else: |
|
30 | else: | |
31 | version = '0.8.3.bzr.r%s.%s' % (revision,branch) |
|
31 | version = '0.8.3.bzr.r%s.%s' % (revision,branch) | |
32 |
|
32 | |||
|
33 | version = '0.8.3' | |||
|
34 | ||||
33 | description = "An enhanced interactive Python shell." |
|
35 | description = "An enhanced interactive Python shell." | |
34 |
|
36 | |||
35 | long_description = \ |
|
37 | long_description = \ | |
36 | """ |
|
38 | """ | |
37 | IPython provides a replacement for the interactive Python interpreter with |
|
39 | IPython provides a replacement for the interactive Python interpreter with | |
38 | extra functionality. |
|
40 | extra functionality. | |
39 |
|
41 | |||
40 | Main features: |
|
42 | Main features: | |
41 |
|
43 | |||
42 | * Comprehensive object introspection. |
|
44 | * Comprehensive object introspection. | |
43 |
|
45 | |||
44 | * Input history, persistent across sessions. |
|
46 | * Input history, persistent across sessions. | |
45 |
|
47 | |||
46 | * Caching of output results during a session with automatically generated |
|
48 | * Caching of output results during a session with automatically generated | |
47 | references. |
|
49 | references. | |
48 |
|
50 | |||
49 | * Readline based name completion. |
|
51 | * Readline based name completion. | |
50 |
|
52 | |||
51 | * Extensible system of 'magic' commands for controlling the environment and |
|
53 | * Extensible system of 'magic' commands for controlling the environment and | |
52 | performing many tasks related either to IPython or the operating system. |
|
54 | performing many tasks related either to IPython or the operating system. | |
53 |
|
55 | |||
54 | * Configuration system with easy switching between different setups (simpler |
|
56 | * Configuration system with easy switching between different setups (simpler | |
55 | than changing $PYTHONSTARTUP environment variables every time). |
|
57 | than changing $PYTHONSTARTUP environment variables every time). | |
56 |
|
58 | |||
57 | * Session logging and reloading. |
|
59 | * Session logging and reloading. | |
58 |
|
60 | |||
59 | * Extensible syntax processing for special purpose situations. |
|
61 | * Extensible syntax processing for special purpose situations. | |
60 |
|
62 | |||
61 | * Access to the system shell with user-extensible alias system. |
|
63 | * Access to the system shell with user-extensible alias system. | |
62 |
|
64 | |||
63 | * Easily embeddable in other Python programs. |
|
65 | * Easily embeddable in other Python programs. | |
64 |
|
66 | |||
65 | * Integrated access to the pdb debugger and the Python profiler. |
|
67 | * Integrated access to the pdb debugger and the Python profiler. | |
66 |
|
68 | |||
67 | The latest development version is always available at the IPython subversion |
|
69 | The latest development version is always available at the IPython subversion | |
68 | repository_. |
|
70 | repository_. | |
69 |
|
71 | |||
70 | .. _repository: http://ipython.scipy.org/svn/ipython/ipython/trunk#egg=ipython-dev |
|
72 | .. _repository: http://ipython.scipy.org/svn/ipython/ipython/trunk#egg=ipython-dev | |
71 | """ |
|
73 | """ | |
72 |
|
74 | |||
73 | license = 'BSD' |
|
75 | license = 'BSD' | |
74 |
|
76 | |||
75 | authors = {'Fernando' : ('Fernando Perez','fperez@colorado.edu'), |
|
77 | authors = {'Fernando' : ('Fernando Perez','fperez@colorado.edu'), | |
76 | 'Janko' : ('Janko Hauser','jhauser@zscout.de'), |
|
78 | 'Janko' : ('Janko Hauser','jhauser@zscout.de'), | |
77 | 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu'), |
|
79 | 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu'), | |
78 | 'Ville' : ('Ville Vainio','vivainio@gmail.com') |
|
80 | 'Ville' : ('Ville Vainio','vivainio@gmail.com') | |
79 | } |
|
81 | } | |
80 |
|
82 | |||
81 | url = 'http://ipython.scipy.org' |
|
83 | url = 'http://ipython.scipy.org' | |
82 |
|
84 | |||
83 | download_url = 'http://ipython.scipy.org/dist' |
|
85 | download_url = 'http://ipython.scipy.org/dist' | |
84 |
|
86 | |||
85 | platforms = ['Linux','Mac OSX','Windows XP/2000/NT','Windows 95/98/ME'] |
|
87 | platforms = ['Linux','Mac OSX','Windows XP/2000/NT','Windows 95/98/ME'] | |
86 |
|
88 | |||
87 | keywords = ['Interactive','Interpreter','Shell'] |
|
89 | keywords = ['Interactive','Interpreter','Shell'] |
@@ -1,2040 +1,2043 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | General purpose utilities. |
|
3 | General purpose utilities. | |
4 |
|
4 | |||
5 | This is a grab-bag of stuff I find useful in most programs I write. Some of |
|
5 | This is a grab-bag of stuff I find useful in most programs I write. Some of | |
6 | these things are also convenient when working at the command line. |
|
6 | these things are also convenient when working at the command line. | |
7 |
|
7 | |||
8 | $Id: genutils.py 2998 2008-01-31 10:06:04Z vivainio $""" |
|
8 | $Id: genutils.py 2998 2008-01-31 10:06:04Z vivainio $""" | |
9 |
|
9 | |||
10 | #***************************************************************************** |
|
10 | #***************************************************************************** | |
11 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
11 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> | |
12 | # |
|
12 | # | |
13 | # Distributed under the terms of the BSD License. The full license is in |
|
13 | # Distributed under the terms of the BSD License. The full license is in | |
14 | # the file COPYING, distributed as part of this software. |
|
14 | # the file COPYING, distributed as part of this software. | |
15 | #***************************************************************************** |
|
15 | #***************************************************************************** | |
16 |
|
16 | |||
17 | from IPython import Release |
|
17 | from IPython import Release | |
18 | __author__ = '%s <%s>' % Release.authors['Fernando'] |
|
18 | __author__ = '%s <%s>' % Release.authors['Fernando'] | |
19 | __license__ = Release.license |
|
19 | __license__ = Release.license | |
20 |
|
20 | |||
21 | #**************************************************************************** |
|
21 | #**************************************************************************** | |
22 | # required modules from the Python standard library |
|
22 | # required modules from the Python standard library | |
23 | import __main__ |
|
23 | import __main__ | |
24 | import commands |
|
24 | import commands | |
25 | import doctest |
|
25 | try: | |
|
26 | import doctest | |||
|
27 | except ImportError: | |||
|
28 | pass | |||
26 | import os |
|
29 | import os | |
27 | import re |
|
30 | import re | |
28 | import shlex |
|
31 | import shlex | |
29 | import shutil |
|
32 | import shutil | |
30 | import sys |
|
33 | import sys | |
31 | import tempfile |
|
34 | import tempfile | |
32 | import time |
|
35 | import time | |
33 | import types |
|
36 | import types | |
34 | import warnings |
|
37 | import warnings | |
35 |
|
38 | |||
36 | # Curses and termios are Unix-only modules |
|
39 | # Curses and termios are Unix-only modules | |
37 | try: |
|
40 | try: | |
38 | import curses |
|
41 | import curses | |
39 | # We need termios as well, so if its import happens to raise, we bail on |
|
42 | # We need termios as well, so if its import happens to raise, we bail on | |
40 | # using curses altogether. |
|
43 | # using curses altogether. | |
41 | import termios |
|
44 | import termios | |
42 | except ImportError: |
|
45 | except ImportError: | |
43 | USE_CURSES = False |
|
46 | USE_CURSES = False | |
44 | else: |
|
47 | else: | |
45 | # Curses on Solaris may not be complete, so we can't use it there |
|
48 | # Curses on Solaris may not be complete, so we can't use it there | |
46 | USE_CURSES = hasattr(curses,'initscr') |
|
49 | USE_CURSES = hasattr(curses,'initscr') | |
47 |
|
50 | |||
48 | # Other IPython utilities |
|
51 | # Other IPython utilities | |
49 | import IPython |
|
52 | import IPython | |
50 | from IPython.Itpl import Itpl,itpl,printpl |
|
53 | from IPython.Itpl import Itpl,itpl,printpl | |
51 | from IPython import DPyGetOpt, platutils |
|
54 | from IPython import DPyGetOpt, platutils | |
52 | from IPython.generics import result_display |
|
55 | from IPython.generics import result_display | |
53 | import IPython.ipapi |
|
56 | import IPython.ipapi | |
54 | from IPython.external.path import path |
|
57 | from IPython.external.path import path | |
55 | if os.name == "nt": |
|
58 | if os.name == "nt": | |
56 | from IPython.winconsole import get_console_size |
|
59 | from IPython.winconsole import get_console_size | |
57 |
|
60 | |||
58 | try: |
|
61 | try: | |
59 | set |
|
62 | set | |
60 | except: |
|
63 | except: | |
61 | from sets import Set as set |
|
64 | from sets import Set as set | |
62 |
|
65 | |||
63 |
|
66 | |||
64 | #**************************************************************************** |
|
67 | #**************************************************************************** | |
65 | # Exceptions |
|
68 | # Exceptions | |
66 | class Error(Exception): |
|
69 | class Error(Exception): | |
67 | """Base class for exceptions in this module.""" |
|
70 | """Base class for exceptions in this module.""" | |
68 | pass |
|
71 | pass | |
69 |
|
72 | |||
70 | #---------------------------------------------------------------------------- |
|
73 | #---------------------------------------------------------------------------- | |
71 | class IOStream: |
|
74 | class IOStream: | |
72 | def __init__(self,stream,fallback): |
|
75 | def __init__(self,stream,fallback): | |
73 | if not hasattr(stream,'write') or not hasattr(stream,'flush'): |
|
76 | if not hasattr(stream,'write') or not hasattr(stream,'flush'): | |
74 | stream = fallback |
|
77 | stream = fallback | |
75 | self.stream = stream |
|
78 | self.stream = stream | |
76 | self._swrite = stream.write |
|
79 | self._swrite = stream.write | |
77 | self.flush = stream.flush |
|
80 | self.flush = stream.flush | |
78 |
|
81 | |||
79 | def write(self,data): |
|
82 | def write(self,data): | |
80 | try: |
|
83 | try: | |
81 | self._swrite(data) |
|
84 | self._swrite(data) | |
82 | except: |
|
85 | except: | |
83 | try: |
|
86 | try: | |
84 | # print handles some unicode issues which may trip a plain |
|
87 | # print handles some unicode issues which may trip a plain | |
85 | # write() call. Attempt to emulate write() by using a |
|
88 | # write() call. Attempt to emulate write() by using a | |
86 | # trailing comma |
|
89 | # trailing comma | |
87 | print >> self.stream, data, |
|
90 | print >> self.stream, data, | |
88 | except: |
|
91 | except: | |
89 | # if we get here, something is seriously broken. |
|
92 | # if we get here, something is seriously broken. | |
90 | print >> sys.stderr, \ |
|
93 | print >> sys.stderr, \ | |
91 | 'ERROR - failed to write data to stream:', self.stream |
|
94 | 'ERROR - failed to write data to stream:', self.stream | |
92 |
|
95 | |||
93 | def close(self): |
|
96 | def close(self): | |
94 | pass |
|
97 | pass | |
95 |
|
98 | |||
96 |
|
99 | |||
97 | class IOTerm: |
|
100 | class IOTerm: | |
98 | """ Term holds the file or file-like objects for handling I/O operations. |
|
101 | """ Term holds the file or file-like objects for handling I/O operations. | |
99 |
|
102 | |||
100 | These are normally just sys.stdin, sys.stdout and sys.stderr but for |
|
103 | These are normally just sys.stdin, sys.stdout and sys.stderr but for | |
101 | Windows they can can replaced to allow editing the strings before they are |
|
104 | Windows they can can replaced to allow editing the strings before they are | |
102 | displayed.""" |
|
105 | displayed.""" | |
103 |
|
106 | |||
104 | # In the future, having IPython channel all its I/O operations through |
|
107 | # In the future, having IPython channel all its I/O operations through | |
105 | # this class will make it easier to embed it into other environments which |
|
108 | # this class will make it easier to embed it into other environments which | |
106 | # are not a normal terminal (such as a GUI-based shell) |
|
109 | # are not a normal terminal (such as a GUI-based shell) | |
107 | def __init__(self,cin=None,cout=None,cerr=None): |
|
110 | def __init__(self,cin=None,cout=None,cerr=None): | |
108 | self.cin = IOStream(cin,sys.stdin) |
|
111 | self.cin = IOStream(cin,sys.stdin) | |
109 | self.cout = IOStream(cout,sys.stdout) |
|
112 | self.cout = IOStream(cout,sys.stdout) | |
110 | self.cerr = IOStream(cerr,sys.stderr) |
|
113 | self.cerr = IOStream(cerr,sys.stderr) | |
111 |
|
114 | |||
112 | # Global variable to be used for all I/O |
|
115 | # Global variable to be used for all I/O | |
113 | Term = IOTerm() |
|
116 | Term = IOTerm() | |
114 |
|
117 | |||
115 | import IPython.rlineimpl as readline |
|
118 | import IPython.rlineimpl as readline | |
116 | # Remake Term to use the readline i/o facilities |
|
119 | # Remake Term to use the readline i/o facilities | |
117 | if sys.platform == 'win32' and readline.have_readline: |
|
120 | if sys.platform == 'win32' and readline.have_readline: | |
118 |
|
121 | |||
119 | Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile) |
|
122 | Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile) | |
120 |
|
123 | |||
121 |
|
124 | |||
122 | #**************************************************************************** |
|
125 | #**************************************************************************** | |
123 | # Generic warning/error printer, used by everything else |
|
126 | # Generic warning/error printer, used by everything else | |
124 | def warn(msg,level=2,exit_val=1): |
|
127 | def warn(msg,level=2,exit_val=1): | |
125 | """Standard warning printer. Gives formatting consistency. |
|
128 | """Standard warning printer. Gives formatting consistency. | |
126 |
|
129 | |||
127 | Output is sent to Term.cerr (sys.stderr by default). |
|
130 | Output is sent to Term.cerr (sys.stderr by default). | |
128 |
|
131 | |||
129 | Options: |
|
132 | Options: | |
130 |
|
133 | |||
131 | -level(2): allows finer control: |
|
134 | -level(2): allows finer control: | |
132 | 0 -> Do nothing, dummy function. |
|
135 | 0 -> Do nothing, dummy function. | |
133 | 1 -> Print message. |
|
136 | 1 -> Print message. | |
134 | 2 -> Print 'WARNING:' + message. (Default level). |
|
137 | 2 -> Print 'WARNING:' + message. (Default level). | |
135 | 3 -> Print 'ERROR:' + message. |
|
138 | 3 -> Print 'ERROR:' + message. | |
136 | 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val). |
|
139 | 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val). | |
137 |
|
140 | |||
138 | -exit_val (1): exit value returned by sys.exit() for a level 4 |
|
141 | -exit_val (1): exit value returned by sys.exit() for a level 4 | |
139 | warning. Ignored for all other levels.""" |
|
142 | warning. Ignored for all other levels.""" | |
140 |
|
143 | |||
141 | if level>0: |
|
144 | if level>0: | |
142 | header = ['','','WARNING: ','ERROR: ','FATAL ERROR: '] |
|
145 | header = ['','','WARNING: ','ERROR: ','FATAL ERROR: '] | |
143 | print >> Term.cerr, '%s%s' % (header[level],msg) |
|
146 | print >> Term.cerr, '%s%s' % (header[level],msg) | |
144 | if level == 4: |
|
147 | if level == 4: | |
145 | print >> Term.cerr,'Exiting.\n' |
|
148 | print >> Term.cerr,'Exiting.\n' | |
146 | sys.exit(exit_val) |
|
149 | sys.exit(exit_val) | |
147 |
|
150 | |||
148 | def info(msg): |
|
151 | def info(msg): | |
149 | """Equivalent to warn(msg,level=1).""" |
|
152 | """Equivalent to warn(msg,level=1).""" | |
150 |
|
153 | |||
151 | warn(msg,level=1) |
|
154 | warn(msg,level=1) | |
152 |
|
155 | |||
153 | def error(msg): |
|
156 | def error(msg): | |
154 | """Equivalent to warn(msg,level=3).""" |
|
157 | """Equivalent to warn(msg,level=3).""" | |
155 |
|
158 | |||
156 | warn(msg,level=3) |
|
159 | warn(msg,level=3) | |
157 |
|
160 | |||
158 | def fatal(msg,exit_val=1): |
|
161 | def fatal(msg,exit_val=1): | |
159 | """Equivalent to warn(msg,exit_val=exit_val,level=4).""" |
|
162 | """Equivalent to warn(msg,exit_val=exit_val,level=4).""" | |
160 |
|
163 | |||
161 | warn(msg,exit_val=exit_val,level=4) |
|
164 | warn(msg,exit_val=exit_val,level=4) | |
162 |
|
165 | |||
163 | #--------------------------------------------------------------------------- |
|
166 | #--------------------------------------------------------------------------- | |
164 | # Debugging routines |
|
167 | # Debugging routines | |
165 | # |
|
168 | # | |
166 | def debugx(expr,pre_msg=''): |
|
169 | def debugx(expr,pre_msg=''): | |
167 | """Print the value of an expression from the caller's frame. |
|
170 | """Print the value of an expression from the caller's frame. | |
168 |
|
171 | |||
169 | Takes an expression, evaluates it in the caller's frame and prints both |
|
172 | Takes an expression, evaluates it in the caller's frame and prints both | |
170 | the given expression and the resulting value (as well as a debug mark |
|
173 | the given expression and the resulting value (as well as a debug mark | |
171 | indicating the name of the calling function. The input must be of a form |
|
174 | indicating the name of the calling function. The input must be of a form | |
172 | suitable for eval(). |
|
175 | suitable for eval(). | |
173 |
|
176 | |||
174 | An optional message can be passed, which will be prepended to the printed |
|
177 | An optional message can be passed, which will be prepended to the printed | |
175 | expr->value pair.""" |
|
178 | expr->value pair.""" | |
176 |
|
179 | |||
177 | cf = sys._getframe(1) |
|
180 | cf = sys._getframe(1) | |
178 | print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr, |
|
181 | print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr, | |
179 | eval(expr,cf.f_globals,cf.f_locals)) |
|
182 | eval(expr,cf.f_globals,cf.f_locals)) | |
180 |
|
183 | |||
181 | # deactivate it by uncommenting the following line, which makes it a no-op |
|
184 | # deactivate it by uncommenting the following line, which makes it a no-op | |
182 | #def debugx(expr,pre_msg=''): pass |
|
185 | #def debugx(expr,pre_msg=''): pass | |
183 |
|
186 | |||
184 | #---------------------------------------------------------------------------- |
|
187 | #---------------------------------------------------------------------------- | |
185 | StringTypes = types.StringTypes |
|
188 | StringTypes = types.StringTypes | |
186 |
|
189 | |||
187 | # Basic timing functionality |
|
190 | # Basic timing functionality | |
188 |
|
191 | |||
189 | # If possible (Unix), use the resource module instead of time.clock() |
|
192 | # If possible (Unix), use the resource module instead of time.clock() | |
190 | try: |
|
193 | try: | |
191 | import resource |
|
194 | import resource | |
192 | def clocku(): |
|
195 | def clocku(): | |
193 | """clocku() -> floating point number |
|
196 | """clocku() -> floating point number | |
194 |
|
197 | |||
195 | Return the *USER* CPU time in seconds since the start of the process. |
|
198 | Return the *USER* CPU time in seconds since the start of the process. | |
196 | This is done via a call to resource.getrusage, so it avoids the |
|
199 | This is done via a call to resource.getrusage, so it avoids the | |
197 | wraparound problems in time.clock().""" |
|
200 | wraparound problems in time.clock().""" | |
198 |
|
201 | |||
199 | return resource.getrusage(resource.RUSAGE_SELF)[0] |
|
202 | return resource.getrusage(resource.RUSAGE_SELF)[0] | |
200 |
|
203 | |||
201 | def clocks(): |
|
204 | def clocks(): | |
202 | """clocks() -> floating point number |
|
205 | """clocks() -> floating point number | |
203 |
|
206 | |||
204 | Return the *SYSTEM* CPU time in seconds since the start of the process. |
|
207 | Return the *SYSTEM* CPU time in seconds since the start of the process. | |
205 | This is done via a call to resource.getrusage, so it avoids the |
|
208 | This is done via a call to resource.getrusage, so it avoids the | |
206 | wraparound problems in time.clock().""" |
|
209 | wraparound problems in time.clock().""" | |
207 |
|
210 | |||
208 | return resource.getrusage(resource.RUSAGE_SELF)[1] |
|
211 | return resource.getrusage(resource.RUSAGE_SELF)[1] | |
209 |
|
212 | |||
210 | def clock(): |
|
213 | def clock(): | |
211 | """clock() -> floating point number |
|
214 | """clock() -> floating point number | |
212 |
|
215 | |||
213 | Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of |
|
216 | Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of | |
214 | the process. This is done via a call to resource.getrusage, so it |
|
217 | the process. This is done via a call to resource.getrusage, so it | |
215 | avoids the wraparound problems in time.clock().""" |
|
218 | avoids the wraparound problems in time.clock().""" | |
216 |
|
219 | |||
217 | u,s = resource.getrusage(resource.RUSAGE_SELF)[:2] |
|
220 | u,s = resource.getrusage(resource.RUSAGE_SELF)[:2] | |
218 | return u+s |
|
221 | return u+s | |
219 |
|
222 | |||
220 | def clock2(): |
|
223 | def clock2(): | |
221 | """clock2() -> (t_user,t_system) |
|
224 | """clock2() -> (t_user,t_system) | |
222 |
|
225 | |||
223 | Similar to clock(), but return a tuple of user/system times.""" |
|
226 | Similar to clock(), but return a tuple of user/system times.""" | |
224 | return resource.getrusage(resource.RUSAGE_SELF)[:2] |
|
227 | return resource.getrusage(resource.RUSAGE_SELF)[:2] | |
225 |
|
228 | |||
226 | except ImportError: |
|
229 | except ImportError: | |
227 | # There is no distinction of user/system time under windows, so we just use |
|
230 | # There is no distinction of user/system time under windows, so we just use | |
228 | # time.clock() for everything... |
|
231 | # time.clock() for everything... | |
229 | clocku = clocks = clock = time.clock |
|
232 | clocku = clocks = clock = time.clock | |
230 | def clock2(): |
|
233 | def clock2(): | |
231 | """Under windows, system CPU time can't be measured. |
|
234 | """Under windows, system CPU time can't be measured. | |
232 |
|
235 | |||
233 | This just returns clock() and zero.""" |
|
236 | This just returns clock() and zero.""" | |
234 | return time.clock(),0.0 |
|
237 | return time.clock(),0.0 | |
235 |
|
238 | |||
236 | def timings_out(reps,func,*args,**kw): |
|
239 | def timings_out(reps,func,*args,**kw): | |
237 | """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output) |
|
240 | """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output) | |
238 |
|
241 | |||
239 | Execute a function reps times, return a tuple with the elapsed total |
|
242 | Execute a function reps times, return a tuple with the elapsed total | |
240 | CPU time in seconds, the time per call and the function's output. |
|
243 | CPU time in seconds, the time per call and the function's output. | |
241 |
|
244 | |||
242 | Under Unix, the return value is the sum of user+system time consumed by |
|
245 | Under Unix, the return value is the sum of user+system time consumed by | |
243 | the process, computed via the resource module. This prevents problems |
|
246 | the process, computed via the resource module. This prevents problems | |
244 | related to the wraparound effect which the time.clock() function has. |
|
247 | related to the wraparound effect which the time.clock() function has. | |
245 |
|
248 | |||
246 | Under Windows the return value is in wall clock seconds. See the |
|
249 | Under Windows the return value is in wall clock seconds. See the | |
247 | documentation for the time module for more details.""" |
|
250 | documentation for the time module for more details.""" | |
248 |
|
251 | |||
249 | reps = int(reps) |
|
252 | reps = int(reps) | |
250 | assert reps >=1, 'reps must be >= 1' |
|
253 | assert reps >=1, 'reps must be >= 1' | |
251 | if reps==1: |
|
254 | if reps==1: | |
252 | start = clock() |
|
255 | start = clock() | |
253 | out = func(*args,**kw) |
|
256 | out = func(*args,**kw) | |
254 | tot_time = clock()-start |
|
257 | tot_time = clock()-start | |
255 | else: |
|
258 | else: | |
256 | rng = xrange(reps-1) # the last time is executed separately to store output |
|
259 | rng = xrange(reps-1) # the last time is executed separately to store output | |
257 | start = clock() |
|
260 | start = clock() | |
258 | for dummy in rng: func(*args,**kw) |
|
261 | for dummy in rng: func(*args,**kw) | |
259 | out = func(*args,**kw) # one last time |
|
262 | out = func(*args,**kw) # one last time | |
260 | tot_time = clock()-start |
|
263 | tot_time = clock()-start | |
261 | av_time = tot_time / reps |
|
264 | av_time = tot_time / reps | |
262 | return tot_time,av_time,out |
|
265 | return tot_time,av_time,out | |
263 |
|
266 | |||
264 | def timings(reps,func,*args,**kw): |
|
267 | def timings(reps,func,*args,**kw): | |
265 | """timings(reps,func,*args,**kw) -> (t_total,t_per_call) |
|
268 | """timings(reps,func,*args,**kw) -> (t_total,t_per_call) | |
266 |
|
269 | |||
267 | Execute a function reps times, return a tuple with the elapsed total CPU |
|
270 | Execute a function reps times, return a tuple with the elapsed total CPU | |
268 | time in seconds and the time per call. These are just the first two values |
|
271 | time in seconds and the time per call. These are just the first two values | |
269 | in timings_out().""" |
|
272 | in timings_out().""" | |
270 |
|
273 | |||
271 | return timings_out(reps,func,*args,**kw)[0:2] |
|
274 | return timings_out(reps,func,*args,**kw)[0:2] | |
272 |
|
275 | |||
273 | def timing(func,*args,**kw): |
|
276 | def timing(func,*args,**kw): | |
274 | """timing(func,*args,**kw) -> t_total |
|
277 | """timing(func,*args,**kw) -> t_total | |
275 |
|
278 | |||
276 | Execute a function once, return the elapsed total CPU time in |
|
279 | Execute a function once, return the elapsed total CPU time in | |
277 | seconds. This is just the first value in timings_out().""" |
|
280 | seconds. This is just the first value in timings_out().""" | |
278 |
|
281 | |||
279 | return timings_out(1,func,*args,**kw)[0] |
|
282 | return timings_out(1,func,*args,**kw)[0] | |
280 |
|
283 | |||
281 | #**************************************************************************** |
|
284 | #**************************************************************************** | |
282 | # file and system |
|
285 | # file and system | |
283 |
|
286 | |||
284 | def arg_split(s,posix=False): |
|
287 | def arg_split(s,posix=False): | |
285 | """Split a command line's arguments in a shell-like manner. |
|
288 | """Split a command line's arguments in a shell-like manner. | |
286 |
|
289 | |||
287 | This is a modified version of the standard library's shlex.split() |
|
290 | This is a modified version of the standard library's shlex.split() | |
288 | function, but with a default of posix=False for splitting, so that quotes |
|
291 | function, but with a default of posix=False for splitting, so that quotes | |
289 | in inputs are respected.""" |
|
292 | in inputs are respected.""" | |
290 |
|
293 | |||
291 | # XXX - there may be unicode-related problems here!!! I'm not sure that |
|
294 | # XXX - there may be unicode-related problems here!!! I'm not sure that | |
292 | # shlex is truly unicode-safe, so it might be necessary to do |
|
295 | # shlex is truly unicode-safe, so it might be necessary to do | |
293 | # |
|
296 | # | |
294 | # s = s.encode(sys.stdin.encoding) |
|
297 | # s = s.encode(sys.stdin.encoding) | |
295 | # |
|
298 | # | |
296 | # first, to ensure that shlex gets a normal string. Input from anyone who |
|
299 | # first, to ensure that shlex gets a normal string. Input from anyone who | |
297 | # knows more about unicode and shlex than I would be good to have here... |
|
300 | # knows more about unicode and shlex than I would be good to have here... | |
298 | lex = shlex.shlex(s, posix=posix) |
|
301 | lex = shlex.shlex(s, posix=posix) | |
299 | lex.whitespace_split = True |
|
302 | lex.whitespace_split = True | |
300 | return list(lex) |
|
303 | return list(lex) | |
301 |
|
304 | |||
302 | def system(cmd,verbose=0,debug=0,header=''): |
|
305 | def system(cmd,verbose=0,debug=0,header=''): | |
303 | """Execute a system command, return its exit status. |
|
306 | """Execute a system command, return its exit status. | |
304 |
|
307 | |||
305 | Options: |
|
308 | Options: | |
306 |
|
309 | |||
307 | - verbose (0): print the command to be executed. |
|
310 | - verbose (0): print the command to be executed. | |
308 |
|
311 | |||
309 | - debug (0): only print, do not actually execute. |
|
312 | - debug (0): only print, do not actually execute. | |
310 |
|
313 | |||
311 | - header (''): Header to print on screen prior to the executed command (it |
|
314 | - header (''): Header to print on screen prior to the executed command (it | |
312 | is only prepended to the command, no newlines are added). |
|
315 | is only prepended to the command, no newlines are added). | |
313 |
|
316 | |||
314 | Note: a stateful version of this function is available through the |
|
317 | Note: a stateful version of this function is available through the | |
315 | SystemExec class.""" |
|
318 | SystemExec class.""" | |
316 |
|
319 | |||
317 | stat = 0 |
|
320 | stat = 0 | |
318 | if verbose or debug: print header+cmd |
|
321 | if verbose or debug: print header+cmd | |
319 | sys.stdout.flush() |
|
322 | sys.stdout.flush() | |
320 | if not debug: stat = os.system(cmd) |
|
323 | if not debug: stat = os.system(cmd) | |
321 | return stat |
|
324 | return stat | |
322 |
|
325 | |||
323 | def abbrev_cwd(): |
|
326 | def abbrev_cwd(): | |
324 | """ Return abbreviated version of cwd, e.g. d:mydir """ |
|
327 | """ Return abbreviated version of cwd, e.g. d:mydir """ | |
325 | cwd = os.getcwd().replace('\\','/') |
|
328 | cwd = os.getcwd().replace('\\','/') | |
326 | drivepart = '' |
|
329 | drivepart = '' | |
327 | tail = cwd |
|
330 | tail = cwd | |
328 | if sys.platform == 'win32': |
|
331 | if sys.platform == 'win32': | |
329 | if len(cwd) < 4: |
|
332 | if len(cwd) < 4: | |
330 | return cwd |
|
333 | return cwd | |
331 | drivepart,tail = os.path.splitdrive(cwd) |
|
334 | drivepart,tail = os.path.splitdrive(cwd) | |
332 |
|
335 | |||
333 |
|
336 | |||
334 | parts = tail.split('/') |
|
337 | parts = tail.split('/') | |
335 | if len(parts) > 2: |
|
338 | if len(parts) > 2: | |
336 | tail = '/'.join(parts[-2:]) |
|
339 | tail = '/'.join(parts[-2:]) | |
337 |
|
340 | |||
338 | return (drivepart + ( |
|
341 | return (drivepart + ( | |
339 | cwd == '/' and '/' or tail)) |
|
342 | cwd == '/' and '/' or tail)) | |
340 |
|
343 | |||
341 |
|
344 | |||
342 | # This function is used by ipython in a lot of places to make system calls. |
|
345 | # This function is used by ipython in a lot of places to make system calls. | |
343 | # We need it to be slightly different under win32, due to the vagaries of |
|
346 | # We need it to be slightly different under win32, due to the vagaries of | |
344 | # 'network shares'. A win32 override is below. |
|
347 | # 'network shares'. A win32 override is below. | |
345 |
|
348 | |||
346 | def shell(cmd,verbose=0,debug=0,header=''): |
|
349 | def shell(cmd,verbose=0,debug=0,header=''): | |
347 | """Execute a command in the system shell, always return None. |
|
350 | """Execute a command in the system shell, always return None. | |
348 |
|
351 | |||
349 | Options: |
|
352 | Options: | |
350 |
|
353 | |||
351 | - verbose (0): print the command to be executed. |
|
354 | - verbose (0): print the command to be executed. | |
352 |
|
355 | |||
353 | - debug (0): only print, do not actually execute. |
|
356 | - debug (0): only print, do not actually execute. | |
354 |
|
357 | |||
355 | - header (''): Header to print on screen prior to the executed command (it |
|
358 | - header (''): Header to print on screen prior to the executed command (it | |
356 | is only prepended to the command, no newlines are added). |
|
359 | is only prepended to the command, no newlines are added). | |
357 |
|
360 | |||
358 | Note: this is similar to genutils.system(), but it returns None so it can |
|
361 | Note: this is similar to genutils.system(), but it returns None so it can | |
359 | be conveniently used in interactive loops without getting the return value |
|
362 | be conveniently used in interactive loops without getting the return value | |
360 | (typically 0) printed many times.""" |
|
363 | (typically 0) printed many times.""" | |
361 |
|
364 | |||
362 | stat = 0 |
|
365 | stat = 0 | |
363 | if verbose or debug: print header+cmd |
|
366 | if verbose or debug: print header+cmd | |
364 | # flush stdout so we don't mangle python's buffering |
|
367 | # flush stdout so we don't mangle python's buffering | |
365 | sys.stdout.flush() |
|
368 | sys.stdout.flush() | |
366 |
|
369 | |||
367 | if not debug: |
|
370 | if not debug: | |
368 | platutils.set_term_title("IPy " + cmd) |
|
371 | platutils.set_term_title("IPy " + cmd) | |
369 | os.system(cmd) |
|
372 | os.system(cmd) | |
370 | platutils.set_term_title("IPy " + abbrev_cwd()) |
|
373 | platutils.set_term_title("IPy " + abbrev_cwd()) | |
371 |
|
374 | |||
372 | # override shell() for win32 to deal with network shares |
|
375 | # override shell() for win32 to deal with network shares | |
373 | if os.name in ('nt','dos'): |
|
376 | if os.name in ('nt','dos'): | |
374 |
|
377 | |||
375 | shell_ori = shell |
|
378 | shell_ori = shell | |
376 |
|
379 | |||
377 | def shell(cmd,verbose=0,debug=0,header=''): |
|
380 | def shell(cmd,verbose=0,debug=0,header=''): | |
378 | if os.getcwd().startswith(r"\\"): |
|
381 | if os.getcwd().startswith(r"\\"): | |
379 | path = os.getcwd() |
|
382 | path = os.getcwd() | |
380 | # change to c drive (cannot be on UNC-share when issuing os.system, |
|
383 | # change to c drive (cannot be on UNC-share when issuing os.system, | |
381 | # as cmd.exe cannot handle UNC addresses) |
|
384 | # as cmd.exe cannot handle UNC addresses) | |
382 | os.chdir("c:") |
|
385 | os.chdir("c:") | |
383 | # issue pushd to the UNC-share and then run the command |
|
386 | # issue pushd to the UNC-share and then run the command | |
384 | try: |
|
387 | try: | |
385 | shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header) |
|
388 | shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header) | |
386 | finally: |
|
389 | finally: | |
387 | os.chdir(path) |
|
390 | os.chdir(path) | |
388 | else: |
|
391 | else: | |
389 | shell_ori(cmd,verbose,debug,header) |
|
392 | shell_ori(cmd,verbose,debug,header) | |
390 |
|
393 | |||
391 | shell.__doc__ = shell_ori.__doc__ |
|
394 | shell.__doc__ = shell_ori.__doc__ | |
392 |
|
395 | |||
393 | def getoutput(cmd,verbose=0,debug=0,header='',split=0): |
|
396 | def getoutput(cmd,verbose=0,debug=0,header='',split=0): | |
394 | """Dummy substitute for perl's backquotes. |
|
397 | """Dummy substitute for perl's backquotes. | |
395 |
|
398 | |||
396 | Executes a command and returns the output. |
|
399 | Executes a command and returns the output. | |
397 |
|
400 | |||
398 | Accepts the same arguments as system(), plus: |
|
401 | Accepts the same arguments as system(), plus: | |
399 |
|
402 | |||
400 | - split(0): if true, the output is returned as a list split on newlines. |
|
403 | - split(0): if true, the output is returned as a list split on newlines. | |
401 |
|
404 | |||
402 | Note: a stateful version of this function is available through the |
|
405 | Note: a stateful version of this function is available through the | |
403 | SystemExec class. |
|
406 | SystemExec class. | |
404 |
|
407 | |||
405 | This is pretty much deprecated and rarely used, |
|
408 | This is pretty much deprecated and rarely used, | |
406 | genutils.getoutputerror may be what you need. |
|
409 | genutils.getoutputerror may be what you need. | |
407 |
|
410 | |||
408 | """ |
|
411 | """ | |
409 |
|
412 | |||
410 | if verbose or debug: print header+cmd |
|
413 | if verbose or debug: print header+cmd | |
411 | if not debug: |
|
414 | if not debug: | |
412 | output = os.popen(cmd).read() |
|
415 | output = os.popen(cmd).read() | |
413 | # stipping last \n is here for backwards compat. |
|
416 | # stipping last \n is here for backwards compat. | |
414 | if output.endswith('\n'): |
|
417 | if output.endswith('\n'): | |
415 | output = output[:-1] |
|
418 | output = output[:-1] | |
416 | if split: |
|
419 | if split: | |
417 | return output.split('\n') |
|
420 | return output.split('\n') | |
418 | else: |
|
421 | else: | |
419 | return output |
|
422 | return output | |
420 |
|
423 | |||
421 | def getoutputerror(cmd,verbose=0,debug=0,header='',split=0): |
|
424 | def getoutputerror(cmd,verbose=0,debug=0,header='',split=0): | |
422 | """Return (standard output,standard error) of executing cmd in a shell. |
|
425 | """Return (standard output,standard error) of executing cmd in a shell. | |
423 |
|
426 | |||
424 | Accepts the same arguments as system(), plus: |
|
427 | Accepts the same arguments as system(), plus: | |
425 |
|
428 | |||
426 | - split(0): if true, each of stdout/err is returned as a list split on |
|
429 | - split(0): if true, each of stdout/err is returned as a list split on | |
427 | newlines. |
|
430 | newlines. | |
428 |
|
431 | |||
429 | Note: a stateful version of this function is available through the |
|
432 | Note: a stateful version of this function is available through the | |
430 | SystemExec class.""" |
|
433 | SystemExec class.""" | |
431 |
|
434 | |||
432 | if verbose or debug: print header+cmd |
|
435 | if verbose or debug: print header+cmd | |
433 | if not cmd: |
|
436 | if not cmd: | |
434 | if split: |
|
437 | if split: | |
435 | return [],[] |
|
438 | return [],[] | |
436 | else: |
|
439 | else: | |
437 | return '','' |
|
440 | return '','' | |
438 | if not debug: |
|
441 | if not debug: | |
439 | pin,pout,perr = os.popen3(cmd) |
|
442 | pin,pout,perr = os.popen3(cmd) | |
440 | tout = pout.read().rstrip() |
|
443 | tout = pout.read().rstrip() | |
441 | terr = perr.read().rstrip() |
|
444 | terr = perr.read().rstrip() | |
442 | pin.close() |
|
445 | pin.close() | |
443 | pout.close() |
|
446 | pout.close() | |
444 | perr.close() |
|
447 | perr.close() | |
445 | if split: |
|
448 | if split: | |
446 | return tout.split('\n'),terr.split('\n') |
|
449 | return tout.split('\n'),terr.split('\n') | |
447 | else: |
|
450 | else: | |
448 | return tout,terr |
|
451 | return tout,terr | |
449 |
|
452 | |||
450 | # for compatibility with older naming conventions |
|
453 | # for compatibility with older naming conventions | |
451 | xsys = system |
|
454 | xsys = system | |
452 | bq = getoutput |
|
455 | bq = getoutput | |
453 |
|
456 | |||
454 | class SystemExec: |
|
457 | class SystemExec: | |
455 | """Access the system and getoutput functions through a stateful interface. |
|
458 | """Access the system and getoutput functions through a stateful interface. | |
456 |
|
459 | |||
457 | Note: here we refer to the system and getoutput functions from this |
|
460 | Note: here we refer to the system and getoutput functions from this | |
458 | library, not the ones from the standard python library. |
|
461 | library, not the ones from the standard python library. | |
459 |
|
462 | |||
460 | This class offers the system and getoutput functions as methods, but the |
|
463 | This class offers the system and getoutput functions as methods, but the | |
461 | verbose, debug and header parameters can be set for the instance (at |
|
464 | verbose, debug and header parameters can be set for the instance (at | |
462 | creation time or later) so that they don't need to be specified on each |
|
465 | creation time or later) so that they don't need to be specified on each | |
463 | call. |
|
466 | call. | |
464 |
|
467 | |||
465 | For efficiency reasons, there's no way to override the parameters on a |
|
468 | For efficiency reasons, there's no way to override the parameters on a | |
466 | per-call basis other than by setting instance attributes. If you need |
|
469 | per-call basis other than by setting instance attributes. If you need | |
467 | local overrides, it's best to directly call system() or getoutput(). |
|
470 | local overrides, it's best to directly call system() or getoutput(). | |
468 |
|
471 | |||
469 | The following names are provided as alternate options: |
|
472 | The following names are provided as alternate options: | |
470 | - xsys: alias to system |
|
473 | - xsys: alias to system | |
471 | - bq: alias to getoutput |
|
474 | - bq: alias to getoutput | |
472 |
|
475 | |||
473 | An instance can then be created as: |
|
476 | An instance can then be created as: | |
474 | >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ') |
|
477 | >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ') | |
475 |
|
478 | |||
476 | And used as: |
|
479 | And used as: | |
477 | >>> sysexec.xsys('pwd') |
|
480 | >>> sysexec.xsys('pwd') | |
478 | >>> dirlist = sysexec.bq('ls -l') |
|
481 | >>> dirlist = sysexec.bq('ls -l') | |
479 | """ |
|
482 | """ | |
480 |
|
483 | |||
481 | def __init__(self,verbose=0,debug=0,header='',split=0): |
|
484 | def __init__(self,verbose=0,debug=0,header='',split=0): | |
482 | """Specify the instance's values for verbose, debug and header.""" |
|
485 | """Specify the instance's values for verbose, debug and header.""" | |
483 | setattr_list(self,'verbose debug header split') |
|
486 | setattr_list(self,'verbose debug header split') | |
484 |
|
487 | |||
485 | def system(self,cmd): |
|
488 | def system(self,cmd): | |
486 | """Stateful interface to system(), with the same keyword parameters.""" |
|
489 | """Stateful interface to system(), with the same keyword parameters.""" | |
487 |
|
490 | |||
488 | system(cmd,self.verbose,self.debug,self.header) |
|
491 | system(cmd,self.verbose,self.debug,self.header) | |
489 |
|
492 | |||
490 | def shell(self,cmd): |
|
493 | def shell(self,cmd): | |
491 | """Stateful interface to shell(), with the same keyword parameters.""" |
|
494 | """Stateful interface to shell(), with the same keyword parameters.""" | |
492 |
|
495 | |||
493 | shell(cmd,self.verbose,self.debug,self.header) |
|
496 | shell(cmd,self.verbose,self.debug,self.header) | |
494 |
|
497 | |||
495 | xsys = system # alias |
|
498 | xsys = system # alias | |
496 |
|
499 | |||
497 | def getoutput(self,cmd): |
|
500 | def getoutput(self,cmd): | |
498 | """Stateful interface to getoutput().""" |
|
501 | """Stateful interface to getoutput().""" | |
499 |
|
502 | |||
500 | return getoutput(cmd,self.verbose,self.debug,self.header,self.split) |
|
503 | return getoutput(cmd,self.verbose,self.debug,self.header,self.split) | |
501 |
|
504 | |||
502 | def getoutputerror(self,cmd): |
|
505 | def getoutputerror(self,cmd): | |
503 | """Stateful interface to getoutputerror().""" |
|
506 | """Stateful interface to getoutputerror().""" | |
504 |
|
507 | |||
505 | return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split) |
|
508 | return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split) | |
506 |
|
509 | |||
507 | bq = getoutput # alias |
|
510 | bq = getoutput # alias | |
508 |
|
511 | |||
509 | #----------------------------------------------------------------------------- |
|
512 | #----------------------------------------------------------------------------- | |
510 | def mutex_opts(dict,ex_op): |
|
513 | def mutex_opts(dict,ex_op): | |
511 | """Check for presence of mutually exclusive keys in a dict. |
|
514 | """Check for presence of mutually exclusive keys in a dict. | |
512 |
|
515 | |||
513 | Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]""" |
|
516 | Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]""" | |
514 | for op1,op2 in ex_op: |
|
517 | for op1,op2 in ex_op: | |
515 | if op1 in dict and op2 in dict: |
|
518 | if op1 in dict and op2 in dict: | |
516 | raise ValueError,'\n*** ERROR in Arguments *** '\ |
|
519 | raise ValueError,'\n*** ERROR in Arguments *** '\ | |
517 | 'Options '+op1+' and '+op2+' are mutually exclusive.' |
|
520 | 'Options '+op1+' and '+op2+' are mutually exclusive.' | |
518 |
|
521 | |||
519 | #----------------------------------------------------------------------------- |
|
522 | #----------------------------------------------------------------------------- | |
520 | def get_py_filename(name): |
|
523 | def get_py_filename(name): | |
521 | """Return a valid python filename in the current directory. |
|
524 | """Return a valid python filename in the current directory. | |
522 |
|
525 | |||
523 | If the given name is not a file, it adds '.py' and searches again. |
|
526 | If the given name is not a file, it adds '.py' and searches again. | |
524 | Raises IOError with an informative message if the file isn't found.""" |
|
527 | Raises IOError with an informative message if the file isn't found.""" | |
525 |
|
528 | |||
526 | name = os.path.expanduser(name) |
|
529 | name = os.path.expanduser(name) | |
527 | if not os.path.isfile(name) and not name.endswith('.py'): |
|
530 | if not os.path.isfile(name) and not name.endswith('.py'): | |
528 | name += '.py' |
|
531 | name += '.py' | |
529 | if os.path.isfile(name): |
|
532 | if os.path.isfile(name): | |
530 | return name |
|
533 | return name | |
531 | else: |
|
534 | else: | |
532 | raise IOError,'File `%s` not found.' % name |
|
535 | raise IOError,'File `%s` not found.' % name | |
533 |
|
536 | |||
534 | #----------------------------------------------------------------------------- |
|
537 | #----------------------------------------------------------------------------- | |
535 | def filefind(fname,alt_dirs = None): |
|
538 | def filefind(fname,alt_dirs = None): | |
536 | """Return the given filename either in the current directory, if it |
|
539 | """Return the given filename either in the current directory, if it | |
537 | exists, or in a specified list of directories. |
|
540 | exists, or in a specified list of directories. | |
538 |
|
541 | |||
539 | ~ expansion is done on all file and directory names. |
|
542 | ~ expansion is done on all file and directory names. | |
540 |
|
543 | |||
541 | Upon an unsuccessful search, raise an IOError exception.""" |
|
544 | Upon an unsuccessful search, raise an IOError exception.""" | |
542 |
|
545 | |||
543 | if alt_dirs is None: |
|
546 | if alt_dirs is None: | |
544 | try: |
|
547 | try: | |
545 | alt_dirs = get_home_dir() |
|
548 | alt_dirs = get_home_dir() | |
546 | except HomeDirError: |
|
549 | except HomeDirError: | |
547 | alt_dirs = os.getcwd() |
|
550 | alt_dirs = os.getcwd() | |
548 | search = [fname] + list_strings(alt_dirs) |
|
551 | search = [fname] + list_strings(alt_dirs) | |
549 | search = map(os.path.expanduser,search) |
|
552 | search = map(os.path.expanduser,search) | |
550 | #print 'search list for',fname,'list:',search # dbg |
|
553 | #print 'search list for',fname,'list:',search # dbg | |
551 | fname = search[0] |
|
554 | fname = search[0] | |
552 | if os.path.isfile(fname): |
|
555 | if os.path.isfile(fname): | |
553 | return fname |
|
556 | return fname | |
554 | for direc in search[1:]: |
|
557 | for direc in search[1:]: | |
555 | testname = os.path.join(direc,fname) |
|
558 | testname = os.path.join(direc,fname) | |
556 | #print 'testname',testname # dbg |
|
559 | #print 'testname',testname # dbg | |
557 | if os.path.isfile(testname): |
|
560 | if os.path.isfile(testname): | |
558 | return testname |
|
561 | return testname | |
559 | raise IOError,'File' + `fname` + \ |
|
562 | raise IOError,'File' + `fname` + \ | |
560 | ' not found in current or supplied directories:' + `alt_dirs` |
|
563 | ' not found in current or supplied directories:' + `alt_dirs` | |
561 |
|
564 | |||
562 | #---------------------------------------------------------------------------- |
|
565 | #---------------------------------------------------------------------------- | |
563 | def file_read(filename): |
|
566 | def file_read(filename): | |
564 | """Read a file and close it. Returns the file source.""" |
|
567 | """Read a file and close it. Returns the file source.""" | |
565 | fobj = open(filename,'r'); |
|
568 | fobj = open(filename,'r'); | |
566 | source = fobj.read(); |
|
569 | source = fobj.read(); | |
567 | fobj.close() |
|
570 | fobj.close() | |
568 | return source |
|
571 | return source | |
569 |
|
572 | |||
570 | def file_readlines(filename): |
|
573 | def file_readlines(filename): | |
571 | """Read a file and close it. Returns the file source using readlines().""" |
|
574 | """Read a file and close it. Returns the file source using readlines().""" | |
572 | fobj = open(filename,'r'); |
|
575 | fobj = open(filename,'r'); | |
573 | lines = fobj.readlines(); |
|
576 | lines = fobj.readlines(); | |
574 | fobj.close() |
|
577 | fobj.close() | |
575 | return lines |
|
578 | return lines | |
576 |
|
579 | |||
577 | #---------------------------------------------------------------------------- |
|
580 | #---------------------------------------------------------------------------- | |
578 | def target_outdated(target,deps): |
|
581 | def target_outdated(target,deps): | |
579 | """Determine whether a target is out of date. |
|
582 | """Determine whether a target is out of date. | |
580 |
|
583 | |||
581 | target_outdated(target,deps) -> 1/0 |
|
584 | target_outdated(target,deps) -> 1/0 | |
582 |
|
585 | |||
583 | deps: list of filenames which MUST exist. |
|
586 | deps: list of filenames which MUST exist. | |
584 | target: single filename which may or may not exist. |
|
587 | target: single filename which may or may not exist. | |
585 |
|
588 | |||
586 | If target doesn't exist or is older than any file listed in deps, return |
|
589 | If target doesn't exist or is older than any file listed in deps, return | |
587 | true, otherwise return false. |
|
590 | true, otherwise return false. | |
588 | """ |
|
591 | """ | |
589 | try: |
|
592 | try: | |
590 | target_time = os.path.getmtime(target) |
|
593 | target_time = os.path.getmtime(target) | |
591 | except os.error: |
|
594 | except os.error: | |
592 | return 1 |
|
595 | return 1 | |
593 | for dep in deps: |
|
596 | for dep in deps: | |
594 | dep_time = os.path.getmtime(dep) |
|
597 | dep_time = os.path.getmtime(dep) | |
595 | if dep_time > target_time: |
|
598 | if dep_time > target_time: | |
596 | #print "For target",target,"Dep failed:",dep # dbg |
|
599 | #print "For target",target,"Dep failed:",dep # dbg | |
597 | #print "times (dep,tar):",dep_time,target_time # dbg |
|
600 | #print "times (dep,tar):",dep_time,target_time # dbg | |
598 | return 1 |
|
601 | return 1 | |
599 | return 0 |
|
602 | return 0 | |
600 |
|
603 | |||
601 | #----------------------------------------------------------------------------- |
|
604 | #----------------------------------------------------------------------------- | |
602 | def target_update(target,deps,cmd): |
|
605 | def target_update(target,deps,cmd): | |
603 | """Update a target with a given command given a list of dependencies. |
|
606 | """Update a target with a given command given a list of dependencies. | |
604 |
|
607 | |||
605 | target_update(target,deps,cmd) -> runs cmd if target is outdated. |
|
608 | target_update(target,deps,cmd) -> runs cmd if target is outdated. | |
606 |
|
609 | |||
607 | This is just a wrapper around target_outdated() which calls the given |
|
610 | This is just a wrapper around target_outdated() which calls the given | |
608 | command if target is outdated.""" |
|
611 | command if target is outdated.""" | |
609 |
|
612 | |||
610 | if target_outdated(target,deps): |
|
613 | if target_outdated(target,deps): | |
611 | xsys(cmd) |
|
614 | xsys(cmd) | |
612 |
|
615 | |||
613 | #---------------------------------------------------------------------------- |
|
616 | #---------------------------------------------------------------------------- | |
614 | def unquote_ends(istr): |
|
617 | def unquote_ends(istr): | |
615 | """Remove a single pair of quotes from the endpoints of a string.""" |
|
618 | """Remove a single pair of quotes from the endpoints of a string.""" | |
616 |
|
619 | |||
617 | if not istr: |
|
620 | if not istr: | |
618 | return istr |
|
621 | return istr | |
619 | if (istr[0]=="'" and istr[-1]=="'") or \ |
|
622 | if (istr[0]=="'" and istr[-1]=="'") or \ | |
620 | (istr[0]=='"' and istr[-1]=='"'): |
|
623 | (istr[0]=='"' and istr[-1]=='"'): | |
621 | return istr[1:-1] |
|
624 | return istr[1:-1] | |
622 | else: |
|
625 | else: | |
623 | return istr |
|
626 | return istr | |
624 |
|
627 | |||
625 | #---------------------------------------------------------------------------- |
|
628 | #---------------------------------------------------------------------------- | |
626 | def process_cmdline(argv,names=[],defaults={},usage=''): |
|
629 | def process_cmdline(argv,names=[],defaults={},usage=''): | |
627 | """ Process command-line options and arguments. |
|
630 | """ Process command-line options and arguments. | |
628 |
|
631 | |||
629 | Arguments: |
|
632 | Arguments: | |
630 |
|
633 | |||
631 | - argv: list of arguments, typically sys.argv. |
|
634 | - argv: list of arguments, typically sys.argv. | |
632 |
|
635 | |||
633 | - names: list of option names. See DPyGetOpt docs for details on options |
|
636 | - names: list of option names. See DPyGetOpt docs for details on options | |
634 | syntax. |
|
637 | syntax. | |
635 |
|
638 | |||
636 | - defaults: dict of default values. |
|
639 | - defaults: dict of default values. | |
637 |
|
640 | |||
638 | - usage: optional usage notice to print if a wrong argument is passed. |
|
641 | - usage: optional usage notice to print if a wrong argument is passed. | |
639 |
|
642 | |||
640 | Return a dict of options and a list of free arguments.""" |
|
643 | Return a dict of options and a list of free arguments.""" | |
641 |
|
644 | |||
642 | getopt = DPyGetOpt.DPyGetOpt() |
|
645 | getopt = DPyGetOpt.DPyGetOpt() | |
643 | getopt.setIgnoreCase(0) |
|
646 | getopt.setIgnoreCase(0) | |
644 | getopt.parseConfiguration(names) |
|
647 | getopt.parseConfiguration(names) | |
645 |
|
648 | |||
646 | try: |
|
649 | try: | |
647 | getopt.processArguments(argv) |
|
650 | getopt.processArguments(argv) | |
648 | except DPyGetOpt.ArgumentError, exc: |
|
651 | except DPyGetOpt.ArgumentError, exc: | |
649 | print usage |
|
652 | print usage | |
650 | warn('"%s"' % exc,level=4) |
|
653 | warn('"%s"' % exc,level=4) | |
651 |
|
654 | |||
652 | defaults.update(getopt.optionValues) |
|
655 | defaults.update(getopt.optionValues) | |
653 | args = getopt.freeValues |
|
656 | args = getopt.freeValues | |
654 |
|
657 | |||
655 | return defaults,args |
|
658 | return defaults,args | |
656 |
|
659 | |||
657 | #---------------------------------------------------------------------------- |
|
660 | #---------------------------------------------------------------------------- | |
658 | def optstr2types(ostr): |
|
661 | def optstr2types(ostr): | |
659 | """Convert a string of option names to a dict of type mappings. |
|
662 | """Convert a string of option names to a dict of type mappings. | |
660 |
|
663 | |||
661 | optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'} |
|
664 | optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'} | |
662 |
|
665 | |||
663 | This is used to get the types of all the options in a string formatted |
|
666 | This is used to get the types of all the options in a string formatted | |
664 | with the conventions of DPyGetOpt. The 'type' None is used for options |
|
667 | with the conventions of DPyGetOpt. The 'type' None is used for options | |
665 | which are strings (they need no further conversion). This function's main |
|
668 | which are strings (they need no further conversion). This function's main | |
666 | use is to get a typemap for use with read_dict(). |
|
669 | use is to get a typemap for use with read_dict(). | |
667 | """ |
|
670 | """ | |
668 |
|
671 | |||
669 | typeconv = {None:'',int:'',float:''} |
|
672 | typeconv = {None:'',int:'',float:''} | |
670 | typemap = {'s':None,'i':int,'f':float} |
|
673 | typemap = {'s':None,'i':int,'f':float} | |
671 | opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)') |
|
674 | opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)') | |
672 |
|
675 | |||
673 | for w in ostr.split(): |
|
676 | for w in ostr.split(): | |
674 | oname,alias,otype = opt_re.match(w).groups() |
|
677 | oname,alias,otype = opt_re.match(w).groups() | |
675 | if otype == '' or alias == '!': # simple switches are integers too |
|
678 | if otype == '' or alias == '!': # simple switches are integers too | |
676 | otype = 'i' |
|
679 | otype = 'i' | |
677 | typeconv[typemap[otype]] += oname + ' ' |
|
680 | typeconv[typemap[otype]] += oname + ' ' | |
678 | return typeconv |
|
681 | return typeconv | |
679 |
|
682 | |||
680 | #---------------------------------------------------------------------------- |
|
683 | #---------------------------------------------------------------------------- | |
681 | def read_dict(filename,type_conv=None,**opt): |
|
684 | def read_dict(filename,type_conv=None,**opt): | |
682 |
|
685 | |||
683 | """Read a dictionary of key=value pairs from an input file, optionally |
|
686 | """Read a dictionary of key=value pairs from an input file, optionally | |
684 | performing conversions on the resulting values. |
|
687 | performing conversions on the resulting values. | |
685 |
|
688 | |||
686 | read_dict(filename,type_conv,**opt) -> dict |
|
689 | read_dict(filename,type_conv,**opt) -> dict | |
687 |
|
690 | |||
688 | Only one value per line is accepted, the format should be |
|
691 | Only one value per line is accepted, the format should be | |
689 | # optional comments are ignored |
|
692 | # optional comments are ignored | |
690 | key value\n |
|
693 | key value\n | |
691 |
|
694 | |||
692 | Args: |
|
695 | Args: | |
693 |
|
696 | |||
694 | - type_conv: A dictionary specifying which keys need to be converted to |
|
697 | - type_conv: A dictionary specifying which keys need to be converted to | |
695 | which types. By default all keys are read as strings. This dictionary |
|
698 | which types. By default all keys are read as strings. This dictionary | |
696 | should have as its keys valid conversion functions for strings |
|
699 | should have as its keys valid conversion functions for strings | |
697 | (int,long,float,complex, or your own). The value for each key |
|
700 | (int,long,float,complex, or your own). The value for each key | |
698 | (converter) should be a whitespace separated string containing the names |
|
701 | (converter) should be a whitespace separated string containing the names | |
699 | of all the entries in the file to be converted using that function. For |
|
702 | of all the entries in the file to be converted using that function. For | |
700 | keys to be left alone, use None as the conversion function (only needed |
|
703 | keys to be left alone, use None as the conversion function (only needed | |
701 | with purge=1, see below). |
|
704 | with purge=1, see below). | |
702 |
|
705 | |||
703 | - opt: dictionary with extra options as below (default in parens) |
|
706 | - opt: dictionary with extra options as below (default in parens) | |
704 |
|
707 | |||
705 | purge(0): if set to 1, all keys *not* listed in type_conv are purged out |
|
708 | purge(0): if set to 1, all keys *not* listed in type_conv are purged out | |
706 | of the dictionary to be returned. If purge is going to be used, the |
|
709 | of the dictionary to be returned. If purge is going to be used, the | |
707 | set of keys to be left as strings also has to be explicitly specified |
|
710 | set of keys to be left as strings also has to be explicitly specified | |
708 | using the (non-existent) conversion function None. |
|
711 | using the (non-existent) conversion function None. | |
709 |
|
712 | |||
710 | fs(None): field separator. This is the key/value separator to be used |
|
713 | fs(None): field separator. This is the key/value separator to be used | |
711 | when parsing the file. The None default means any whitespace [behavior |
|
714 | when parsing the file. The None default means any whitespace [behavior | |
712 | of string.split()]. |
|
715 | of string.split()]. | |
713 |
|
716 | |||
714 | strip(0): if 1, strip string values of leading/trailinig whitespace. |
|
717 | strip(0): if 1, strip string values of leading/trailinig whitespace. | |
715 |
|
718 | |||
716 | warn(1): warning level if requested keys are not found in file. |
|
719 | warn(1): warning level if requested keys are not found in file. | |
717 | - 0: silently ignore. |
|
720 | - 0: silently ignore. | |
718 | - 1: inform but proceed. |
|
721 | - 1: inform but proceed. | |
719 | - 2: raise KeyError exception. |
|
722 | - 2: raise KeyError exception. | |
720 |
|
723 | |||
721 | no_empty(0): if 1, remove keys with whitespace strings as a value. |
|
724 | no_empty(0): if 1, remove keys with whitespace strings as a value. | |
722 |
|
725 | |||
723 | unique([]): list of keys (or space separated string) which can't be |
|
726 | unique([]): list of keys (or space separated string) which can't be | |
724 | repeated. If one such key is found in the file, each new instance |
|
727 | repeated. If one such key is found in the file, each new instance | |
725 | overwrites the previous one. For keys not listed here, the behavior is |
|
728 | overwrites the previous one. For keys not listed here, the behavior is | |
726 | to make a list of all appearances. |
|
729 | to make a list of all appearances. | |
727 |
|
730 | |||
728 | Example: |
|
731 | Example: | |
729 | If the input file test.ini has: |
|
732 | If the input file test.ini has: | |
730 | i 3 |
|
733 | i 3 | |
731 | x 4.5 |
|
734 | x 4.5 | |
732 | y 5.5 |
|
735 | y 5.5 | |
733 | s hi ho |
|
736 | s hi ho | |
734 | Then: |
|
737 | Then: | |
735 |
|
738 | |||
736 | >>> type_conv={int:'i',float:'x',None:'s'} |
|
739 | >>> type_conv={int:'i',float:'x',None:'s'} | |
737 | >>> read_dict('test.ini') |
|
740 | >>> read_dict('test.ini') | |
738 | {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'} |
|
741 | {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'} | |
739 | >>> read_dict('test.ini',type_conv) |
|
742 | >>> read_dict('test.ini',type_conv) | |
740 | {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'} |
|
743 | {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'} | |
741 | >>> read_dict('test.ini',type_conv,purge=1) |
|
744 | >>> read_dict('test.ini',type_conv,purge=1) | |
742 | {'i': 3, 's': 'hi ho', 'x': 4.5} |
|
745 | {'i': 3, 's': 'hi ho', 'x': 4.5} | |
743 | """ |
|
746 | """ | |
744 |
|
747 | |||
745 | # starting config |
|
748 | # starting config | |
746 | opt.setdefault('purge',0) |
|
749 | opt.setdefault('purge',0) | |
747 | opt.setdefault('fs',None) # field sep defaults to any whitespace |
|
750 | opt.setdefault('fs',None) # field sep defaults to any whitespace | |
748 | opt.setdefault('strip',0) |
|
751 | opt.setdefault('strip',0) | |
749 | opt.setdefault('warn',1) |
|
752 | opt.setdefault('warn',1) | |
750 | opt.setdefault('no_empty',0) |
|
753 | opt.setdefault('no_empty',0) | |
751 | opt.setdefault('unique','') |
|
754 | opt.setdefault('unique','') | |
752 | if type(opt['unique']) in StringTypes: |
|
755 | if type(opt['unique']) in StringTypes: | |
753 | unique_keys = qw(opt['unique']) |
|
756 | unique_keys = qw(opt['unique']) | |
754 | elif type(opt['unique']) in (types.TupleType,types.ListType): |
|
757 | elif type(opt['unique']) in (types.TupleType,types.ListType): | |
755 | unique_keys = opt['unique'] |
|
758 | unique_keys = opt['unique'] | |
756 | else: |
|
759 | else: | |
757 | raise ValueError, 'Unique keys must be given as a string, List or Tuple' |
|
760 | raise ValueError, 'Unique keys must be given as a string, List or Tuple' | |
758 |
|
761 | |||
759 | dict = {} |
|
762 | dict = {} | |
760 | # first read in table of values as strings |
|
763 | # first read in table of values as strings | |
761 | file = open(filename,'r') |
|
764 | file = open(filename,'r') | |
762 | for line in file.readlines(): |
|
765 | for line in file.readlines(): | |
763 | line = line.strip() |
|
766 | line = line.strip() | |
764 | if len(line) and line[0]=='#': continue |
|
767 | if len(line) and line[0]=='#': continue | |
765 | if len(line)>0: |
|
768 | if len(line)>0: | |
766 | lsplit = line.split(opt['fs'],1) |
|
769 | lsplit = line.split(opt['fs'],1) | |
767 | try: |
|
770 | try: | |
768 | key,val = lsplit |
|
771 | key,val = lsplit | |
769 | except ValueError: |
|
772 | except ValueError: | |
770 | key,val = lsplit[0],'' |
|
773 | key,val = lsplit[0],'' | |
771 | key = key.strip() |
|
774 | key = key.strip() | |
772 | if opt['strip']: val = val.strip() |
|
775 | if opt['strip']: val = val.strip() | |
773 | if val == "''" or val == '""': val = '' |
|
776 | if val == "''" or val == '""': val = '' | |
774 | if opt['no_empty'] and (val=='' or val.isspace()): |
|
777 | if opt['no_empty'] and (val=='' or val.isspace()): | |
775 | continue |
|
778 | continue | |
776 | # if a key is found more than once in the file, build a list |
|
779 | # if a key is found more than once in the file, build a list | |
777 | # unless it's in the 'unique' list. In that case, last found in file |
|
780 | # unless it's in the 'unique' list. In that case, last found in file | |
778 | # takes precedence. User beware. |
|
781 | # takes precedence. User beware. | |
779 | try: |
|
782 | try: | |
780 | if dict[key] and key in unique_keys: |
|
783 | if dict[key] and key in unique_keys: | |
781 | dict[key] = val |
|
784 | dict[key] = val | |
782 | elif type(dict[key]) is types.ListType: |
|
785 | elif type(dict[key]) is types.ListType: | |
783 | dict[key].append(val) |
|
786 | dict[key].append(val) | |
784 | else: |
|
787 | else: | |
785 | dict[key] = [dict[key],val] |
|
788 | dict[key] = [dict[key],val] | |
786 | except KeyError: |
|
789 | except KeyError: | |
787 | dict[key] = val |
|
790 | dict[key] = val | |
788 | # purge if requested |
|
791 | # purge if requested | |
789 | if opt['purge']: |
|
792 | if opt['purge']: | |
790 | accepted_keys = qwflat(type_conv.values()) |
|
793 | accepted_keys = qwflat(type_conv.values()) | |
791 | for key in dict.keys(): |
|
794 | for key in dict.keys(): | |
792 | if key in accepted_keys: continue |
|
795 | if key in accepted_keys: continue | |
793 | del(dict[key]) |
|
796 | del(dict[key]) | |
794 | # now convert if requested |
|
797 | # now convert if requested | |
795 | if type_conv==None: return dict |
|
798 | if type_conv==None: return dict | |
796 | conversions = type_conv.keys() |
|
799 | conversions = type_conv.keys() | |
797 | try: conversions.remove(None) |
|
800 | try: conversions.remove(None) | |
798 | except: pass |
|
801 | except: pass | |
799 | for convert in conversions: |
|
802 | for convert in conversions: | |
800 | for val in qw(type_conv[convert]): |
|
803 | for val in qw(type_conv[convert]): | |
801 | try: |
|
804 | try: | |
802 | dict[val] = convert(dict[val]) |
|
805 | dict[val] = convert(dict[val]) | |
803 | except KeyError,e: |
|
806 | except KeyError,e: | |
804 | if opt['warn'] == 0: |
|
807 | if opt['warn'] == 0: | |
805 | pass |
|
808 | pass | |
806 | elif opt['warn'] == 1: |
|
809 | elif opt['warn'] == 1: | |
807 | print >>sys.stderr, 'Warning: key',val,\ |
|
810 | print >>sys.stderr, 'Warning: key',val,\ | |
808 | 'not found in file',filename |
|
811 | 'not found in file',filename | |
809 | elif opt['warn'] == 2: |
|
812 | elif opt['warn'] == 2: | |
810 | raise KeyError,e |
|
813 | raise KeyError,e | |
811 | else: |
|
814 | else: | |
812 | raise ValueError,'Warning level must be 0,1 or 2' |
|
815 | raise ValueError,'Warning level must be 0,1 or 2' | |
813 |
|
816 | |||
814 | return dict |
|
817 | return dict | |
815 |
|
818 | |||
816 | #---------------------------------------------------------------------------- |
|
819 | #---------------------------------------------------------------------------- | |
817 | def flag_calls(func): |
|
820 | def flag_calls(func): | |
818 | """Wrap a function to detect and flag when it gets called. |
|
821 | """Wrap a function to detect and flag when it gets called. | |
819 |
|
822 | |||
820 | This is a decorator which takes a function and wraps it in a function with |
|
823 | This is a decorator which takes a function and wraps it in a function with | |
821 | a 'called' attribute. wrapper.called is initialized to False. |
|
824 | a 'called' attribute. wrapper.called is initialized to False. | |
822 |
|
825 | |||
823 | The wrapper.called attribute is set to False right before each call to the |
|
826 | The wrapper.called attribute is set to False right before each call to the | |
824 | wrapped function, so if the call fails it remains False. After the call |
|
827 | wrapped function, so if the call fails it remains False. After the call | |
825 | completes, wrapper.called is set to True and the output is returned. |
|
828 | completes, wrapper.called is set to True and the output is returned. | |
826 |
|
829 | |||
827 | Testing for truth in wrapper.called allows you to determine if a call to |
|
830 | Testing for truth in wrapper.called allows you to determine if a call to | |
828 | func() was attempted and succeeded.""" |
|
831 | func() was attempted and succeeded.""" | |
829 |
|
832 | |||
830 | def wrapper(*args,**kw): |
|
833 | def wrapper(*args,**kw): | |
831 | wrapper.called = False |
|
834 | wrapper.called = False | |
832 | out = func(*args,**kw) |
|
835 | out = func(*args,**kw) | |
833 | wrapper.called = True |
|
836 | wrapper.called = True | |
834 | return out |
|
837 | return out | |
835 |
|
838 | |||
836 | wrapper.called = False |
|
839 | wrapper.called = False | |
837 | wrapper.__doc__ = func.__doc__ |
|
840 | wrapper.__doc__ = func.__doc__ | |
838 | return wrapper |
|
841 | return wrapper | |
839 |
|
842 | |||
840 | #---------------------------------------------------------------------------- |
|
843 | #---------------------------------------------------------------------------- | |
841 | def dhook_wrap(func,*a,**k): |
|
844 | def dhook_wrap(func,*a,**k): | |
842 | """Wrap a function call in a sys.displayhook controller. |
|
845 | """Wrap a function call in a sys.displayhook controller. | |
843 |
|
846 | |||
844 | Returns a wrapper around func which calls func, with all its arguments and |
|
847 | Returns a wrapper around func which calls func, with all its arguments and | |
845 | keywords unmodified, using the default sys.displayhook. Since IPython |
|
848 | keywords unmodified, using the default sys.displayhook. Since IPython | |
846 | modifies sys.displayhook, it breaks the behavior of certain systems that |
|
849 | modifies sys.displayhook, it breaks the behavior of certain systems that | |
847 | rely on the default behavior, notably doctest. |
|
850 | rely on the default behavior, notably doctest. | |
848 | """ |
|
851 | """ | |
849 |
|
852 | |||
850 | def f(*a,**k): |
|
853 | def f(*a,**k): | |
851 |
|
854 | |||
852 | dhook_s = sys.displayhook |
|
855 | dhook_s = sys.displayhook | |
853 | sys.displayhook = sys.__displayhook__ |
|
856 | sys.displayhook = sys.__displayhook__ | |
854 | try: |
|
857 | try: | |
855 | out = func(*a,**k) |
|
858 | out = func(*a,**k) | |
856 | finally: |
|
859 | finally: | |
857 | sys.displayhook = dhook_s |
|
860 | sys.displayhook = dhook_s | |
858 |
|
861 | |||
859 | return out |
|
862 | return out | |
860 |
|
863 | |||
861 | f.__doc__ = func.__doc__ |
|
864 | f.__doc__ = func.__doc__ | |
862 | return f |
|
865 | return f | |
863 |
|
866 | |||
864 | #---------------------------------------------------------------------------- |
|
867 | #---------------------------------------------------------------------------- | |
865 | def doctest_reload(): |
|
868 | def doctest_reload(): | |
866 | """Properly reload doctest to reuse it interactively. |
|
869 | """Properly reload doctest to reuse it interactively. | |
867 |
|
870 | |||
868 | This routine: |
|
871 | This routine: | |
869 |
|
872 | |||
870 | - reloads doctest |
|
873 | - reloads doctest | |
871 |
|
874 | |||
872 | - resets its global 'master' attribute to None, so that multiple uses of |
|
875 | - resets its global 'master' attribute to None, so that multiple uses of | |
873 | the module interactively don't produce cumulative reports. |
|
876 | the module interactively don't produce cumulative reports. | |
874 |
|
877 | |||
875 | - Monkeypatches its core test runner method to protect it from IPython's |
|
878 | - Monkeypatches its core test runner method to protect it from IPython's | |
876 | modified displayhook. Doctest expects the default displayhook behavior |
|
879 | modified displayhook. Doctest expects the default displayhook behavior | |
877 | deep down, so our modification breaks it completely. For this reason, a |
|
880 | deep down, so our modification breaks it completely. For this reason, a | |
878 | hard monkeypatch seems like a reasonable solution rather than asking |
|
881 | hard monkeypatch seems like a reasonable solution rather than asking | |
879 | users to manually use a different doctest runner when under IPython.""" |
|
882 | users to manually use a different doctest runner when under IPython.""" | |
880 |
|
883 | |||
881 | import doctest |
|
884 | import doctest | |
882 | reload(doctest) |
|
885 | reload(doctest) | |
883 | doctest.master=None |
|
886 | doctest.master=None | |
884 |
|
887 | |||
885 | try: |
|
888 | try: | |
886 | doctest.DocTestRunner |
|
889 | doctest.DocTestRunner | |
887 | except AttributeError: |
|
890 | except AttributeError: | |
888 | # This is only for python 2.3 compatibility, remove once we move to |
|
891 | # This is only for python 2.3 compatibility, remove once we move to | |
889 | # 2.4 only. |
|
892 | # 2.4 only. | |
890 | pass |
|
893 | pass | |
891 | else: |
|
894 | else: | |
892 | doctest.DocTestRunner.run = dhook_wrap(doctest.DocTestRunner.run) |
|
895 | doctest.DocTestRunner.run = dhook_wrap(doctest.DocTestRunner.run) | |
893 |
|
896 | |||
894 | #---------------------------------------------------------------------------- |
|
897 | #---------------------------------------------------------------------------- | |
895 | class HomeDirError(Error): |
|
898 | class HomeDirError(Error): | |
896 | pass |
|
899 | pass | |
897 |
|
900 | |||
898 | def get_home_dir(): |
|
901 | def get_home_dir(): | |
899 | """Return the closest possible equivalent to a 'home' directory. |
|
902 | """Return the closest possible equivalent to a 'home' directory. | |
900 |
|
903 | |||
901 | We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH. |
|
904 | We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH. | |
902 |
|
905 | |||
903 | Currently only Posix and NT are implemented, a HomeDirError exception is |
|
906 | Currently only Posix and NT are implemented, a HomeDirError exception is | |
904 | raised for all other OSes. """ |
|
907 | raised for all other OSes. """ | |
905 |
|
908 | |||
906 | isdir = os.path.isdir |
|
909 | isdir = os.path.isdir | |
907 | env = os.environ |
|
910 | env = os.environ | |
908 |
|
911 | |||
909 | # first, check py2exe distribution root directory for _ipython. |
|
912 | # first, check py2exe distribution root directory for _ipython. | |
910 | # This overrides all. Normally does not exist. |
|
913 | # This overrides all. Normally does not exist. | |
911 |
|
914 | |||
912 | if '\\library.zip\\' in IPython.__file__.lower(): |
|
915 | if '\\library.zip\\' in IPython.__file__.lower(): | |
913 | root, rest = IPython.__file__.lower().split('library.zip') |
|
916 | root, rest = IPython.__file__.lower().split('library.zip') | |
914 | if isdir(root + '_ipython'): |
|
917 | if isdir(root + '_ipython'): | |
915 | os.environ["IPYKITROOT"] = root.rstrip('\\') |
|
918 | os.environ["IPYKITROOT"] = root.rstrip('\\') | |
916 | return root |
|
919 | return root | |
917 |
|
920 | |||
918 | try: |
|
921 | try: | |
919 | homedir = env['HOME'] |
|
922 | homedir = env['HOME'] | |
920 | if not isdir(homedir): |
|
923 | if not isdir(homedir): | |
921 | # in case a user stuck some string which does NOT resolve to a |
|
924 | # in case a user stuck some string which does NOT resolve to a | |
922 | # valid path, it's as good as if we hadn't foud it |
|
925 | # valid path, it's as good as if we hadn't foud it | |
923 | raise KeyError |
|
926 | raise KeyError | |
924 | return homedir |
|
927 | return homedir | |
925 | except KeyError: |
|
928 | except KeyError: | |
926 | if os.name == 'posix': |
|
929 | if os.name == 'posix': | |
927 | raise HomeDirError,'undefined $HOME, IPython can not proceed.' |
|
930 | raise HomeDirError,'undefined $HOME, IPython can not proceed.' | |
928 | elif os.name == 'nt': |
|
931 | elif os.name == 'nt': | |
929 | # For some strange reason, win9x returns 'nt' for os.name. |
|
932 | # For some strange reason, win9x returns 'nt' for os.name. | |
930 | try: |
|
933 | try: | |
931 | homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH']) |
|
934 | homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH']) | |
932 | if not isdir(homedir): |
|
935 | if not isdir(homedir): | |
933 | homedir = os.path.join(env['USERPROFILE']) |
|
936 | homedir = os.path.join(env['USERPROFILE']) | |
934 | if not isdir(homedir): |
|
937 | if not isdir(homedir): | |
935 | raise HomeDirError |
|
938 | raise HomeDirError | |
936 | return homedir |
|
939 | return homedir | |
937 | except: |
|
940 | except: | |
938 | try: |
|
941 | try: | |
939 | # Use the registry to get the 'My Documents' folder. |
|
942 | # Use the registry to get the 'My Documents' folder. | |
940 | import _winreg as wreg |
|
943 | import _winreg as wreg | |
941 | key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, |
|
944 | key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, | |
942 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") |
|
945 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") | |
943 | homedir = wreg.QueryValueEx(key,'Personal')[0] |
|
946 | homedir = wreg.QueryValueEx(key,'Personal')[0] | |
944 | key.Close() |
|
947 | key.Close() | |
945 | if not isdir(homedir): |
|
948 | if not isdir(homedir): | |
946 | e = ('Invalid "Personal" folder registry key ' |
|
949 | e = ('Invalid "Personal" folder registry key ' | |
947 | 'typically "My Documents".\n' |
|
950 | 'typically "My Documents".\n' | |
948 | 'Value: %s\n' |
|
951 | 'Value: %s\n' | |
949 | 'This is not a valid directory on your system.' % |
|
952 | 'This is not a valid directory on your system.' % | |
950 | homedir) |
|
953 | homedir) | |
951 | raise HomeDirError(e) |
|
954 | raise HomeDirError(e) | |
952 | return homedir |
|
955 | return homedir | |
953 | except HomeDirError: |
|
956 | except HomeDirError: | |
954 | raise |
|
957 | raise | |
955 | except: |
|
958 | except: | |
956 | return 'C:\\' |
|
959 | return 'C:\\' | |
957 | elif os.name == 'dos': |
|
960 | elif os.name == 'dos': | |
958 | # Desperate, may do absurd things in classic MacOS. May work under DOS. |
|
961 | # Desperate, may do absurd things in classic MacOS. May work under DOS. | |
959 | return 'C:\\' |
|
962 | return 'C:\\' | |
960 | else: |
|
963 | else: | |
961 | raise HomeDirError,'support for your operating system not implemented.' |
|
964 | raise HomeDirError,'support for your operating system not implemented.' | |
962 |
|
965 | |||
963 | #**************************************************************************** |
|
966 | #**************************************************************************** | |
964 | # strings and text |
|
967 | # strings and text | |
965 |
|
968 | |||
966 | class LSString(str): |
|
969 | class LSString(str): | |
967 | """String derivative with a special access attributes. |
|
970 | """String derivative with a special access attributes. | |
968 |
|
971 | |||
969 | These are normal strings, but with the special attributes: |
|
972 | These are normal strings, but with the special attributes: | |
970 |
|
973 | |||
971 | .l (or .list) : value as list (split on newlines). |
|
974 | .l (or .list) : value as list (split on newlines). | |
972 | .n (or .nlstr): original value (the string itself). |
|
975 | .n (or .nlstr): original value (the string itself). | |
973 | .s (or .spstr): value as whitespace-separated string. |
|
976 | .s (or .spstr): value as whitespace-separated string. | |
974 | .p (or .paths): list of path objects |
|
977 | .p (or .paths): list of path objects | |
975 |
|
978 | |||
976 | Any values which require transformations are computed only once and |
|
979 | Any values which require transformations are computed only once and | |
977 | cached. |
|
980 | cached. | |
978 |
|
981 | |||
979 | Such strings are very useful to efficiently interact with the shell, which |
|
982 | Such strings are very useful to efficiently interact with the shell, which | |
980 | typically only understands whitespace-separated options for commands.""" |
|
983 | typically only understands whitespace-separated options for commands.""" | |
981 |
|
984 | |||
982 | def get_list(self): |
|
985 | def get_list(self): | |
983 | try: |
|
986 | try: | |
984 | return self.__list |
|
987 | return self.__list | |
985 | except AttributeError: |
|
988 | except AttributeError: | |
986 | self.__list = self.split('\n') |
|
989 | self.__list = self.split('\n') | |
987 | return self.__list |
|
990 | return self.__list | |
988 |
|
991 | |||
989 | l = list = property(get_list) |
|
992 | l = list = property(get_list) | |
990 |
|
993 | |||
991 | def get_spstr(self): |
|
994 | def get_spstr(self): | |
992 | try: |
|
995 | try: | |
993 | return self.__spstr |
|
996 | return self.__spstr | |
994 | except AttributeError: |
|
997 | except AttributeError: | |
995 | self.__spstr = self.replace('\n',' ') |
|
998 | self.__spstr = self.replace('\n',' ') | |
996 | return self.__spstr |
|
999 | return self.__spstr | |
997 |
|
1000 | |||
998 | s = spstr = property(get_spstr) |
|
1001 | s = spstr = property(get_spstr) | |
999 |
|
1002 | |||
1000 | def get_nlstr(self): |
|
1003 | def get_nlstr(self): | |
1001 | return self |
|
1004 | return self | |
1002 |
|
1005 | |||
1003 | n = nlstr = property(get_nlstr) |
|
1006 | n = nlstr = property(get_nlstr) | |
1004 |
|
1007 | |||
1005 | def get_paths(self): |
|
1008 | def get_paths(self): | |
1006 | try: |
|
1009 | try: | |
1007 | return self.__paths |
|
1010 | return self.__paths | |
1008 | except AttributeError: |
|
1011 | except AttributeError: | |
1009 | self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)] |
|
1012 | self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)] | |
1010 | return self.__paths |
|
1013 | return self.__paths | |
1011 |
|
1014 | |||
1012 | p = paths = property(get_paths) |
|
1015 | p = paths = property(get_paths) | |
1013 |
|
1016 | |||
1014 | def print_lsstring(arg): |
|
1017 | def print_lsstring(arg): | |
1015 | """ Prettier (non-repr-like) and more informative printer for LSString """ |
|
1018 | """ Prettier (non-repr-like) and more informative printer for LSString """ | |
1016 | print "LSString (.p, .n, .l, .s available). Value:" |
|
1019 | print "LSString (.p, .n, .l, .s available). Value:" | |
1017 | print arg |
|
1020 | print arg | |
1018 |
|
1021 | |||
1019 | print_lsstring = result_display.when_type(LSString)(print_lsstring) |
|
1022 | print_lsstring = result_display.when_type(LSString)(print_lsstring) | |
1020 |
|
1023 | |||
1021 | #---------------------------------------------------------------------------- |
|
1024 | #---------------------------------------------------------------------------- | |
1022 | class SList(list): |
|
1025 | class SList(list): | |
1023 | """List derivative with a special access attributes. |
|
1026 | """List derivative with a special access attributes. | |
1024 |
|
1027 | |||
1025 | These are normal lists, but with the special attributes: |
|
1028 | These are normal lists, but with the special attributes: | |
1026 |
|
1029 | |||
1027 | .l (or .list) : value as list (the list itself). |
|
1030 | .l (or .list) : value as list (the list itself). | |
1028 | .n (or .nlstr): value as a string, joined on newlines. |
|
1031 | .n (or .nlstr): value as a string, joined on newlines. | |
1029 | .s (or .spstr): value as a string, joined on spaces. |
|
1032 | .s (or .spstr): value as a string, joined on spaces. | |
1030 | .p (or .paths): list of path objects |
|
1033 | .p (or .paths): list of path objects | |
1031 |
|
1034 | |||
1032 | Any values which require transformations are computed only once and |
|
1035 | Any values which require transformations are computed only once and | |
1033 | cached.""" |
|
1036 | cached.""" | |
1034 |
|
1037 | |||
1035 | def get_list(self): |
|
1038 | def get_list(self): | |
1036 | return self |
|
1039 | return self | |
1037 |
|
1040 | |||
1038 | l = list = property(get_list) |
|
1041 | l = list = property(get_list) | |
1039 |
|
1042 | |||
1040 | def get_spstr(self): |
|
1043 | def get_spstr(self): | |
1041 | try: |
|
1044 | try: | |
1042 | return self.__spstr |
|
1045 | return self.__spstr | |
1043 | except AttributeError: |
|
1046 | except AttributeError: | |
1044 | self.__spstr = ' '.join(self) |
|
1047 | self.__spstr = ' '.join(self) | |
1045 | return self.__spstr |
|
1048 | return self.__spstr | |
1046 |
|
1049 | |||
1047 | s = spstr = property(get_spstr) |
|
1050 | s = spstr = property(get_spstr) | |
1048 |
|
1051 | |||
1049 | def get_nlstr(self): |
|
1052 | def get_nlstr(self): | |
1050 | try: |
|
1053 | try: | |
1051 | return self.__nlstr |
|
1054 | return self.__nlstr | |
1052 | except AttributeError: |
|
1055 | except AttributeError: | |
1053 | self.__nlstr = '\n'.join(self) |
|
1056 | self.__nlstr = '\n'.join(self) | |
1054 | return self.__nlstr |
|
1057 | return self.__nlstr | |
1055 |
|
1058 | |||
1056 | n = nlstr = property(get_nlstr) |
|
1059 | n = nlstr = property(get_nlstr) | |
1057 |
|
1060 | |||
1058 | def get_paths(self): |
|
1061 | def get_paths(self): | |
1059 | try: |
|
1062 | try: | |
1060 | return self.__paths |
|
1063 | return self.__paths | |
1061 | except AttributeError: |
|
1064 | except AttributeError: | |
1062 | self.__paths = [path(p) for p in self if os.path.exists(p)] |
|
1065 | self.__paths = [path(p) for p in self if os.path.exists(p)] | |
1063 | return self.__paths |
|
1066 | return self.__paths | |
1064 |
|
1067 | |||
1065 | p = paths = property(get_paths) |
|
1068 | p = paths = property(get_paths) | |
1066 |
|
1069 | |||
1067 | def grep(self, pattern, prune = False, field = None): |
|
1070 | def grep(self, pattern, prune = False, field = None): | |
1068 | """ Return all strings matching 'pattern' (a regex or callable) |
|
1071 | """ Return all strings matching 'pattern' (a regex or callable) | |
1069 |
|
1072 | |||
1070 | This is case-insensitive. If prune is true, return all items |
|
1073 | This is case-insensitive. If prune is true, return all items | |
1071 | NOT matching the pattern. |
|
1074 | NOT matching the pattern. | |
1072 |
|
1075 | |||
1073 | If field is specified, the match must occur in the specified |
|
1076 | If field is specified, the match must occur in the specified | |
1074 | whitespace-separated field. |
|
1077 | whitespace-separated field. | |
1075 |
|
1078 | |||
1076 | Examples:: |
|
1079 | Examples:: | |
1077 |
|
1080 | |||
1078 | a.grep( lambda x: x.startswith('C') ) |
|
1081 | a.grep( lambda x: x.startswith('C') ) | |
1079 | a.grep('Cha.*log', prune=1) |
|
1082 | a.grep('Cha.*log', prune=1) | |
1080 | a.grep('chm', field=-1) |
|
1083 | a.grep('chm', field=-1) | |
1081 | """ |
|
1084 | """ | |
1082 |
|
1085 | |||
1083 | def match_target(s): |
|
1086 | def match_target(s): | |
1084 | if field is None: |
|
1087 | if field is None: | |
1085 | return s |
|
1088 | return s | |
1086 | parts = s.split() |
|
1089 | parts = s.split() | |
1087 | try: |
|
1090 | try: | |
1088 | tgt = parts[field] |
|
1091 | tgt = parts[field] | |
1089 | return tgt |
|
1092 | return tgt | |
1090 | except IndexError: |
|
1093 | except IndexError: | |
1091 | return "" |
|
1094 | return "" | |
1092 |
|
1095 | |||
1093 | if isinstance(pattern, basestring): |
|
1096 | if isinstance(pattern, basestring): | |
1094 | pred = lambda x : re.search(pattern, x, re.IGNORECASE) |
|
1097 | pred = lambda x : re.search(pattern, x, re.IGNORECASE) | |
1095 | else: |
|
1098 | else: | |
1096 | pred = pattern |
|
1099 | pred = pattern | |
1097 | if not prune: |
|
1100 | if not prune: | |
1098 | return SList([el for el in self if pred(match_target(el))]) |
|
1101 | return SList([el for el in self if pred(match_target(el))]) | |
1099 | else: |
|
1102 | else: | |
1100 | return SList([el for el in self if not pred(match_target(el))]) |
|
1103 | return SList([el for el in self if not pred(match_target(el))]) | |
1101 | def fields(self, *fields): |
|
1104 | def fields(self, *fields): | |
1102 | """ Collect whitespace-separated fields from string list |
|
1105 | """ Collect whitespace-separated fields from string list | |
1103 |
|
1106 | |||
1104 | Allows quick awk-like usage of string lists. |
|
1107 | Allows quick awk-like usage of string lists. | |
1105 |
|
1108 | |||
1106 | Example data (in var a, created by 'a = !ls -l'):: |
|
1109 | Example data (in var a, created by 'a = !ls -l'):: | |
1107 | -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog |
|
1110 | -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog | |
1108 | drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython |
|
1111 | drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython | |
1109 |
|
1112 | |||
1110 | a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+'] |
|
1113 | a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+'] | |
1111 | a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+'] |
|
1114 | a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+'] | |
1112 | (note the joining by space). |
|
1115 | (note the joining by space). | |
1113 | a.fields(-1) is ['ChangeLog', 'IPython'] |
|
1116 | a.fields(-1) is ['ChangeLog', 'IPython'] | |
1114 |
|
1117 | |||
1115 | IndexErrors are ignored. |
|
1118 | IndexErrors are ignored. | |
1116 |
|
1119 | |||
1117 | Without args, fields() just split()'s the strings. |
|
1120 | Without args, fields() just split()'s the strings. | |
1118 | """ |
|
1121 | """ | |
1119 | if len(fields) == 0: |
|
1122 | if len(fields) == 0: | |
1120 | return [el.split() for el in self] |
|
1123 | return [el.split() for el in self] | |
1121 |
|
1124 | |||
1122 | res = SList() |
|
1125 | res = SList() | |
1123 | for el in [f.split() for f in self]: |
|
1126 | for el in [f.split() for f in self]: | |
1124 | lineparts = [] |
|
1127 | lineparts = [] | |
1125 |
|
1128 | |||
1126 | for fd in fields: |
|
1129 | for fd in fields: | |
1127 | try: |
|
1130 | try: | |
1128 | lineparts.append(el[fd]) |
|
1131 | lineparts.append(el[fd]) | |
1129 | except IndexError: |
|
1132 | except IndexError: | |
1130 | pass |
|
1133 | pass | |
1131 | if lineparts: |
|
1134 | if lineparts: | |
1132 | res.append(" ".join(lineparts)) |
|
1135 | res.append(" ".join(lineparts)) | |
1133 |
|
1136 | |||
1134 | return res |
|
1137 | return res | |
1135 |
|
1138 | |||
1136 |
|
1139 | |||
1137 |
|
1140 | |||
1138 |
|
1141 | |||
1139 |
|
1142 | |||
1140 | def print_slist(arg): |
|
1143 | def print_slist(arg): | |
1141 | """ Prettier (non-repr-like) and more informative printer for SList """ |
|
1144 | """ Prettier (non-repr-like) and more informative printer for SList """ | |
1142 | print "SList (.p, .n, .l, .s, .grep(), .fields() available). Value:" |
|
1145 | print "SList (.p, .n, .l, .s, .grep(), .fields() available). Value:" | |
1143 | nlprint(arg) |
|
1146 | nlprint(arg) | |
1144 |
|
1147 | |||
1145 | print_slist = result_display.when_type(SList)(print_slist) |
|
1148 | print_slist = result_display.when_type(SList)(print_slist) | |
1146 |
|
1149 | |||
1147 |
|
1150 | |||
1148 |
|
1151 | |||
1149 | #---------------------------------------------------------------------------- |
|
1152 | #---------------------------------------------------------------------------- | |
1150 | def esc_quotes(strng): |
|
1153 | def esc_quotes(strng): | |
1151 | """Return the input string with single and double quotes escaped out""" |
|
1154 | """Return the input string with single and double quotes escaped out""" | |
1152 |
|
1155 | |||
1153 | return strng.replace('"','\\"').replace("'","\\'") |
|
1156 | return strng.replace('"','\\"').replace("'","\\'") | |
1154 |
|
1157 | |||
1155 | #---------------------------------------------------------------------------- |
|
1158 | #---------------------------------------------------------------------------- | |
1156 | def make_quoted_expr(s): |
|
1159 | def make_quoted_expr(s): | |
1157 | """Return string s in appropriate quotes, using raw string if possible. |
|
1160 | """Return string s in appropriate quotes, using raw string if possible. | |
1158 |
|
1161 | |||
1159 | Effectively this turns string: cd \ao\ao\ |
|
1162 | Effectively this turns string: cd \ao\ao\ | |
1160 | to: r"cd \ao\ao\_"[:-1] |
|
1163 | to: r"cd \ao\ao\_"[:-1] | |
1161 |
|
1164 | |||
1162 | Note the use of raw string and padding at the end to allow trailing backslash. |
|
1165 | Note the use of raw string and padding at the end to allow trailing backslash. | |
1163 |
|
1166 | |||
1164 | """ |
|
1167 | """ | |
1165 |
|
1168 | |||
1166 | tail = '' |
|
1169 | tail = '' | |
1167 | tailpadding = '' |
|
1170 | tailpadding = '' | |
1168 | raw = '' |
|
1171 | raw = '' | |
1169 | if "\\" in s: |
|
1172 | if "\\" in s: | |
1170 | raw = 'r' |
|
1173 | raw = 'r' | |
1171 | if s.endswith('\\'): |
|
1174 | if s.endswith('\\'): | |
1172 | tail = '[:-1]' |
|
1175 | tail = '[:-1]' | |
1173 | tailpadding = '_' |
|
1176 | tailpadding = '_' | |
1174 | if '"' not in s: |
|
1177 | if '"' not in s: | |
1175 | quote = '"' |
|
1178 | quote = '"' | |
1176 | elif "'" not in s: |
|
1179 | elif "'" not in s: | |
1177 | quote = "'" |
|
1180 | quote = "'" | |
1178 | elif '"""' not in s and not s.endswith('"'): |
|
1181 | elif '"""' not in s and not s.endswith('"'): | |
1179 | quote = '"""' |
|
1182 | quote = '"""' | |
1180 | elif "'''" not in s and not s.endswith("'"): |
|
1183 | elif "'''" not in s and not s.endswith("'"): | |
1181 | quote = "'''" |
|
1184 | quote = "'''" | |
1182 | else: |
|
1185 | else: | |
1183 | # give up, backslash-escaped string will do |
|
1186 | # give up, backslash-escaped string will do | |
1184 | return '"%s"' % esc_quotes(s) |
|
1187 | return '"%s"' % esc_quotes(s) | |
1185 | res = raw + quote + s + tailpadding + quote + tail |
|
1188 | res = raw + quote + s + tailpadding + quote + tail | |
1186 | return res |
|
1189 | return res | |
1187 |
|
1190 | |||
1188 |
|
1191 | |||
1189 | #---------------------------------------------------------------------------- |
|
1192 | #---------------------------------------------------------------------------- | |
1190 | def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'): |
|
1193 | def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'): | |
1191 | """Take multiple lines of input. |
|
1194 | """Take multiple lines of input. | |
1192 |
|
1195 | |||
1193 | A list with each line of input as a separate element is returned when a |
|
1196 | A list with each line of input as a separate element is returned when a | |
1194 | termination string is entered (defaults to a single '.'). Input can also |
|
1197 | termination string is entered (defaults to a single '.'). Input can also | |
1195 | terminate via EOF (^D in Unix, ^Z-RET in Windows). |
|
1198 | terminate via EOF (^D in Unix, ^Z-RET in Windows). | |
1196 |
|
1199 | |||
1197 | Lines of input which end in \\ are joined into single entries (and a |
|
1200 | Lines of input which end in \\ are joined into single entries (and a | |
1198 | secondary continuation prompt is issued as long as the user terminates |
|
1201 | secondary continuation prompt is issued as long as the user terminates | |
1199 | lines with \\). This allows entering very long strings which are still |
|
1202 | lines with \\). This allows entering very long strings which are still | |
1200 | meant to be treated as single entities. |
|
1203 | meant to be treated as single entities. | |
1201 | """ |
|
1204 | """ | |
1202 |
|
1205 | |||
1203 | try: |
|
1206 | try: | |
1204 | if header: |
|
1207 | if header: | |
1205 | header += '\n' |
|
1208 | header += '\n' | |
1206 | lines = [raw_input(header + ps1)] |
|
1209 | lines = [raw_input(header + ps1)] | |
1207 | except EOFError: |
|
1210 | except EOFError: | |
1208 | return [] |
|
1211 | return [] | |
1209 | terminate = [terminate_str] |
|
1212 | terminate = [terminate_str] | |
1210 | try: |
|
1213 | try: | |
1211 | while lines[-1:] != terminate: |
|
1214 | while lines[-1:] != terminate: | |
1212 | new_line = raw_input(ps1) |
|
1215 | new_line = raw_input(ps1) | |
1213 | while new_line.endswith('\\'): |
|
1216 | while new_line.endswith('\\'): | |
1214 | new_line = new_line[:-1] + raw_input(ps2) |
|
1217 | new_line = new_line[:-1] + raw_input(ps2) | |
1215 | lines.append(new_line) |
|
1218 | lines.append(new_line) | |
1216 |
|
1219 | |||
1217 | return lines[:-1] # don't return the termination command |
|
1220 | return lines[:-1] # don't return the termination command | |
1218 | except EOFError: |
|
1221 | except EOFError: | |
1219 |
|
1222 | |||
1220 | return lines |
|
1223 | return lines | |
1221 |
|
1224 | |||
1222 | #---------------------------------------------------------------------------- |
|
1225 | #---------------------------------------------------------------------------- | |
1223 | def raw_input_ext(prompt='', ps2='... '): |
|
1226 | def raw_input_ext(prompt='', ps2='... '): | |
1224 | """Similar to raw_input(), but accepts extended lines if input ends with \\.""" |
|
1227 | """Similar to raw_input(), but accepts extended lines if input ends with \\.""" | |
1225 |
|
1228 | |||
1226 | line = raw_input(prompt) |
|
1229 | line = raw_input(prompt) | |
1227 | while line.endswith('\\'): |
|
1230 | while line.endswith('\\'): | |
1228 | line = line[:-1] + raw_input(ps2) |
|
1231 | line = line[:-1] + raw_input(ps2) | |
1229 | return line |
|
1232 | return line | |
1230 |
|
1233 | |||
1231 | #---------------------------------------------------------------------------- |
|
1234 | #---------------------------------------------------------------------------- | |
1232 | def ask_yes_no(prompt,default=None): |
|
1235 | def ask_yes_no(prompt,default=None): | |
1233 | """Asks a question and returns a boolean (y/n) answer. |
|
1236 | """Asks a question and returns a boolean (y/n) answer. | |
1234 |
|
1237 | |||
1235 | If default is given (one of 'y','n'), it is used if the user input is |
|
1238 | If default is given (one of 'y','n'), it is used if the user input is | |
1236 | empty. Otherwise the question is repeated until an answer is given. |
|
1239 | empty. Otherwise the question is repeated until an answer is given. | |
1237 |
|
1240 | |||
1238 | An EOF is treated as the default answer. If there is no default, an |
|
1241 | An EOF is treated as the default answer. If there is no default, an | |
1239 | exception is raised to prevent infinite loops. |
|
1242 | exception is raised to prevent infinite loops. | |
1240 |
|
1243 | |||
1241 | Valid answers are: y/yes/n/no (match is not case sensitive).""" |
|
1244 | Valid answers are: y/yes/n/no (match is not case sensitive).""" | |
1242 |
|
1245 | |||
1243 | answers = {'y':True,'n':False,'yes':True,'no':False} |
|
1246 | answers = {'y':True,'n':False,'yes':True,'no':False} | |
1244 | ans = None |
|
1247 | ans = None | |
1245 | while ans not in answers.keys(): |
|
1248 | while ans not in answers.keys(): | |
1246 | try: |
|
1249 | try: | |
1247 | ans = raw_input(prompt+' ').lower() |
|
1250 | ans = raw_input(prompt+' ').lower() | |
1248 | if not ans: # response was an empty string |
|
1251 | if not ans: # response was an empty string | |
1249 | ans = default |
|
1252 | ans = default | |
1250 | except KeyboardInterrupt: |
|
1253 | except KeyboardInterrupt: | |
1251 | pass |
|
1254 | pass | |
1252 | except EOFError: |
|
1255 | except EOFError: | |
1253 | if default in answers.keys(): |
|
1256 | if default in answers.keys(): | |
1254 | ans = default |
|
1257 | ans = default | |
1255 |
|
1258 | |||
1256 | else: |
|
1259 | else: | |
1257 | raise |
|
1260 | raise | |
1258 |
|
1261 | |||
1259 | return answers[ans] |
|
1262 | return answers[ans] | |
1260 |
|
1263 | |||
1261 | #---------------------------------------------------------------------------- |
|
1264 | #---------------------------------------------------------------------------- | |
1262 | def marquee(txt='',width=78,mark='*'): |
|
1265 | def marquee(txt='',width=78,mark='*'): | |
1263 | """Return the input string centered in a 'marquee'.""" |
|
1266 | """Return the input string centered in a 'marquee'.""" | |
1264 | if not txt: |
|
1267 | if not txt: | |
1265 | return (mark*width)[:width] |
|
1268 | return (mark*width)[:width] | |
1266 | nmark = (width-len(txt)-2)/len(mark)/2 |
|
1269 | nmark = (width-len(txt)-2)/len(mark)/2 | |
1267 | if nmark < 0: nmark =0 |
|
1270 | if nmark < 0: nmark =0 | |
1268 | marks = mark*nmark |
|
1271 | marks = mark*nmark | |
1269 | return '%s %s %s' % (marks,txt,marks) |
|
1272 | return '%s %s %s' % (marks,txt,marks) | |
1270 |
|
1273 | |||
1271 | #---------------------------------------------------------------------------- |
|
1274 | #---------------------------------------------------------------------------- | |
1272 | class EvalDict: |
|
1275 | class EvalDict: | |
1273 | """ |
|
1276 | """ | |
1274 | Emulate a dict which evaluates its contents in the caller's frame. |
|
1277 | Emulate a dict which evaluates its contents in the caller's frame. | |
1275 |
|
1278 | |||
1276 | Usage: |
|
1279 | Usage: | |
1277 | >>>number = 19 |
|
1280 | >>>number = 19 | |
1278 | >>>text = "python" |
|
1281 | >>>text = "python" | |
1279 | >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict() |
|
1282 | >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict() | |
1280 | """ |
|
1283 | """ | |
1281 |
|
1284 | |||
1282 | # This version is due to sismex01@hebmex.com on c.l.py, and is basically a |
|
1285 | # This version is due to sismex01@hebmex.com on c.l.py, and is basically a | |
1283 | # modified (shorter) version of: |
|
1286 | # modified (shorter) version of: | |
1284 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by |
|
1287 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by | |
1285 | # Skip Montanaro (skip@pobox.com). |
|
1288 | # Skip Montanaro (skip@pobox.com). | |
1286 |
|
1289 | |||
1287 | def __getitem__(self, name): |
|
1290 | def __getitem__(self, name): | |
1288 | frame = sys._getframe(1) |
|
1291 | frame = sys._getframe(1) | |
1289 | return eval(name, frame.f_globals, frame.f_locals) |
|
1292 | return eval(name, frame.f_globals, frame.f_locals) | |
1290 |
|
1293 | |||
1291 | EvalString = EvalDict # for backwards compatibility |
|
1294 | EvalString = EvalDict # for backwards compatibility | |
1292 | #---------------------------------------------------------------------------- |
|
1295 | #---------------------------------------------------------------------------- | |
1293 | def qw(words,flat=0,sep=None,maxsplit=-1): |
|
1296 | def qw(words,flat=0,sep=None,maxsplit=-1): | |
1294 | """Similar to Perl's qw() operator, but with some more options. |
|
1297 | """Similar to Perl's qw() operator, but with some more options. | |
1295 |
|
1298 | |||
1296 | qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit) |
|
1299 | qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit) | |
1297 |
|
1300 | |||
1298 | words can also be a list itself, and with flat=1, the output will be |
|
1301 | words can also be a list itself, and with flat=1, the output will be | |
1299 | recursively flattened. Examples: |
|
1302 | recursively flattened. Examples: | |
1300 |
|
1303 | |||
1301 | >>> qw('1 2') |
|
1304 | >>> qw('1 2') | |
1302 | ['1', '2'] |
|
1305 | ['1', '2'] | |
1303 | >>> qw(['a b','1 2',['m n','p q']]) |
|
1306 | >>> qw(['a b','1 2',['m n','p q']]) | |
1304 | [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]] |
|
1307 | [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]] | |
1305 | >>> qw(['a b','1 2',['m n','p q']],flat=1) |
|
1308 | >>> qw(['a b','1 2',['m n','p q']],flat=1) | |
1306 | ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """ |
|
1309 | ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """ | |
1307 |
|
1310 | |||
1308 | if type(words) in StringTypes: |
|
1311 | if type(words) in StringTypes: | |
1309 | return [word.strip() for word in words.split(sep,maxsplit) |
|
1312 | return [word.strip() for word in words.split(sep,maxsplit) | |
1310 | if word and not word.isspace() ] |
|
1313 | if word and not word.isspace() ] | |
1311 | if flat: |
|
1314 | if flat: | |
1312 | return flatten(map(qw,words,[1]*len(words))) |
|
1315 | return flatten(map(qw,words,[1]*len(words))) | |
1313 | return map(qw,words) |
|
1316 | return map(qw,words) | |
1314 |
|
1317 | |||
1315 | #---------------------------------------------------------------------------- |
|
1318 | #---------------------------------------------------------------------------- | |
1316 | def qwflat(words,sep=None,maxsplit=-1): |
|
1319 | def qwflat(words,sep=None,maxsplit=-1): | |
1317 | """Calls qw(words) in flat mode. It's just a convenient shorthand.""" |
|
1320 | """Calls qw(words) in flat mode. It's just a convenient shorthand.""" | |
1318 | return qw(words,1,sep,maxsplit) |
|
1321 | return qw(words,1,sep,maxsplit) | |
1319 |
|
1322 | |||
1320 | #---------------------------------------------------------------------------- |
|
1323 | #---------------------------------------------------------------------------- | |
1321 | def qw_lol(indata): |
|
1324 | def qw_lol(indata): | |
1322 | """qw_lol('a b') -> [['a','b']], |
|
1325 | """qw_lol('a b') -> [['a','b']], | |
1323 | otherwise it's just a call to qw(). |
|
1326 | otherwise it's just a call to qw(). | |
1324 |
|
1327 | |||
1325 | We need this to make sure the modules_some keys *always* end up as a |
|
1328 | We need this to make sure the modules_some keys *always* end up as a | |
1326 | list of lists.""" |
|
1329 | list of lists.""" | |
1327 |
|
1330 | |||
1328 | if type(indata) in StringTypes: |
|
1331 | if type(indata) in StringTypes: | |
1329 | return [qw(indata)] |
|
1332 | return [qw(indata)] | |
1330 | else: |
|
1333 | else: | |
1331 | return qw(indata) |
|
1334 | return qw(indata) | |
1332 |
|
1335 | |||
1333 | #----------------------------------------------------------------------------- |
|
1336 | #----------------------------------------------------------------------------- | |
1334 | def list_strings(arg): |
|
1337 | def list_strings(arg): | |
1335 | """Always return a list of strings, given a string or list of strings |
|
1338 | """Always return a list of strings, given a string or list of strings | |
1336 | as input.""" |
|
1339 | as input.""" | |
1337 |
|
1340 | |||
1338 | if type(arg) in StringTypes: return [arg] |
|
1341 | if type(arg) in StringTypes: return [arg] | |
1339 | else: return arg |
|
1342 | else: return arg | |
1340 |
|
1343 | |||
1341 | #---------------------------------------------------------------------------- |
|
1344 | #---------------------------------------------------------------------------- | |
1342 | def grep(pat,list,case=1): |
|
1345 | def grep(pat,list,case=1): | |
1343 | """Simple minded grep-like function. |
|
1346 | """Simple minded grep-like function. | |
1344 | grep(pat,list) returns occurrences of pat in list, None on failure. |
|
1347 | grep(pat,list) returns occurrences of pat in list, None on failure. | |
1345 |
|
1348 | |||
1346 | It only does simple string matching, with no support for regexps. Use the |
|
1349 | It only does simple string matching, with no support for regexps. Use the | |
1347 | option case=0 for case-insensitive matching.""" |
|
1350 | option case=0 for case-insensitive matching.""" | |
1348 |
|
1351 | |||
1349 | # This is pretty crude. At least it should implement copying only references |
|
1352 | # This is pretty crude. At least it should implement copying only references | |
1350 | # to the original data in case it's big. Now it copies the data for output. |
|
1353 | # to the original data in case it's big. Now it copies the data for output. | |
1351 | out=[] |
|
1354 | out=[] | |
1352 | if case: |
|
1355 | if case: | |
1353 | for term in list: |
|
1356 | for term in list: | |
1354 | if term.find(pat)>-1: out.append(term) |
|
1357 | if term.find(pat)>-1: out.append(term) | |
1355 | else: |
|
1358 | else: | |
1356 | lpat=pat.lower() |
|
1359 | lpat=pat.lower() | |
1357 | for term in list: |
|
1360 | for term in list: | |
1358 | if term.lower().find(lpat)>-1: out.append(term) |
|
1361 | if term.lower().find(lpat)>-1: out.append(term) | |
1359 |
|
1362 | |||
1360 | if len(out): return out |
|
1363 | if len(out): return out | |
1361 | else: return None |
|
1364 | else: return None | |
1362 |
|
1365 | |||
1363 | #---------------------------------------------------------------------------- |
|
1366 | #---------------------------------------------------------------------------- | |
1364 | def dgrep(pat,*opts): |
|
1367 | def dgrep(pat,*opts): | |
1365 | """Return grep() on dir()+dir(__builtins__). |
|
1368 | """Return grep() on dir()+dir(__builtins__). | |
1366 |
|
1369 | |||
1367 | A very common use of grep() when working interactively.""" |
|
1370 | A very common use of grep() when working interactively.""" | |
1368 |
|
1371 | |||
1369 | return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts) |
|
1372 | return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts) | |
1370 |
|
1373 | |||
1371 | #---------------------------------------------------------------------------- |
|
1374 | #---------------------------------------------------------------------------- | |
1372 | def idgrep(pat): |
|
1375 | def idgrep(pat): | |
1373 | """Case-insensitive dgrep()""" |
|
1376 | """Case-insensitive dgrep()""" | |
1374 |
|
1377 | |||
1375 | return dgrep(pat,0) |
|
1378 | return dgrep(pat,0) | |
1376 |
|
1379 | |||
1377 | #---------------------------------------------------------------------------- |
|
1380 | #---------------------------------------------------------------------------- | |
1378 | def igrep(pat,list): |
|
1381 | def igrep(pat,list): | |
1379 | """Synonym for case-insensitive grep.""" |
|
1382 | """Synonym for case-insensitive grep.""" | |
1380 |
|
1383 | |||
1381 | return grep(pat,list,case=0) |
|
1384 | return grep(pat,list,case=0) | |
1382 |
|
1385 | |||
1383 | #---------------------------------------------------------------------------- |
|
1386 | #---------------------------------------------------------------------------- | |
1384 | def indent(str,nspaces=4,ntabs=0): |
|
1387 | def indent(str,nspaces=4,ntabs=0): | |
1385 | """Indent a string a given number of spaces or tabstops. |
|
1388 | """Indent a string a given number of spaces or tabstops. | |
1386 |
|
1389 | |||
1387 | indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. |
|
1390 | indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. | |
1388 | """ |
|
1391 | """ | |
1389 | if str is None: |
|
1392 | if str is None: | |
1390 | return |
|
1393 | return | |
1391 | ind = '\t'*ntabs+' '*nspaces |
|
1394 | ind = '\t'*ntabs+' '*nspaces | |
1392 | outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind)) |
|
1395 | outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind)) | |
1393 | if outstr.endswith(os.linesep+ind): |
|
1396 | if outstr.endswith(os.linesep+ind): | |
1394 | return outstr[:-len(ind)] |
|
1397 | return outstr[:-len(ind)] | |
1395 | else: |
|
1398 | else: | |
1396 | return outstr |
|
1399 | return outstr | |
1397 |
|
1400 | |||
1398 | #----------------------------------------------------------------------------- |
|
1401 | #----------------------------------------------------------------------------- | |
1399 | def native_line_ends(filename,backup=1): |
|
1402 | def native_line_ends(filename,backup=1): | |
1400 | """Convert (in-place) a file to line-ends native to the current OS. |
|
1403 | """Convert (in-place) a file to line-ends native to the current OS. | |
1401 |
|
1404 | |||
1402 | If the optional backup argument is given as false, no backup of the |
|
1405 | If the optional backup argument is given as false, no backup of the | |
1403 | original file is left. """ |
|
1406 | original file is left. """ | |
1404 |
|
1407 | |||
1405 | backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'} |
|
1408 | backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'} | |
1406 |
|
1409 | |||
1407 | bak_filename = filename + backup_suffixes[os.name] |
|
1410 | bak_filename = filename + backup_suffixes[os.name] | |
1408 |
|
1411 | |||
1409 | original = open(filename).read() |
|
1412 | original = open(filename).read() | |
1410 | shutil.copy2(filename,bak_filename) |
|
1413 | shutil.copy2(filename,bak_filename) | |
1411 | try: |
|
1414 | try: | |
1412 | new = open(filename,'wb') |
|
1415 | new = open(filename,'wb') | |
1413 | new.write(os.linesep.join(original.splitlines())) |
|
1416 | new.write(os.linesep.join(original.splitlines())) | |
1414 | new.write(os.linesep) # ALWAYS put an eol at the end of the file |
|
1417 | new.write(os.linesep) # ALWAYS put an eol at the end of the file | |
1415 | new.close() |
|
1418 | new.close() | |
1416 | except: |
|
1419 | except: | |
1417 | os.rename(bak_filename,filename) |
|
1420 | os.rename(bak_filename,filename) | |
1418 | if not backup: |
|
1421 | if not backup: | |
1419 | try: |
|
1422 | try: | |
1420 | os.remove(bak_filename) |
|
1423 | os.remove(bak_filename) | |
1421 | except: |
|
1424 | except: | |
1422 | pass |
|
1425 | pass | |
1423 |
|
1426 | |||
1424 | #---------------------------------------------------------------------------- |
|
1427 | #---------------------------------------------------------------------------- | |
1425 | def get_pager_cmd(pager_cmd = None): |
|
1428 | def get_pager_cmd(pager_cmd = None): | |
1426 | """Return a pager command. |
|
1429 | """Return a pager command. | |
1427 |
|
1430 | |||
1428 | Makes some attempts at finding an OS-correct one.""" |
|
1431 | Makes some attempts at finding an OS-correct one.""" | |
1429 |
|
1432 | |||
1430 | if os.name == 'posix': |
|
1433 | if os.name == 'posix': | |
1431 | default_pager_cmd = 'less -r' # -r for color control sequences |
|
1434 | default_pager_cmd = 'less -r' # -r for color control sequences | |
1432 | elif os.name in ['nt','dos']: |
|
1435 | elif os.name in ['nt','dos']: | |
1433 | default_pager_cmd = 'type' |
|
1436 | default_pager_cmd = 'type' | |
1434 |
|
1437 | |||
1435 | if pager_cmd is None: |
|
1438 | if pager_cmd is None: | |
1436 | try: |
|
1439 | try: | |
1437 | pager_cmd = os.environ['PAGER'] |
|
1440 | pager_cmd = os.environ['PAGER'] | |
1438 | except: |
|
1441 | except: | |
1439 | pager_cmd = default_pager_cmd |
|
1442 | pager_cmd = default_pager_cmd | |
1440 | return pager_cmd |
|
1443 | return pager_cmd | |
1441 |
|
1444 | |||
1442 | #----------------------------------------------------------------------------- |
|
1445 | #----------------------------------------------------------------------------- | |
1443 | def get_pager_start(pager,start): |
|
1446 | def get_pager_start(pager,start): | |
1444 | """Return the string for paging files with an offset. |
|
1447 | """Return the string for paging files with an offset. | |
1445 |
|
1448 | |||
1446 | This is the '+N' argument which less and more (under Unix) accept. |
|
1449 | This is the '+N' argument which less and more (under Unix) accept. | |
1447 | """ |
|
1450 | """ | |
1448 |
|
1451 | |||
1449 | if pager in ['less','more']: |
|
1452 | if pager in ['less','more']: | |
1450 | if start: |
|
1453 | if start: | |
1451 | start_string = '+' + str(start) |
|
1454 | start_string = '+' + str(start) | |
1452 | else: |
|
1455 | else: | |
1453 | start_string = '' |
|
1456 | start_string = '' | |
1454 | else: |
|
1457 | else: | |
1455 | start_string = '' |
|
1458 | start_string = '' | |
1456 | return start_string |
|
1459 | return start_string | |
1457 |
|
1460 | |||
1458 | #---------------------------------------------------------------------------- |
|
1461 | #---------------------------------------------------------------------------- | |
1459 | # (X)emacs on W32 doesn't like to be bypassed with msvcrt.getch() |
|
1462 | # (X)emacs on W32 doesn't like to be bypassed with msvcrt.getch() | |
1460 | if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs': |
|
1463 | if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs': | |
1461 | import msvcrt |
|
1464 | import msvcrt | |
1462 | def page_more(): |
|
1465 | def page_more(): | |
1463 | """ Smart pausing between pages |
|
1466 | """ Smart pausing between pages | |
1464 |
|
1467 | |||
1465 | @return: True if need print more lines, False if quit |
|
1468 | @return: True if need print more lines, False if quit | |
1466 | """ |
|
1469 | """ | |
1467 | Term.cout.write('---Return to continue, q to quit--- ') |
|
1470 | Term.cout.write('---Return to continue, q to quit--- ') | |
1468 | ans = msvcrt.getch() |
|
1471 | ans = msvcrt.getch() | |
1469 | if ans in ("q", "Q"): |
|
1472 | if ans in ("q", "Q"): | |
1470 | result = False |
|
1473 | result = False | |
1471 | else: |
|
1474 | else: | |
1472 | result = True |
|
1475 | result = True | |
1473 | Term.cout.write("\b"*37 + " "*37 + "\b"*37) |
|
1476 | Term.cout.write("\b"*37 + " "*37 + "\b"*37) | |
1474 | return result |
|
1477 | return result | |
1475 | else: |
|
1478 | else: | |
1476 | def page_more(): |
|
1479 | def page_more(): | |
1477 | ans = raw_input('---Return to continue, q to quit--- ') |
|
1480 | ans = raw_input('---Return to continue, q to quit--- ') | |
1478 | if ans.lower().startswith('q'): |
|
1481 | if ans.lower().startswith('q'): | |
1479 | return False |
|
1482 | return False | |
1480 | else: |
|
1483 | else: | |
1481 | return True |
|
1484 | return True | |
1482 |
|
1485 | |||
1483 | esc_re = re.compile(r"(\x1b[^m]+m)") |
|
1486 | esc_re = re.compile(r"(\x1b[^m]+m)") | |
1484 |
|
1487 | |||
1485 | def page_dumb(strng,start=0,screen_lines=25): |
|
1488 | def page_dumb(strng,start=0,screen_lines=25): | |
1486 | """Very dumb 'pager' in Python, for when nothing else works. |
|
1489 | """Very dumb 'pager' in Python, for when nothing else works. | |
1487 |
|
1490 | |||
1488 | Only moves forward, same interface as page(), except for pager_cmd and |
|
1491 | Only moves forward, same interface as page(), except for pager_cmd and | |
1489 | mode.""" |
|
1492 | mode.""" | |
1490 |
|
1493 | |||
1491 | out_ln = strng.splitlines()[start:] |
|
1494 | out_ln = strng.splitlines()[start:] | |
1492 | screens = chop(out_ln,screen_lines-1) |
|
1495 | screens = chop(out_ln,screen_lines-1) | |
1493 | if len(screens) == 1: |
|
1496 | if len(screens) == 1: | |
1494 | print >>Term.cout, os.linesep.join(screens[0]) |
|
1497 | print >>Term.cout, os.linesep.join(screens[0]) | |
1495 | else: |
|
1498 | else: | |
1496 | last_escape = "" |
|
1499 | last_escape = "" | |
1497 | for scr in screens[0:-1]: |
|
1500 | for scr in screens[0:-1]: | |
1498 | hunk = os.linesep.join(scr) |
|
1501 | hunk = os.linesep.join(scr) | |
1499 | print >>Term.cout, last_escape + hunk |
|
1502 | print >>Term.cout, last_escape + hunk | |
1500 | if not page_more(): |
|
1503 | if not page_more(): | |
1501 | return |
|
1504 | return | |
1502 | esc_list = esc_re.findall(hunk) |
|
1505 | esc_list = esc_re.findall(hunk) | |
1503 | if len(esc_list) > 0: |
|
1506 | if len(esc_list) > 0: | |
1504 | last_escape = esc_list[-1] |
|
1507 | last_escape = esc_list[-1] | |
1505 | print >>Term.cout, last_escape + os.linesep.join(screens[-1]) |
|
1508 | print >>Term.cout, last_escape + os.linesep.join(screens[-1]) | |
1506 |
|
1509 | |||
1507 | #---------------------------------------------------------------------------- |
|
1510 | #---------------------------------------------------------------------------- | |
1508 | def page(strng,start=0,screen_lines=0,pager_cmd = None): |
|
1511 | def page(strng,start=0,screen_lines=0,pager_cmd = None): | |
1509 | """Print a string, piping through a pager after a certain length. |
|
1512 | """Print a string, piping through a pager after a certain length. | |
1510 |
|
1513 | |||
1511 | The screen_lines parameter specifies the number of *usable* lines of your |
|
1514 | The screen_lines parameter specifies the number of *usable* lines of your | |
1512 | terminal screen (total lines minus lines you need to reserve to show other |
|
1515 | terminal screen (total lines minus lines you need to reserve to show other | |
1513 | information). |
|
1516 | information). | |
1514 |
|
1517 | |||
1515 | If you set screen_lines to a number <=0, page() will try to auto-determine |
|
1518 | If you set screen_lines to a number <=0, page() will try to auto-determine | |
1516 | your screen size and will only use up to (screen_size+screen_lines) for |
|
1519 | your screen size and will only use up to (screen_size+screen_lines) for | |
1517 | printing, paging after that. That is, if you want auto-detection but need |
|
1520 | printing, paging after that. That is, if you want auto-detection but need | |
1518 | to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for |
|
1521 | to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for | |
1519 | auto-detection without any lines reserved simply use screen_lines = 0. |
|
1522 | auto-detection without any lines reserved simply use screen_lines = 0. | |
1520 |
|
1523 | |||
1521 | If a string won't fit in the allowed lines, it is sent through the |
|
1524 | If a string won't fit in the allowed lines, it is sent through the | |
1522 | specified pager command. If none given, look for PAGER in the environment, |
|
1525 | specified pager command. If none given, look for PAGER in the environment, | |
1523 | and ultimately default to less. |
|
1526 | and ultimately default to less. | |
1524 |
|
1527 | |||
1525 | If no system pager works, the string is sent through a 'dumb pager' |
|
1528 | If no system pager works, the string is sent through a 'dumb pager' | |
1526 | written in python, very simplistic. |
|
1529 | written in python, very simplistic. | |
1527 | """ |
|
1530 | """ | |
1528 |
|
1531 | |||
1529 |
|
1532 | |||
1530 | # first, try the hook |
|
1533 | # first, try the hook | |
1531 | ip = IPython.ipapi.get() |
|
1534 | ip = IPython.ipapi.get() | |
1532 | if ip: |
|
1535 | if ip: | |
1533 | try: |
|
1536 | try: | |
1534 | ip.IP.hooks.show_in_pager(strng) |
|
1537 | ip.IP.hooks.show_in_pager(strng) | |
1535 | return |
|
1538 | return | |
1536 | except IPython.ipapi.TryNext: |
|
1539 | except IPython.ipapi.TryNext: | |
1537 | pass |
|
1540 | pass | |
1538 |
|
1541 | |||
1539 | # Ugly kludge, but calling curses.initscr() flat out crashes in emacs |
|
1542 | # Ugly kludge, but calling curses.initscr() flat out crashes in emacs | |
1540 | TERM = os.environ.get('TERM','dumb') |
|
1543 | TERM = os.environ.get('TERM','dumb') | |
1541 | if TERM in ['dumb','emacs'] and os.name != 'nt': |
|
1544 | if TERM in ['dumb','emacs'] and os.name != 'nt': | |
1542 | print strng |
|
1545 | print strng | |
1543 | return |
|
1546 | return | |
1544 | # chop off the topmost part of the string we don't want to see |
|
1547 | # chop off the topmost part of the string we don't want to see | |
1545 | str_lines = strng.split(os.linesep)[start:] |
|
1548 | str_lines = strng.split(os.linesep)[start:] | |
1546 | str_toprint = os.linesep.join(str_lines) |
|
1549 | str_toprint = os.linesep.join(str_lines) | |
1547 | num_newlines = len(str_lines) |
|
1550 | num_newlines = len(str_lines) | |
1548 | len_str = len(str_toprint) |
|
1551 | len_str = len(str_toprint) | |
1549 |
|
1552 | |||
1550 | # Dumb heuristics to guesstimate number of on-screen lines the string |
|
1553 | # Dumb heuristics to guesstimate number of on-screen lines the string | |
1551 | # takes. Very basic, but good enough for docstrings in reasonable |
|
1554 | # takes. Very basic, but good enough for docstrings in reasonable | |
1552 | # terminals. If someone later feels like refining it, it's not hard. |
|
1555 | # terminals. If someone later feels like refining it, it's not hard. | |
1553 | numlines = max(num_newlines,int(len_str/80)+1) |
|
1556 | numlines = max(num_newlines,int(len_str/80)+1) | |
1554 |
|
1557 | |||
1555 | if os.name == "nt": |
|
1558 | if os.name == "nt": | |
1556 | screen_lines_def = get_console_size(defaulty=25)[1] |
|
1559 | screen_lines_def = get_console_size(defaulty=25)[1] | |
1557 | else: |
|
1560 | else: | |
1558 | screen_lines_def = 25 # default value if we can't auto-determine |
|
1561 | screen_lines_def = 25 # default value if we can't auto-determine | |
1559 |
|
1562 | |||
1560 | # auto-determine screen size |
|
1563 | # auto-determine screen size | |
1561 | if screen_lines <= 0: |
|
1564 | if screen_lines <= 0: | |
1562 | if TERM=='xterm': |
|
1565 | if TERM=='xterm': | |
1563 | use_curses = USE_CURSES |
|
1566 | use_curses = USE_CURSES | |
1564 | else: |
|
1567 | else: | |
1565 | # curses causes problems on many terminals other than xterm. |
|
1568 | # curses causes problems on many terminals other than xterm. | |
1566 | use_curses = False |
|
1569 | use_curses = False | |
1567 | if use_curses: |
|
1570 | if use_curses: | |
1568 | # There is a bug in curses, where *sometimes* it fails to properly |
|
1571 | # There is a bug in curses, where *sometimes* it fails to properly | |
1569 | # initialize, and then after the endwin() call is made, the |
|
1572 | # initialize, and then after the endwin() call is made, the | |
1570 | # terminal is left in an unusable state. Rather than trying to |
|
1573 | # terminal is left in an unusable state. Rather than trying to | |
1571 | # check everytime for this (by requesting and comparing termios |
|
1574 | # check everytime for this (by requesting and comparing termios | |
1572 | # flags each time), we just save the initial terminal state and |
|
1575 | # flags each time), we just save the initial terminal state and | |
1573 | # unconditionally reset it every time. It's cheaper than making |
|
1576 | # unconditionally reset it every time. It's cheaper than making | |
1574 | # the checks. |
|
1577 | # the checks. | |
1575 | term_flags = termios.tcgetattr(sys.stdout) |
|
1578 | term_flags = termios.tcgetattr(sys.stdout) | |
1576 | scr = curses.initscr() |
|
1579 | scr = curses.initscr() | |
1577 | screen_lines_real,screen_cols = scr.getmaxyx() |
|
1580 | screen_lines_real,screen_cols = scr.getmaxyx() | |
1578 | curses.endwin() |
|
1581 | curses.endwin() | |
1579 | # Restore terminal state in case endwin() didn't. |
|
1582 | # Restore terminal state in case endwin() didn't. | |
1580 | termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags) |
|
1583 | termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags) | |
1581 | # Now we have what we needed: the screen size in rows/columns |
|
1584 | # Now we have what we needed: the screen size in rows/columns | |
1582 | screen_lines += screen_lines_real |
|
1585 | screen_lines += screen_lines_real | |
1583 | #print '***Screen size:',screen_lines_real,'lines x',\ |
|
1586 | #print '***Screen size:',screen_lines_real,'lines x',\ | |
1584 | #screen_cols,'columns.' # dbg |
|
1587 | #screen_cols,'columns.' # dbg | |
1585 | else: |
|
1588 | else: | |
1586 | screen_lines += screen_lines_def |
|
1589 | screen_lines += screen_lines_def | |
1587 |
|
1590 | |||
1588 | #print 'numlines',numlines,'screenlines',screen_lines # dbg |
|
1591 | #print 'numlines',numlines,'screenlines',screen_lines # dbg | |
1589 | if numlines <= screen_lines : |
|
1592 | if numlines <= screen_lines : | |
1590 | #print '*** normal print' # dbg |
|
1593 | #print '*** normal print' # dbg | |
1591 | print >>Term.cout, str_toprint |
|
1594 | print >>Term.cout, str_toprint | |
1592 | else: |
|
1595 | else: | |
1593 | # Try to open pager and default to internal one if that fails. |
|
1596 | # Try to open pager and default to internal one if that fails. | |
1594 | # All failure modes are tagged as 'retval=1', to match the return |
|
1597 | # All failure modes are tagged as 'retval=1', to match the return | |
1595 | # value of a failed system command. If any intermediate attempt |
|
1598 | # value of a failed system command. If any intermediate attempt | |
1596 | # sets retval to 1, at the end we resort to our own page_dumb() pager. |
|
1599 | # sets retval to 1, at the end we resort to our own page_dumb() pager. | |
1597 | pager_cmd = get_pager_cmd(pager_cmd) |
|
1600 | pager_cmd = get_pager_cmd(pager_cmd) | |
1598 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) |
|
1601 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) | |
1599 | if os.name == 'nt': |
|
1602 | if os.name == 'nt': | |
1600 | if pager_cmd.startswith('type'): |
|
1603 | if pager_cmd.startswith('type'): | |
1601 | # The default WinXP 'type' command is failing on complex strings. |
|
1604 | # The default WinXP 'type' command is failing on complex strings. | |
1602 | retval = 1 |
|
1605 | retval = 1 | |
1603 | else: |
|
1606 | else: | |
1604 | tmpname = tempfile.mktemp('.txt') |
|
1607 | tmpname = tempfile.mktemp('.txt') | |
1605 | tmpfile = file(tmpname,'wt') |
|
1608 | tmpfile = file(tmpname,'wt') | |
1606 | tmpfile.write(strng) |
|
1609 | tmpfile.write(strng) | |
1607 | tmpfile.close() |
|
1610 | tmpfile.close() | |
1608 | cmd = "%s < %s" % (pager_cmd,tmpname) |
|
1611 | cmd = "%s < %s" % (pager_cmd,tmpname) | |
1609 | if os.system(cmd): |
|
1612 | if os.system(cmd): | |
1610 | retval = 1 |
|
1613 | retval = 1 | |
1611 | else: |
|
1614 | else: | |
1612 | retval = None |
|
1615 | retval = None | |
1613 | os.remove(tmpname) |
|
1616 | os.remove(tmpname) | |
1614 | else: |
|
1617 | else: | |
1615 | try: |
|
1618 | try: | |
1616 | retval = None |
|
1619 | retval = None | |
1617 | # if I use popen4, things hang. No idea why. |
|
1620 | # if I use popen4, things hang. No idea why. | |
1618 | #pager,shell_out = os.popen4(pager_cmd) |
|
1621 | #pager,shell_out = os.popen4(pager_cmd) | |
1619 | pager = os.popen(pager_cmd,'w') |
|
1622 | pager = os.popen(pager_cmd,'w') | |
1620 | pager.write(strng) |
|
1623 | pager.write(strng) | |
1621 | pager.close() |
|
1624 | pager.close() | |
1622 | retval = pager.close() # success returns None |
|
1625 | retval = pager.close() # success returns None | |
1623 | except IOError,msg: # broken pipe when user quits |
|
1626 | except IOError,msg: # broken pipe when user quits | |
1624 | if msg.args == (32,'Broken pipe'): |
|
1627 | if msg.args == (32,'Broken pipe'): | |
1625 | retval = None |
|
1628 | retval = None | |
1626 | else: |
|
1629 | else: | |
1627 | retval = 1 |
|
1630 | retval = 1 | |
1628 | except OSError: |
|
1631 | except OSError: | |
1629 | # Other strange problems, sometimes seen in Win2k/cygwin |
|
1632 | # Other strange problems, sometimes seen in Win2k/cygwin | |
1630 | retval = 1 |
|
1633 | retval = 1 | |
1631 | if retval is not None: |
|
1634 | if retval is not None: | |
1632 | page_dumb(strng,screen_lines=screen_lines) |
|
1635 | page_dumb(strng,screen_lines=screen_lines) | |
1633 |
|
1636 | |||
1634 | #---------------------------------------------------------------------------- |
|
1637 | #---------------------------------------------------------------------------- | |
1635 | def page_file(fname,start = 0, pager_cmd = None): |
|
1638 | def page_file(fname,start = 0, pager_cmd = None): | |
1636 | """Page a file, using an optional pager command and starting line. |
|
1639 | """Page a file, using an optional pager command and starting line. | |
1637 | """ |
|
1640 | """ | |
1638 |
|
1641 | |||
1639 | pager_cmd = get_pager_cmd(pager_cmd) |
|
1642 | pager_cmd = get_pager_cmd(pager_cmd) | |
1640 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) |
|
1643 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) | |
1641 |
|
1644 | |||
1642 | try: |
|
1645 | try: | |
1643 | if os.environ['TERM'] in ['emacs','dumb']: |
|
1646 | if os.environ['TERM'] in ['emacs','dumb']: | |
1644 | raise EnvironmentError |
|
1647 | raise EnvironmentError | |
1645 | xsys(pager_cmd + ' ' + fname) |
|
1648 | xsys(pager_cmd + ' ' + fname) | |
1646 | except: |
|
1649 | except: | |
1647 | try: |
|
1650 | try: | |
1648 | if start > 0: |
|
1651 | if start > 0: | |
1649 | start -= 1 |
|
1652 | start -= 1 | |
1650 | page(open(fname).read(),start) |
|
1653 | page(open(fname).read(),start) | |
1651 | except: |
|
1654 | except: | |
1652 | print 'Unable to show file',`fname` |
|
1655 | print 'Unable to show file',`fname` | |
1653 |
|
1656 | |||
1654 |
|
1657 | |||
1655 | #---------------------------------------------------------------------------- |
|
1658 | #---------------------------------------------------------------------------- | |
1656 | def snip_print(str,width = 75,print_full = 0,header = ''): |
|
1659 | def snip_print(str,width = 75,print_full = 0,header = ''): | |
1657 | """Print a string snipping the midsection to fit in width. |
|
1660 | """Print a string snipping the midsection to fit in width. | |
1658 |
|
1661 | |||
1659 | print_full: mode control: |
|
1662 | print_full: mode control: | |
1660 | - 0: only snip long strings |
|
1663 | - 0: only snip long strings | |
1661 | - 1: send to page() directly. |
|
1664 | - 1: send to page() directly. | |
1662 | - 2: snip long strings and ask for full length viewing with page() |
|
1665 | - 2: snip long strings and ask for full length viewing with page() | |
1663 | Return 1 if snipping was necessary, 0 otherwise.""" |
|
1666 | Return 1 if snipping was necessary, 0 otherwise.""" | |
1664 |
|
1667 | |||
1665 | if print_full == 1: |
|
1668 | if print_full == 1: | |
1666 | page(header+str) |
|
1669 | page(header+str) | |
1667 | return 0 |
|
1670 | return 0 | |
1668 |
|
1671 | |||
1669 | print header, |
|
1672 | print header, | |
1670 | if len(str) < width: |
|
1673 | if len(str) < width: | |
1671 | print str |
|
1674 | print str | |
1672 | snip = 0 |
|
1675 | snip = 0 | |
1673 | else: |
|
1676 | else: | |
1674 | whalf = int((width -5)/2) |
|
1677 | whalf = int((width -5)/2) | |
1675 | print str[:whalf] + ' <...> ' + str[-whalf:] |
|
1678 | print str[:whalf] + ' <...> ' + str[-whalf:] | |
1676 | snip = 1 |
|
1679 | snip = 1 | |
1677 | if snip and print_full == 2: |
|
1680 | if snip and print_full == 2: | |
1678 | if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y': |
|
1681 | if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y': | |
1679 | page(str) |
|
1682 | page(str) | |
1680 | return snip |
|
1683 | return snip | |
1681 |
|
1684 | |||
1682 | #**************************************************************************** |
|
1685 | #**************************************************************************** | |
1683 | # lists, dicts and structures |
|
1686 | # lists, dicts and structures | |
1684 |
|
1687 | |||
1685 | def belong(candidates,checklist): |
|
1688 | def belong(candidates,checklist): | |
1686 | """Check whether a list of items appear in a given list of options. |
|
1689 | """Check whether a list of items appear in a given list of options. | |
1687 |
|
1690 | |||
1688 | Returns a list of 1 and 0, one for each candidate given.""" |
|
1691 | Returns a list of 1 and 0, one for each candidate given.""" | |
1689 |
|
1692 | |||
1690 | return [x in checklist for x in candidates] |
|
1693 | return [x in checklist for x in candidates] | |
1691 |
|
1694 | |||
1692 | #---------------------------------------------------------------------------- |
|
1695 | #---------------------------------------------------------------------------- | |
1693 | def uniq_stable(elems): |
|
1696 | def uniq_stable(elems): | |
1694 | """uniq_stable(elems) -> list |
|
1697 | """uniq_stable(elems) -> list | |
1695 |
|
1698 | |||
1696 | Return from an iterable, a list of all the unique elements in the input, |
|
1699 | Return from an iterable, a list of all the unique elements in the input, | |
1697 | but maintaining the order in which they first appear. |
|
1700 | but maintaining the order in which they first appear. | |
1698 |
|
1701 | |||
1699 | A naive solution to this problem which just makes a dictionary with the |
|
1702 | A naive solution to this problem which just makes a dictionary with the | |
1700 | elements as keys fails to respect the stability condition, since |
|
1703 | elements as keys fails to respect the stability condition, since | |
1701 | dictionaries are unsorted by nature. |
|
1704 | dictionaries are unsorted by nature. | |
1702 |
|
1705 | |||
1703 | Note: All elements in the input must be valid dictionary keys for this |
|
1706 | Note: All elements in the input must be valid dictionary keys for this | |
1704 | routine to work, as it internally uses a dictionary for efficiency |
|
1707 | routine to work, as it internally uses a dictionary for efficiency | |
1705 | reasons.""" |
|
1708 | reasons.""" | |
1706 |
|
1709 | |||
1707 | unique = [] |
|
1710 | unique = [] | |
1708 | unique_dict = {} |
|
1711 | unique_dict = {} | |
1709 | for nn in elems: |
|
1712 | for nn in elems: | |
1710 | if nn not in unique_dict: |
|
1713 | if nn not in unique_dict: | |
1711 | unique.append(nn) |
|
1714 | unique.append(nn) | |
1712 | unique_dict[nn] = None |
|
1715 | unique_dict[nn] = None | |
1713 | return unique |
|
1716 | return unique | |
1714 |
|
1717 | |||
1715 | #---------------------------------------------------------------------------- |
|
1718 | #---------------------------------------------------------------------------- | |
1716 | class NLprinter: |
|
1719 | class NLprinter: | |
1717 | """Print an arbitrarily nested list, indicating index numbers. |
|
1720 | """Print an arbitrarily nested list, indicating index numbers. | |
1718 |
|
1721 | |||
1719 | An instance of this class called nlprint is available and callable as a |
|
1722 | An instance of this class called nlprint is available and callable as a | |
1720 | function. |
|
1723 | function. | |
1721 |
|
1724 | |||
1722 | nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent' |
|
1725 | nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent' | |
1723 | and using 'sep' to separate the index from the value. """ |
|
1726 | and using 'sep' to separate the index from the value. """ | |
1724 |
|
1727 | |||
1725 | def __init__(self): |
|
1728 | def __init__(self): | |
1726 | self.depth = 0 |
|
1729 | self.depth = 0 | |
1727 |
|
1730 | |||
1728 | def __call__(self,lst,pos='',**kw): |
|
1731 | def __call__(self,lst,pos='',**kw): | |
1729 | """Prints the nested list numbering levels.""" |
|
1732 | """Prints the nested list numbering levels.""" | |
1730 | kw.setdefault('indent',' ') |
|
1733 | kw.setdefault('indent',' ') | |
1731 | kw.setdefault('sep',': ') |
|
1734 | kw.setdefault('sep',': ') | |
1732 | kw.setdefault('start',0) |
|
1735 | kw.setdefault('start',0) | |
1733 | kw.setdefault('stop',len(lst)) |
|
1736 | kw.setdefault('stop',len(lst)) | |
1734 | # we need to remove start and stop from kw so they don't propagate |
|
1737 | # we need to remove start and stop from kw so they don't propagate | |
1735 | # into a recursive call for a nested list. |
|
1738 | # into a recursive call for a nested list. | |
1736 | start = kw['start']; del kw['start'] |
|
1739 | start = kw['start']; del kw['start'] | |
1737 | stop = kw['stop']; del kw['stop'] |
|
1740 | stop = kw['stop']; del kw['stop'] | |
1738 | if self.depth == 0 and 'header' in kw.keys(): |
|
1741 | if self.depth == 0 and 'header' in kw.keys(): | |
1739 | print kw['header'] |
|
1742 | print kw['header'] | |
1740 |
|
1743 | |||
1741 | for idx in range(start,stop): |
|
1744 | for idx in range(start,stop): | |
1742 | elem = lst[idx] |
|
1745 | elem = lst[idx] | |
1743 | if type(elem)==type([]): |
|
1746 | if type(elem)==type([]): | |
1744 | self.depth += 1 |
|
1747 | self.depth += 1 | |
1745 | self.__call__(elem,itpl('$pos$idx,'),**kw) |
|
1748 | self.__call__(elem,itpl('$pos$idx,'),**kw) | |
1746 | self.depth -= 1 |
|
1749 | self.depth -= 1 | |
1747 | else: |
|
1750 | else: | |
1748 | printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem') |
|
1751 | printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem') | |
1749 |
|
1752 | |||
1750 | nlprint = NLprinter() |
|
1753 | nlprint = NLprinter() | |
1751 | #---------------------------------------------------------------------------- |
|
1754 | #---------------------------------------------------------------------------- | |
1752 | def all_belong(candidates,checklist): |
|
1755 | def all_belong(candidates,checklist): | |
1753 | """Check whether a list of items ALL appear in a given list of options. |
|
1756 | """Check whether a list of items ALL appear in a given list of options. | |
1754 |
|
1757 | |||
1755 | Returns a single 1 or 0 value.""" |
|
1758 | Returns a single 1 or 0 value.""" | |
1756 |
|
1759 | |||
1757 | return 1-(0 in [x in checklist for x in candidates]) |
|
1760 | return 1-(0 in [x in checklist for x in candidates]) | |
1758 |
|
1761 | |||
1759 | #---------------------------------------------------------------------------- |
|
1762 | #---------------------------------------------------------------------------- | |
1760 | def sort_compare(lst1,lst2,inplace = 1): |
|
1763 | def sort_compare(lst1,lst2,inplace = 1): | |
1761 | """Sort and compare two lists. |
|
1764 | """Sort and compare two lists. | |
1762 |
|
1765 | |||
1763 | By default it does it in place, thus modifying the lists. Use inplace = 0 |
|
1766 | By default it does it in place, thus modifying the lists. Use inplace = 0 | |
1764 | to avoid that (at the cost of temporary copy creation).""" |
|
1767 | to avoid that (at the cost of temporary copy creation).""" | |
1765 | if not inplace: |
|
1768 | if not inplace: | |
1766 | lst1 = lst1[:] |
|
1769 | lst1 = lst1[:] | |
1767 | lst2 = lst2[:] |
|
1770 | lst2 = lst2[:] | |
1768 | lst1.sort(); lst2.sort() |
|
1771 | lst1.sort(); lst2.sort() | |
1769 | return lst1 == lst2 |
|
1772 | return lst1 == lst2 | |
1770 |
|
1773 | |||
1771 | #---------------------------------------------------------------------------- |
|
1774 | #---------------------------------------------------------------------------- | |
1772 | def mkdict(**kwargs): |
|
1775 | def mkdict(**kwargs): | |
1773 | """Return a dict from a keyword list. |
|
1776 | """Return a dict from a keyword list. | |
1774 |
|
1777 | |||
1775 | It's just syntactic sugar for making ditcionary creation more convenient: |
|
1778 | It's just syntactic sugar for making ditcionary creation more convenient: | |
1776 | # the standard way |
|
1779 | # the standard way | |
1777 | >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 } |
|
1780 | >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 } | |
1778 | # a cleaner way |
|
1781 | # a cleaner way | |
1779 | >>>data = dict(red=1, green=2, blue=3) |
|
1782 | >>>data = dict(red=1, green=2, blue=3) | |
1780 |
|
1783 | |||
1781 | If you need more than this, look at the Struct() class.""" |
|
1784 | If you need more than this, look at the Struct() class.""" | |
1782 |
|
1785 | |||
1783 | return kwargs |
|
1786 | return kwargs | |
1784 |
|
1787 | |||
1785 | #---------------------------------------------------------------------------- |
|
1788 | #---------------------------------------------------------------------------- | |
1786 | def list2dict(lst): |
|
1789 | def list2dict(lst): | |
1787 | """Takes a list of (key,value) pairs and turns it into a dict.""" |
|
1790 | """Takes a list of (key,value) pairs and turns it into a dict.""" | |
1788 |
|
1791 | |||
1789 | dic = {} |
|
1792 | dic = {} | |
1790 | for k,v in lst: dic[k] = v |
|
1793 | for k,v in lst: dic[k] = v | |
1791 | return dic |
|
1794 | return dic | |
1792 |
|
1795 | |||
1793 | #---------------------------------------------------------------------------- |
|
1796 | #---------------------------------------------------------------------------- | |
1794 | def list2dict2(lst,default=''): |
|
1797 | def list2dict2(lst,default=''): | |
1795 | """Takes a list and turns it into a dict. |
|
1798 | """Takes a list and turns it into a dict. | |
1796 | Much slower than list2dict, but more versatile. This version can take |
|
1799 | Much slower than list2dict, but more versatile. This version can take | |
1797 | lists with sublists of arbitrary length (including sclars).""" |
|
1800 | lists with sublists of arbitrary length (including sclars).""" | |
1798 |
|
1801 | |||
1799 | dic = {} |
|
1802 | dic = {} | |
1800 | for elem in lst: |
|
1803 | for elem in lst: | |
1801 | if type(elem) in (types.ListType,types.TupleType): |
|
1804 | if type(elem) in (types.ListType,types.TupleType): | |
1802 | size = len(elem) |
|
1805 | size = len(elem) | |
1803 | if size == 0: |
|
1806 | if size == 0: | |
1804 | pass |
|
1807 | pass | |
1805 | elif size == 1: |
|
1808 | elif size == 1: | |
1806 | dic[elem] = default |
|
1809 | dic[elem] = default | |
1807 | else: |
|
1810 | else: | |
1808 | k,v = elem[0], elem[1:] |
|
1811 | k,v = elem[0], elem[1:] | |
1809 | if len(v) == 1: v = v[0] |
|
1812 | if len(v) == 1: v = v[0] | |
1810 | dic[k] = v |
|
1813 | dic[k] = v | |
1811 | else: |
|
1814 | else: | |
1812 | dic[elem] = default |
|
1815 | dic[elem] = default | |
1813 | return dic |
|
1816 | return dic | |
1814 |
|
1817 | |||
1815 | #---------------------------------------------------------------------------- |
|
1818 | #---------------------------------------------------------------------------- | |
1816 | def flatten(seq): |
|
1819 | def flatten(seq): | |
1817 | """Flatten a list of lists (NOT recursive, only works for 2d lists).""" |
|
1820 | """Flatten a list of lists (NOT recursive, only works for 2d lists).""" | |
1818 |
|
1821 | |||
1819 | return [x for subseq in seq for x in subseq] |
|
1822 | return [x for subseq in seq for x in subseq] | |
1820 |
|
1823 | |||
1821 | #---------------------------------------------------------------------------- |
|
1824 | #---------------------------------------------------------------------------- | |
1822 | def get_slice(seq,start=0,stop=None,step=1): |
|
1825 | def get_slice(seq,start=0,stop=None,step=1): | |
1823 | """Get a slice of a sequence with variable step. Specify start,stop,step.""" |
|
1826 | """Get a slice of a sequence with variable step. Specify start,stop,step.""" | |
1824 | if stop == None: |
|
1827 | if stop == None: | |
1825 | stop = len(seq) |
|
1828 | stop = len(seq) | |
1826 | item = lambda i: seq[i] |
|
1829 | item = lambda i: seq[i] | |
1827 | return map(item,xrange(start,stop,step)) |
|
1830 | return map(item,xrange(start,stop,step)) | |
1828 |
|
1831 | |||
1829 | #---------------------------------------------------------------------------- |
|
1832 | #---------------------------------------------------------------------------- | |
1830 | def chop(seq,size): |
|
1833 | def chop(seq,size): | |
1831 | """Chop a sequence into chunks of the given size.""" |
|
1834 | """Chop a sequence into chunks of the given size.""" | |
1832 | chunk = lambda i: seq[i:i+size] |
|
1835 | chunk = lambda i: seq[i:i+size] | |
1833 | return map(chunk,xrange(0,len(seq),size)) |
|
1836 | return map(chunk,xrange(0,len(seq),size)) | |
1834 |
|
1837 | |||
1835 | #---------------------------------------------------------------------------- |
|
1838 | #---------------------------------------------------------------------------- | |
1836 | # with is a keyword as of python 2.5, so this function is renamed to withobj |
|
1839 | # with is a keyword as of python 2.5, so this function is renamed to withobj | |
1837 | # from its old 'with' name. |
|
1840 | # from its old 'with' name. | |
1838 | def with_obj(object, **args): |
|
1841 | def with_obj(object, **args): | |
1839 | """Set multiple attributes for an object, similar to Pascal's with. |
|
1842 | """Set multiple attributes for an object, similar to Pascal's with. | |
1840 |
|
1843 | |||
1841 | Example: |
|
1844 | Example: | |
1842 | with_obj(jim, |
|
1845 | with_obj(jim, | |
1843 | born = 1960, |
|
1846 | born = 1960, | |
1844 | haircolour = 'Brown', |
|
1847 | haircolour = 'Brown', | |
1845 | eyecolour = 'Green') |
|
1848 | eyecolour = 'Green') | |
1846 |
|
1849 | |||
1847 | Credit: Greg Ewing, in |
|
1850 | Credit: Greg Ewing, in | |
1848 | http://mail.python.org/pipermail/python-list/2001-May/040703.html. |
|
1851 | http://mail.python.org/pipermail/python-list/2001-May/040703.html. | |
1849 |
|
1852 | |||
1850 | NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with' |
|
1853 | NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with' | |
1851 | has become a keyword for Python 2.5, so we had to rename it.""" |
|
1854 | has become a keyword for Python 2.5, so we had to rename it.""" | |
1852 |
|
1855 | |||
1853 | object.__dict__.update(args) |
|
1856 | object.__dict__.update(args) | |
1854 |
|
1857 | |||
1855 | #---------------------------------------------------------------------------- |
|
1858 | #---------------------------------------------------------------------------- | |
1856 | def setattr_list(obj,alist,nspace = None): |
|
1859 | def setattr_list(obj,alist,nspace = None): | |
1857 | """Set a list of attributes for an object taken from a namespace. |
|
1860 | """Set a list of attributes for an object taken from a namespace. | |
1858 |
|
1861 | |||
1859 | setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in |
|
1862 | setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in | |
1860 | alist with their values taken from nspace, which must be a dict (something |
|
1863 | alist with their values taken from nspace, which must be a dict (something | |
1861 | like locals() will often do) If nspace isn't given, locals() of the |
|
1864 | like locals() will often do) If nspace isn't given, locals() of the | |
1862 | *caller* is used, so in most cases you can omit it. |
|
1865 | *caller* is used, so in most cases you can omit it. | |
1863 |
|
1866 | |||
1864 | Note that alist can be given as a string, which will be automatically |
|
1867 | Note that alist can be given as a string, which will be automatically | |
1865 | split into a list on whitespace. If given as a list, it must be a list of |
|
1868 | split into a list on whitespace. If given as a list, it must be a list of | |
1866 | *strings* (the variable names themselves), not of variables.""" |
|
1869 | *strings* (the variable names themselves), not of variables.""" | |
1867 |
|
1870 | |||
1868 | # this grabs the local variables from the *previous* call frame -- that is |
|
1871 | # this grabs the local variables from the *previous* call frame -- that is | |
1869 | # the locals from the function that called setattr_list(). |
|
1872 | # the locals from the function that called setattr_list(). | |
1870 | # - snipped from weave.inline() |
|
1873 | # - snipped from weave.inline() | |
1871 | if nspace is None: |
|
1874 | if nspace is None: | |
1872 | call_frame = sys._getframe().f_back |
|
1875 | call_frame = sys._getframe().f_back | |
1873 | nspace = call_frame.f_locals |
|
1876 | nspace = call_frame.f_locals | |
1874 |
|
1877 | |||
1875 | if type(alist) in StringTypes: |
|
1878 | if type(alist) in StringTypes: | |
1876 | alist = alist.split() |
|
1879 | alist = alist.split() | |
1877 | for attr in alist: |
|
1880 | for attr in alist: | |
1878 | val = eval(attr,nspace) |
|
1881 | val = eval(attr,nspace) | |
1879 | setattr(obj,attr,val) |
|
1882 | setattr(obj,attr,val) | |
1880 |
|
1883 | |||
1881 | #---------------------------------------------------------------------------- |
|
1884 | #---------------------------------------------------------------------------- | |
1882 | def getattr_list(obj,alist,*args): |
|
1885 | def getattr_list(obj,alist,*args): | |
1883 | """getattr_list(obj,alist[, default]) -> attribute list. |
|
1886 | """getattr_list(obj,alist[, default]) -> attribute list. | |
1884 |
|
1887 | |||
1885 | Get a list of named attributes for an object. When a default argument is |
|
1888 | Get a list of named attributes for an object. When a default argument is | |
1886 | given, it is returned when the attribute doesn't exist; without it, an |
|
1889 | given, it is returned when the attribute doesn't exist; without it, an | |
1887 | exception is raised in that case. |
|
1890 | exception is raised in that case. | |
1888 |
|
1891 | |||
1889 | Note that alist can be given as a string, which will be automatically |
|
1892 | Note that alist can be given as a string, which will be automatically | |
1890 | split into a list on whitespace. If given as a list, it must be a list of |
|
1893 | split into a list on whitespace. If given as a list, it must be a list of | |
1891 | *strings* (the variable names themselves), not of variables.""" |
|
1894 | *strings* (the variable names themselves), not of variables.""" | |
1892 |
|
1895 | |||
1893 | if type(alist) in StringTypes: |
|
1896 | if type(alist) in StringTypes: | |
1894 | alist = alist.split() |
|
1897 | alist = alist.split() | |
1895 | if args: |
|
1898 | if args: | |
1896 | if len(args)==1: |
|
1899 | if len(args)==1: | |
1897 | default = args[0] |
|
1900 | default = args[0] | |
1898 | return map(lambda attr: getattr(obj,attr,default),alist) |
|
1901 | return map(lambda attr: getattr(obj,attr,default),alist) | |
1899 | else: |
|
1902 | else: | |
1900 | raise ValueError,'getattr_list() takes only one optional argument' |
|
1903 | raise ValueError,'getattr_list() takes only one optional argument' | |
1901 | else: |
|
1904 | else: | |
1902 | return map(lambda attr: getattr(obj,attr),alist) |
|
1905 | return map(lambda attr: getattr(obj,attr),alist) | |
1903 |
|
1906 | |||
1904 | #---------------------------------------------------------------------------- |
|
1907 | #---------------------------------------------------------------------------- | |
1905 | def map_method(method,object_list,*argseq,**kw): |
|
1908 | def map_method(method,object_list,*argseq,**kw): | |
1906 | """map_method(method,object_list,*args,**kw) -> list |
|
1909 | """map_method(method,object_list,*args,**kw) -> list | |
1907 |
|
1910 | |||
1908 | Return a list of the results of applying the methods to the items of the |
|
1911 | Return a list of the results of applying the methods to the items of the | |
1909 | argument sequence(s). If more than one sequence is given, the method is |
|
1912 | argument sequence(s). If more than one sequence is given, the method is | |
1910 | called with an argument list consisting of the corresponding item of each |
|
1913 | called with an argument list consisting of the corresponding item of each | |
1911 | sequence. All sequences must be of the same length. |
|
1914 | sequence. All sequences must be of the same length. | |
1912 |
|
1915 | |||
1913 | Keyword arguments are passed verbatim to all objects called. |
|
1916 | Keyword arguments are passed verbatim to all objects called. | |
1914 |
|
1917 | |||
1915 | This is Python code, so it's not nearly as fast as the builtin map().""" |
|
1918 | This is Python code, so it's not nearly as fast as the builtin map().""" | |
1916 |
|
1919 | |||
1917 | out_list = [] |
|
1920 | out_list = [] | |
1918 | idx = 0 |
|
1921 | idx = 0 | |
1919 | for object in object_list: |
|
1922 | for object in object_list: | |
1920 | try: |
|
1923 | try: | |
1921 | handler = getattr(object, method) |
|
1924 | handler = getattr(object, method) | |
1922 | except AttributeError: |
|
1925 | except AttributeError: | |
1923 | out_list.append(None) |
|
1926 | out_list.append(None) | |
1924 | else: |
|
1927 | else: | |
1925 | if argseq: |
|
1928 | if argseq: | |
1926 | args = map(lambda lst:lst[idx],argseq) |
|
1929 | args = map(lambda lst:lst[idx],argseq) | |
1927 | #print 'ob',object,'hand',handler,'ar',args # dbg |
|
1930 | #print 'ob',object,'hand',handler,'ar',args # dbg | |
1928 | out_list.append(handler(args,**kw)) |
|
1931 | out_list.append(handler(args,**kw)) | |
1929 | else: |
|
1932 | else: | |
1930 | out_list.append(handler(**kw)) |
|
1933 | out_list.append(handler(**kw)) | |
1931 | idx += 1 |
|
1934 | idx += 1 | |
1932 | return out_list |
|
1935 | return out_list | |
1933 |
|
1936 | |||
1934 | #---------------------------------------------------------------------------- |
|
1937 | #---------------------------------------------------------------------------- | |
1935 | def get_class_members(cls): |
|
1938 | def get_class_members(cls): | |
1936 | ret = dir(cls) |
|
1939 | ret = dir(cls) | |
1937 | if hasattr(cls,'__bases__'): |
|
1940 | if hasattr(cls,'__bases__'): | |
1938 | for base in cls.__bases__: |
|
1941 | for base in cls.__bases__: | |
1939 | ret.extend(get_class_members(base)) |
|
1942 | ret.extend(get_class_members(base)) | |
1940 | return ret |
|
1943 | return ret | |
1941 |
|
1944 | |||
1942 | #---------------------------------------------------------------------------- |
|
1945 | #---------------------------------------------------------------------------- | |
1943 | def dir2(obj): |
|
1946 | def dir2(obj): | |
1944 | """dir2(obj) -> list of strings |
|
1947 | """dir2(obj) -> list of strings | |
1945 |
|
1948 | |||
1946 | Extended version of the Python builtin dir(), which does a few extra |
|
1949 | Extended version of the Python builtin dir(), which does a few extra | |
1947 | checks, and supports common objects with unusual internals that confuse |
|
1950 | checks, and supports common objects with unusual internals that confuse | |
1948 | dir(), such as Traits and PyCrust. |
|
1951 | dir(), such as Traits and PyCrust. | |
1949 |
|
1952 | |||
1950 | This version is guaranteed to return only a list of true strings, whereas |
|
1953 | This version is guaranteed to return only a list of true strings, whereas | |
1951 | dir() returns anything that objects inject into themselves, even if they |
|
1954 | dir() returns anything that objects inject into themselves, even if they | |
1952 | are later not really valid for attribute access (many extension libraries |
|
1955 | are later not really valid for attribute access (many extension libraries | |
1953 | have such bugs). |
|
1956 | have such bugs). | |
1954 | """ |
|
1957 | """ | |
1955 |
|
1958 | |||
1956 | # Start building the attribute list via dir(), and then complete it |
|
1959 | # Start building the attribute list via dir(), and then complete it | |
1957 | # with a few extra special-purpose calls. |
|
1960 | # with a few extra special-purpose calls. | |
1958 | words = dir(obj) |
|
1961 | words = dir(obj) | |
1959 |
|
1962 | |||
1960 | if hasattr(obj,'__class__'): |
|
1963 | if hasattr(obj,'__class__'): | |
1961 | words.append('__class__') |
|
1964 | words.append('__class__') | |
1962 | words.extend(get_class_members(obj.__class__)) |
|
1965 | words.extend(get_class_members(obj.__class__)) | |
1963 | #if '__base__' in words: 1/0 |
|
1966 | #if '__base__' in words: 1/0 | |
1964 |
|
1967 | |||
1965 | # Some libraries (such as traits) may introduce duplicates, we want to |
|
1968 | # Some libraries (such as traits) may introduce duplicates, we want to | |
1966 | # track and clean this up if it happens |
|
1969 | # track and clean this up if it happens | |
1967 | may_have_dupes = False |
|
1970 | may_have_dupes = False | |
1968 |
|
1971 | |||
1969 | # this is the 'dir' function for objects with Enthought's traits |
|
1972 | # this is the 'dir' function for objects with Enthought's traits | |
1970 | if hasattr(obj, 'trait_names'): |
|
1973 | if hasattr(obj, 'trait_names'): | |
1971 | try: |
|
1974 | try: | |
1972 | words.extend(obj.trait_names()) |
|
1975 | words.extend(obj.trait_names()) | |
1973 | may_have_dupes = True |
|
1976 | may_have_dupes = True | |
1974 | except TypeError: |
|
1977 | except TypeError: | |
1975 | # This will happen if `obj` is a class and not an instance. |
|
1978 | # This will happen if `obj` is a class and not an instance. | |
1976 | pass |
|
1979 | pass | |
1977 |
|
1980 | |||
1978 | # Support for PyCrust-style _getAttributeNames magic method. |
|
1981 | # Support for PyCrust-style _getAttributeNames magic method. | |
1979 | if hasattr(obj, '_getAttributeNames'): |
|
1982 | if hasattr(obj, '_getAttributeNames'): | |
1980 | try: |
|
1983 | try: | |
1981 | words.extend(obj._getAttributeNames()) |
|
1984 | words.extend(obj._getAttributeNames()) | |
1982 | may_have_dupes = True |
|
1985 | may_have_dupes = True | |
1983 | except TypeError: |
|
1986 | except TypeError: | |
1984 | # `obj` is a class and not an instance. Ignore |
|
1987 | # `obj` is a class and not an instance. Ignore | |
1985 | # this error. |
|
1988 | # this error. | |
1986 | pass |
|
1989 | pass | |
1987 |
|
1990 | |||
1988 | if may_have_dupes: |
|
1991 | if may_have_dupes: | |
1989 | # eliminate possible duplicates, as some traits may also |
|
1992 | # eliminate possible duplicates, as some traits may also | |
1990 | # appear as normal attributes in the dir() call. |
|
1993 | # appear as normal attributes in the dir() call. | |
1991 | words = list(set(words)) |
|
1994 | words = list(set(words)) | |
1992 | words.sort() |
|
1995 | words.sort() | |
1993 |
|
1996 | |||
1994 | # filter out non-string attributes which may be stuffed by dir() calls |
|
1997 | # filter out non-string attributes which may be stuffed by dir() calls | |
1995 | # and poor coding in third-party modules |
|
1998 | # and poor coding in third-party modules | |
1996 | return [w for w in words if isinstance(w, basestring)] |
|
1999 | return [w for w in words if isinstance(w, basestring)] | |
1997 |
|
2000 | |||
1998 | #---------------------------------------------------------------------------- |
|
2001 | #---------------------------------------------------------------------------- | |
1999 | def import_fail_info(mod_name,fns=None): |
|
2002 | def import_fail_info(mod_name,fns=None): | |
2000 | """Inform load failure for a module.""" |
|
2003 | """Inform load failure for a module.""" | |
2001 |
|
2004 | |||
2002 | if fns == None: |
|
2005 | if fns == None: | |
2003 | warn("Loading of %s failed.\n" % (mod_name,)) |
|
2006 | warn("Loading of %s failed.\n" % (mod_name,)) | |
2004 | else: |
|
2007 | else: | |
2005 | warn("Loading of %s from %s failed.\n" % (fns,mod_name)) |
|
2008 | warn("Loading of %s from %s failed.\n" % (fns,mod_name)) | |
2006 |
|
2009 | |||
2007 | #---------------------------------------------------------------------------- |
|
2010 | #---------------------------------------------------------------------------- | |
2008 | # Proposed popitem() extension, written as a method |
|
2011 | # Proposed popitem() extension, written as a method | |
2009 |
|
2012 | |||
2010 |
|
2013 | |||
2011 | class NotGiven: pass |
|
2014 | class NotGiven: pass | |
2012 |
|
2015 | |||
2013 | def popkey(dct,key,default=NotGiven): |
|
2016 | def popkey(dct,key,default=NotGiven): | |
2014 | """Return dct[key] and delete dct[key]. |
|
2017 | """Return dct[key] and delete dct[key]. | |
2015 |
|
2018 | |||
2016 | If default is given, return it if dct[key] doesn't exist, otherwise raise |
|
2019 | If default is given, return it if dct[key] doesn't exist, otherwise raise | |
2017 | KeyError. """ |
|
2020 | KeyError. """ | |
2018 |
|
2021 | |||
2019 | try: |
|
2022 | try: | |
2020 | val = dct[key] |
|
2023 | val = dct[key] | |
2021 | except KeyError: |
|
2024 | except KeyError: | |
2022 | if default is NotGiven: |
|
2025 | if default is NotGiven: | |
2023 | raise |
|
2026 | raise | |
2024 | else: |
|
2027 | else: | |
2025 | return default |
|
2028 | return default | |
2026 | else: |
|
2029 | else: | |
2027 | del dct[key] |
|
2030 | del dct[key] | |
2028 | return val |
|
2031 | return val | |
2029 |
|
2032 | |||
2030 | def wrap_deprecated(func, suggest = '<nothing>'): |
|
2033 | def wrap_deprecated(func, suggest = '<nothing>'): | |
2031 | def newFunc(*args, **kwargs): |
|
2034 | def newFunc(*args, **kwargs): | |
2032 | warnings.warn("Call to deprecated function %s, use %s instead" % |
|
2035 | warnings.warn("Call to deprecated function %s, use %s instead" % | |
2033 | ( func.__name__, suggest), |
|
2036 | ( func.__name__, suggest), | |
2034 | category=DeprecationWarning, |
|
2037 | category=DeprecationWarning, | |
2035 | stacklevel = 2) |
|
2038 | stacklevel = 2) | |
2036 | return func(*args, **kwargs) |
|
2039 | return func(*args, **kwargs) | |
2037 | return newFunc |
|
2040 | return newFunc | |
2038 |
|
2041 | |||
2039 | #*************************** end of file <genutils.py> ********************** |
|
2042 | #*************************** end of file <genutils.py> ********************** | |
2040 |
|
2043 |
@@ -1,2683 +1,2686 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | IPython -- An enhanced Interactive Python |
|
3 | IPython -- An enhanced Interactive Python | |
4 |
|
4 | |||
5 | Requires Python 2.3 or newer. |
|
5 | Requires Python 2.3 or newer. | |
6 |
|
6 | |||
7 | This file contains all the classes and helper functions specific to IPython. |
|
7 | This file contains all the classes and helper functions specific to IPython. | |
8 |
|
8 | |||
9 | """ |
|
9 | """ | |
10 |
|
10 | |||
11 | #***************************************************************************** |
|
11 | #***************************************************************************** | |
12 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
12 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
13 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
13 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> | |
14 | # |
|
14 | # | |
15 | # Distributed under the terms of the BSD License. The full license is in |
|
15 | # Distributed under the terms of the BSD License. The full license is in | |
16 | # the file COPYING, distributed as part of this software. |
|
16 | # the file COPYING, distributed as part of this software. | |
17 | # |
|
17 | # | |
18 | # Note: this code originally subclassed code.InteractiveConsole from the |
|
18 | # Note: this code originally subclassed code.InteractiveConsole from the | |
19 | # Python standard library. Over time, all of that class has been copied |
|
19 | # Python standard library. Over time, all of that class has been copied | |
20 | # verbatim here for modifications which could not be accomplished by |
|
20 | # verbatim here for modifications which could not be accomplished by | |
21 | # subclassing. At this point, there are no dependencies at all on the code |
|
21 | # subclassing. At this point, there are no dependencies at all on the code | |
22 | # module anymore (it is not even imported). The Python License (sec. 2) |
|
22 | # module anymore (it is not even imported). The Python License (sec. 2) | |
23 | # allows for this, but it's always nice to acknowledge credit where credit is |
|
23 | # allows for this, but it's always nice to acknowledge credit where credit is | |
24 | # due. |
|
24 | # due. | |
25 | #***************************************************************************** |
|
25 | #***************************************************************************** | |
26 |
|
26 | |||
27 | #**************************************************************************** |
|
27 | #**************************************************************************** | |
28 | # Modules and globals |
|
28 | # Modules and globals | |
29 |
|
29 | |||
30 | from IPython import Release |
|
30 | from IPython import Release | |
31 | __author__ = '%s <%s>\n%s <%s>' % \ |
|
31 | __author__ = '%s <%s>\n%s <%s>' % \ | |
32 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) |
|
32 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) | |
33 | __license__ = Release.license |
|
33 | __license__ = Release.license | |
34 | __version__ = Release.version |
|
34 | __version__ = Release.version | |
35 |
|
35 | |||
36 | # Python standard modules |
|
36 | # Python standard modules | |
37 | import __main__ |
|
37 | import __main__ | |
38 | import __builtin__ |
|
38 | import __builtin__ | |
39 | import StringIO |
|
39 | import StringIO | |
40 | import bdb |
|
40 | import bdb | |
41 | import cPickle as pickle |
|
41 | import cPickle as pickle | |
42 | import codeop |
|
42 | import codeop | |
43 | import exceptions |
|
43 | import exceptions | |
44 | import glob |
|
44 | import glob | |
45 | import inspect |
|
45 | import inspect | |
46 | import keyword |
|
46 | import keyword | |
47 | import new |
|
47 | import new | |
48 | import os |
|
48 | import os | |
49 | import pydoc |
|
49 | import pydoc | |
50 | import re |
|
50 | import re | |
51 | import shutil |
|
51 | import shutil | |
52 | import string |
|
52 | import string | |
53 | import sys |
|
53 | import sys | |
54 | import tempfile |
|
54 | import tempfile | |
55 | import traceback |
|
55 | import traceback | |
56 | import types |
|
56 | import types | |
57 | import warnings |
|
57 | import warnings | |
58 | warnings.filterwarnings('ignore', r'.*sets module*') |
|
58 | warnings.filterwarnings('ignore', r'.*sets module*') | |
59 | from sets import Set |
|
59 | from sets import Set | |
60 | from pprint import pprint, pformat |
|
60 | from pprint import pprint, pformat | |
61 |
|
61 | |||
62 | # IPython's own modules |
|
62 | # IPython's own modules | |
63 | #import IPython |
|
63 | #import IPython | |
64 | from IPython import Debugger,OInspect,PyColorize,ultraTB |
|
64 | from IPython import Debugger,OInspect,PyColorize,ultraTB | |
65 | from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names |
|
65 | from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names | |
66 | from IPython.Extensions import pickleshare |
|
66 | from IPython.Extensions import pickleshare | |
67 | from IPython.FakeModule import FakeModule |
|
67 | from IPython.FakeModule import FakeModule | |
68 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns |
|
68 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns | |
69 | from IPython.Logger import Logger |
|
69 | from IPython.Logger import Logger | |
70 | from IPython.Magic import Magic |
|
70 | from IPython.Magic import Magic | |
71 | from IPython.Prompts import CachedOutput |
|
71 | from IPython.Prompts import CachedOutput | |
72 | from IPython.ipstruct import Struct |
|
72 | from IPython.ipstruct import Struct | |
73 | from IPython.background_jobs import BackgroundJobManager |
|
73 | from IPython.background_jobs import BackgroundJobManager | |
74 | from IPython.usage import cmd_line_usage,interactive_usage |
|
74 | from IPython.usage import cmd_line_usage,interactive_usage | |
75 | from IPython.genutils import * |
|
75 | from IPython.genutils import * | |
76 | from IPython.strdispatch import StrDispatch |
|
76 | from IPython.strdispatch import StrDispatch | |
77 | import IPython.ipapi |
|
77 | import IPython.ipapi | |
78 | import IPython.history |
|
78 | import IPython.history | |
79 | import IPython.prefilter as prefilter |
|
79 | import IPython.prefilter as prefilter | |
80 | import IPython.shadowns |
|
80 | import IPython.shadowns | |
81 | # Globals |
|
81 | # Globals | |
82 |
|
82 | |||
83 | # store the builtin raw_input globally, and use this always, in case user code |
|
83 | # store the builtin raw_input globally, and use this always, in case user code | |
84 | # overwrites it (like wx.py.PyShell does) |
|
84 | # overwrites it (like wx.py.PyShell does) | |
85 | raw_input_original = raw_input |
|
85 | raw_input_original = raw_input | |
86 |
|
86 | |||
87 | # compiled regexps for autoindent management |
|
87 | # compiled regexps for autoindent management | |
88 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
88 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
89 |
|
89 | |||
90 |
|
90 | |||
91 | #**************************************************************************** |
|
91 | #**************************************************************************** | |
92 | # Some utility function definitions |
|
92 | # Some utility function definitions | |
93 |
|
93 | |||
94 | ini_spaces_re = re.compile(r'^(\s+)') |
|
94 | ini_spaces_re = re.compile(r'^(\s+)') | |
95 |
|
95 | |||
96 | def num_ini_spaces(strng): |
|
96 | def num_ini_spaces(strng): | |
97 | """Return the number of initial spaces in a string""" |
|
97 | """Return the number of initial spaces in a string""" | |
98 |
|
98 | |||
99 | ini_spaces = ini_spaces_re.match(strng) |
|
99 | ini_spaces = ini_spaces_re.match(strng) | |
100 | if ini_spaces: |
|
100 | if ini_spaces: | |
101 | return ini_spaces.end() |
|
101 | return ini_spaces.end() | |
102 | else: |
|
102 | else: | |
103 | return 0 |
|
103 | return 0 | |
104 |
|
104 | |||
105 | def softspace(file, newvalue): |
|
105 | def softspace(file, newvalue): | |
106 | """Copied from code.py, to remove the dependency""" |
|
106 | """Copied from code.py, to remove the dependency""" | |
107 |
|
107 | |||
108 | oldvalue = 0 |
|
108 | oldvalue = 0 | |
109 | try: |
|
109 | try: | |
110 | oldvalue = file.softspace |
|
110 | oldvalue = file.softspace | |
111 | except AttributeError: |
|
111 | except AttributeError: | |
112 | pass |
|
112 | pass | |
113 | try: |
|
113 | try: | |
114 | file.softspace = newvalue |
|
114 | file.softspace = newvalue | |
115 | except (AttributeError, TypeError): |
|
115 | except (AttributeError, TypeError): | |
116 | # "attribute-less object" or "read-only attributes" |
|
116 | # "attribute-less object" or "read-only attributes" | |
117 | pass |
|
117 | pass | |
118 | return oldvalue |
|
118 | return oldvalue | |
119 |
|
119 | |||
120 |
|
120 | |||
121 | #**************************************************************************** |
|
121 | #**************************************************************************** | |
122 | # Local use exceptions |
|
122 | # Local use exceptions | |
123 | class SpaceInInput(exceptions.Exception): pass |
|
123 | class SpaceInInput(exceptions.Exception): pass | |
124 |
|
124 | |||
125 |
|
125 | |||
126 | #**************************************************************************** |
|
126 | #**************************************************************************** | |
127 | # Local use classes |
|
127 | # Local use classes | |
128 | class Bunch: pass |
|
128 | class Bunch: pass | |
129 |
|
129 | |||
130 | class Undefined: pass |
|
130 | class Undefined: pass | |
131 |
|
131 | |||
132 | class Quitter(object): |
|
132 | class Quitter(object): | |
133 | """Simple class to handle exit, similar to Python 2.5's. |
|
133 | """Simple class to handle exit, similar to Python 2.5's. | |
134 |
|
134 | |||
135 | It handles exiting in an ipython-safe manner, which the one in Python 2.5 |
|
135 | It handles exiting in an ipython-safe manner, which the one in Python 2.5 | |
136 | doesn't do (obviously, since it doesn't know about ipython).""" |
|
136 | doesn't do (obviously, since it doesn't know about ipython).""" | |
137 |
|
137 | |||
138 | def __init__(self,shell,name): |
|
138 | def __init__(self,shell,name): | |
139 | self.shell = shell |
|
139 | self.shell = shell | |
140 | self.name = name |
|
140 | self.name = name | |
141 |
|
141 | |||
142 | def __repr__(self): |
|
142 | def __repr__(self): | |
143 | return 'Type %s() to exit.' % self.name |
|
143 | return 'Type %s() to exit.' % self.name | |
144 | __str__ = __repr__ |
|
144 | __str__ = __repr__ | |
145 |
|
145 | |||
146 | def __call__(self): |
|
146 | def __call__(self): | |
147 | self.shell.exit() |
|
147 | self.shell.exit() | |
148 |
|
148 | |||
149 | class InputList(list): |
|
149 | class InputList(list): | |
150 | """Class to store user input. |
|
150 | """Class to store user input. | |
151 |
|
151 | |||
152 | It's basically a list, but slices return a string instead of a list, thus |
|
152 | It's basically a list, but slices return a string instead of a list, thus | |
153 | allowing things like (assuming 'In' is an instance): |
|
153 | allowing things like (assuming 'In' is an instance): | |
154 |
|
154 | |||
155 | exec In[4:7] |
|
155 | exec In[4:7] | |
156 |
|
156 | |||
157 | or |
|
157 | or | |
158 |
|
158 | |||
159 | exec In[5:9] + In[14] + In[21:25]""" |
|
159 | exec In[5:9] + In[14] + In[21:25]""" | |
160 |
|
160 | |||
161 | def __getslice__(self,i,j): |
|
161 | def __getslice__(self,i,j): | |
162 | return ''.join(list.__getslice__(self,i,j)) |
|
162 | return ''.join(list.__getslice__(self,i,j)) | |
163 |
|
163 | |||
164 | class SyntaxTB(ultraTB.ListTB): |
|
164 | class SyntaxTB(ultraTB.ListTB): | |
165 | """Extension which holds some state: the last exception value""" |
|
165 | """Extension which holds some state: the last exception value""" | |
166 |
|
166 | |||
167 | def __init__(self,color_scheme = 'NoColor'): |
|
167 | def __init__(self,color_scheme = 'NoColor'): | |
168 | ultraTB.ListTB.__init__(self,color_scheme) |
|
168 | ultraTB.ListTB.__init__(self,color_scheme) | |
169 | self.last_syntax_error = None |
|
169 | self.last_syntax_error = None | |
170 |
|
170 | |||
171 | def __call__(self, etype, value, elist): |
|
171 | def __call__(self, etype, value, elist): | |
172 | self.last_syntax_error = value |
|
172 | self.last_syntax_error = value | |
173 | ultraTB.ListTB.__call__(self,etype,value,elist) |
|
173 | ultraTB.ListTB.__call__(self,etype,value,elist) | |
174 |
|
174 | |||
175 | def clear_err_state(self): |
|
175 | def clear_err_state(self): | |
176 | """Return the current error state and clear it""" |
|
176 | """Return the current error state and clear it""" | |
177 | e = self.last_syntax_error |
|
177 | e = self.last_syntax_error | |
178 | self.last_syntax_error = None |
|
178 | self.last_syntax_error = None | |
179 | return e |
|
179 | return e | |
180 |
|
180 | |||
181 | #**************************************************************************** |
|
181 | #**************************************************************************** | |
182 | # Main IPython class |
|
182 | # Main IPython class | |
183 |
|
183 | |||
184 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so |
|
184 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so | |
185 | # until a full rewrite is made. I've cleaned all cross-class uses of |
|
185 | # until a full rewrite is made. I've cleaned all cross-class uses of | |
186 | # attributes and methods, but too much user code out there relies on the |
|
186 | # attributes and methods, but too much user code out there relies on the | |
187 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. |
|
187 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. | |
188 | # |
|
188 | # | |
189 | # But at least now, all the pieces have been separated and we could, in |
|
189 | # But at least now, all the pieces have been separated and we could, in | |
190 | # principle, stop using the mixin. This will ease the transition to the |
|
190 | # principle, stop using the mixin. This will ease the transition to the | |
191 | # chainsaw branch. |
|
191 | # chainsaw branch. | |
192 |
|
192 | |||
193 | # For reference, the following is the list of 'self.foo' uses in the Magic |
|
193 | # For reference, the following is the list of 'self.foo' uses in the Magic | |
194 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython |
|
194 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython | |
195 | # class, to prevent clashes. |
|
195 | # class, to prevent clashes. | |
196 |
|
196 | |||
197 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', |
|
197 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', | |
198 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', |
|
198 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', | |
199 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', |
|
199 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', | |
200 | # 'self.value'] |
|
200 | # 'self.value'] | |
201 |
|
201 | |||
202 | class InteractiveShell(object,Magic): |
|
202 | class InteractiveShell(object,Magic): | |
203 | """An enhanced console for Python.""" |
|
203 | """An enhanced console for Python.""" | |
204 |
|
204 | |||
205 | # class attribute to indicate whether the class supports threads or not. |
|
205 | # class attribute to indicate whether the class supports threads or not. | |
206 | # Subclasses with thread support should override this as needed. |
|
206 | # Subclasses with thread support should override this as needed. | |
207 | isthreaded = False |
|
207 | isthreaded = False | |
208 |
|
208 | |||
209 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
209 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), | |
210 | user_ns = None,user_global_ns=None,banner2='', |
|
210 | user_ns = None,user_global_ns=None,banner2='', | |
211 | custom_exceptions=((),None),embedded=False): |
|
211 | custom_exceptions=((),None),embedded=False): | |
212 |
|
212 | |||
213 | # log system |
|
213 | # log system | |
214 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') |
|
214 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') | |
215 |
|
215 | |||
216 | # some minimal strict typechecks. For some core data structures, I |
|
216 | # some minimal strict typechecks. For some core data structures, I | |
217 | # want actual basic python types, not just anything that looks like |
|
217 | # want actual basic python types, not just anything that looks like | |
218 | # one. This is especially true for namespaces. |
|
218 | # one. This is especially true for namespaces. | |
219 | for ns in (user_ns,user_global_ns): |
|
219 | for ns in (user_ns,user_global_ns): | |
220 | if ns is not None and type(ns) != types.DictType: |
|
220 | if ns is not None and type(ns) != types.DictType: | |
221 | raise TypeError,'namespace must be a dictionary' |
|
221 | raise TypeError,'namespace must be a dictionary' | |
222 | # Job manager (for jobs run as background threads) |
|
222 | # Job manager (for jobs run as background threads) | |
223 | self.jobs = BackgroundJobManager() |
|
223 | self.jobs = BackgroundJobManager() | |
224 |
|
224 | |||
225 | # Store the actual shell's name |
|
225 | # Store the actual shell's name | |
226 | self.name = name |
|
226 | self.name = name | |
227 | self.more = False |
|
227 | self.more = False | |
228 |
|
228 | |||
229 | # We need to know whether the instance is meant for embedding, since |
|
229 | # We need to know whether the instance is meant for embedding, since | |
230 | # global/local namespaces need to be handled differently in that case |
|
230 | # global/local namespaces need to be handled differently in that case | |
231 | self.embedded = embedded |
|
231 | self.embedded = embedded | |
232 | if embedded: |
|
232 | if embedded: | |
233 | # Control variable so users can, from within the embedded instance, |
|
233 | # Control variable so users can, from within the embedded instance, | |
234 | # permanently deactivate it. |
|
234 | # permanently deactivate it. | |
235 | self.embedded_active = True |
|
235 | self.embedded_active = True | |
236 |
|
236 | |||
237 | # command compiler |
|
237 | # command compiler | |
238 | self.compile = codeop.CommandCompiler() |
|
238 | self.compile = codeop.CommandCompiler() | |
239 |
|
239 | |||
240 | # User input buffer |
|
240 | # User input buffer | |
241 | self.buffer = [] |
|
241 | self.buffer = [] | |
242 |
|
242 | |||
243 | # Default name given in compilation of code |
|
243 | # Default name given in compilation of code | |
244 | self.filename = '<ipython console>' |
|
244 | self.filename = '<ipython console>' | |
245 |
|
245 | |||
246 | # Install our own quitter instead of the builtins. For python2.3-2.4, |
|
246 | # Install our own quitter instead of the builtins. For python2.3-2.4, | |
247 | # this brings in behavior like 2.5, and for 2.5 it's identical. |
|
247 | # this brings in behavior like 2.5, and for 2.5 it's identical. | |
248 | __builtin__.exit = Quitter(self,'exit') |
|
248 | __builtin__.exit = Quitter(self,'exit') | |
249 | __builtin__.quit = Quitter(self,'quit') |
|
249 | __builtin__.quit = Quitter(self,'quit') | |
250 |
|
250 | |||
251 | # Make an empty namespace, which extension writers can rely on both |
|
251 | # Make an empty namespace, which extension writers can rely on both | |
252 | # existing and NEVER being used by ipython itself. This gives them a |
|
252 | # existing and NEVER being used by ipython itself. This gives them a | |
253 | # convenient location for storing additional information and state |
|
253 | # convenient location for storing additional information and state | |
254 | # their extensions may require, without fear of collisions with other |
|
254 | # their extensions may require, without fear of collisions with other | |
255 | # ipython names that may develop later. |
|
255 | # ipython names that may develop later. | |
256 | self.meta = Struct() |
|
256 | self.meta = Struct() | |
257 |
|
257 | |||
258 | # Create the namespace where the user will operate. user_ns is |
|
258 | # Create the namespace where the user will operate. user_ns is | |
259 | # normally the only one used, and it is passed to the exec calls as |
|
259 | # normally the only one used, and it is passed to the exec calls as | |
260 | # the locals argument. But we do carry a user_global_ns namespace |
|
260 | # the locals argument. But we do carry a user_global_ns namespace | |
261 | # given as the exec 'globals' argument, This is useful in embedding |
|
261 | # given as the exec 'globals' argument, This is useful in embedding | |
262 | # situations where the ipython shell opens in a context where the |
|
262 | # situations where the ipython shell opens in a context where the | |
263 | # distinction between locals and globals is meaningful. |
|
263 | # distinction between locals and globals is meaningful. | |
264 |
|
264 | |||
265 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
265 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
266 | # level as a dict instead of a module. This is a manual fix, but I |
|
266 | # level as a dict instead of a module. This is a manual fix, but I | |
267 | # should really track down where the problem is coming from. Alex |
|
267 | # should really track down where the problem is coming from. Alex | |
268 | # Schmolck reported this problem first. |
|
268 | # Schmolck reported this problem first. | |
269 |
|
269 | |||
270 | # A useful post by Alex Martelli on this topic: |
|
270 | # A useful post by Alex Martelli on this topic: | |
271 | # Re: inconsistent value from __builtins__ |
|
271 | # Re: inconsistent value from __builtins__ | |
272 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
272 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
273 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
273 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
274 | # Gruppen: comp.lang.python |
|
274 | # Gruppen: comp.lang.python | |
275 |
|
275 | |||
276 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
276 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
277 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
277 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
278 | # > <type 'dict'> |
|
278 | # > <type 'dict'> | |
279 | # > >>> print type(__builtins__) |
|
279 | # > >>> print type(__builtins__) | |
280 | # > <type 'module'> |
|
280 | # > <type 'module'> | |
281 | # > Is this difference in return value intentional? |
|
281 | # > Is this difference in return value intentional? | |
282 |
|
282 | |||
283 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
283 | # Well, it's documented that '__builtins__' can be either a dictionary | |
284 | # or a module, and it's been that way for a long time. Whether it's |
|
284 | # or a module, and it's been that way for a long time. Whether it's | |
285 | # intentional (or sensible), I don't know. In any case, the idea is |
|
285 | # intentional (or sensible), I don't know. In any case, the idea is | |
286 | # that if you need to access the built-in namespace directly, you |
|
286 | # that if you need to access the built-in namespace directly, you | |
287 | # should start with "import __builtin__" (note, no 's') which will |
|
287 | # should start with "import __builtin__" (note, no 's') which will | |
288 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
288 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
289 |
|
289 | |||
290 | # These routines return properly built dicts as needed by the rest of |
|
290 | # These routines return properly built dicts as needed by the rest of | |
291 | # the code, and can also be used by extension writers to generate |
|
291 | # the code, and can also be used by extension writers to generate | |
292 | # properly initialized namespaces. |
|
292 | # properly initialized namespaces. | |
293 | user_ns = IPython.ipapi.make_user_ns(user_ns) |
|
293 | user_ns = IPython.ipapi.make_user_ns(user_ns) | |
294 | user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns) |
|
294 | user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns) | |
295 |
|
295 | |||
296 | # Assign namespaces |
|
296 | # Assign namespaces | |
297 | # This is the namespace where all normal user variables live |
|
297 | # This is the namespace where all normal user variables live | |
298 | self.user_ns = user_ns |
|
298 | self.user_ns = user_ns | |
299 | # Embedded instances require a separate namespace for globals. |
|
299 | # Embedded instances require a separate namespace for globals. | |
300 | # Normally this one is unused by non-embedded instances. |
|
300 | # Normally this one is unused by non-embedded instances. | |
301 | self.user_global_ns = user_global_ns |
|
301 | self.user_global_ns = user_global_ns | |
302 | # A namespace to keep track of internal data structures to prevent |
|
302 | # A namespace to keep track of internal data structures to prevent | |
303 | # them from cluttering user-visible stuff. Will be updated later |
|
303 | # them from cluttering user-visible stuff. Will be updated later | |
304 | self.internal_ns = {} |
|
304 | self.internal_ns = {} | |
305 |
|
305 | |||
306 | # Namespace of system aliases. Each entry in the alias |
|
306 | # Namespace of system aliases. Each entry in the alias | |
307 | # table must be a 2-tuple of the form (N,name), where N is the number |
|
307 | # table must be a 2-tuple of the form (N,name), where N is the number | |
308 | # of positional arguments of the alias. |
|
308 | # of positional arguments of the alias. | |
309 | self.alias_table = {} |
|
309 | self.alias_table = {} | |
310 |
|
310 | |||
311 | # A table holding all the namespaces IPython deals with, so that |
|
311 | # A table holding all the namespaces IPython deals with, so that | |
312 | # introspection facilities can search easily. |
|
312 | # introspection facilities can search easily. | |
313 | self.ns_table = {'user':user_ns, |
|
313 | self.ns_table = {'user':user_ns, | |
314 | 'user_global':user_global_ns, |
|
314 | 'user_global':user_global_ns, | |
315 | 'alias':self.alias_table, |
|
315 | 'alias':self.alias_table, | |
316 | 'internal':self.internal_ns, |
|
316 | 'internal':self.internal_ns, | |
317 | 'builtin':__builtin__.__dict__ |
|
317 | 'builtin':__builtin__.__dict__ | |
318 | } |
|
318 | } | |
319 | # The user namespace MUST have a pointer to the shell itself. |
|
319 | # The user namespace MUST have a pointer to the shell itself. | |
320 | self.user_ns[name] = self |
|
320 | self.user_ns[name] = self | |
321 |
|
321 | |||
322 | # We need to insert into sys.modules something that looks like a |
|
322 | # We need to insert into sys.modules something that looks like a | |
323 | # module but which accesses the IPython namespace, for shelve and |
|
323 | # module but which accesses the IPython namespace, for shelve and | |
324 | # pickle to work interactively. Normally they rely on getting |
|
324 | # pickle to work interactively. Normally they rely on getting | |
325 | # everything out of __main__, but for embedding purposes each IPython |
|
325 | # everything out of __main__, but for embedding purposes each IPython | |
326 | # instance has its own private namespace, so we can't go shoving |
|
326 | # instance has its own private namespace, so we can't go shoving | |
327 | # everything into __main__. |
|
327 | # everything into __main__. | |
328 |
|
328 | |||
329 | # note, however, that we should only do this for non-embedded |
|
329 | # note, however, that we should only do this for non-embedded | |
330 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
330 | # ipythons, which really mimic the __main__.__dict__ with their own | |
331 | # namespace. Embedded instances, on the other hand, should not do |
|
331 | # namespace. Embedded instances, on the other hand, should not do | |
332 | # this because they need to manage the user local/global namespaces |
|
332 | # this because they need to manage the user local/global namespaces | |
333 | # only, but they live within a 'normal' __main__ (meaning, they |
|
333 | # only, but they live within a 'normal' __main__ (meaning, they | |
334 | # shouldn't overtake the execution environment of the script they're |
|
334 | # shouldn't overtake the execution environment of the script they're | |
335 | # embedded in). |
|
335 | # embedded in). | |
336 |
|
336 | |||
337 | if not embedded: |
|
337 | if not embedded: | |
338 | try: |
|
338 | try: | |
339 | main_name = self.user_ns['__name__'] |
|
339 | main_name = self.user_ns['__name__'] | |
340 | except KeyError: |
|
340 | except KeyError: | |
341 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' |
|
341 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' | |
342 | else: |
|
342 | else: | |
343 | #print "pickle hack in place" # dbg |
|
343 | #print "pickle hack in place" # dbg | |
344 | #print 'main_name:',main_name # dbg |
|
344 | #print 'main_name:',main_name # dbg | |
345 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
345 | sys.modules[main_name] = FakeModule(self.user_ns) | |
346 |
|
346 | |||
347 | # Now that FakeModule produces a real module, we've run into a nasty |
|
347 | # Now that FakeModule produces a real module, we've run into a nasty | |
348 | # problem: after script execution (via %run), the module where the user |
|
348 | # problem: after script execution (via %run), the module where the user | |
349 | # code ran is deleted. Now that this object is a true module (needed |
|
349 | # code ran is deleted. Now that this object is a true module (needed | |
350 | # so docetst and other tools work correctly), the Python module |
|
350 | # so docetst and other tools work correctly), the Python module | |
351 | # teardown mechanism runs over it, and sets to None every variable |
|
351 | # teardown mechanism runs over it, and sets to None every variable | |
352 | # present in that module. This means that later calls to functions |
|
352 | # present in that module. This means that later calls to functions | |
353 | # defined in the script (which have become interactively visible after |
|
353 | # defined in the script (which have become interactively visible after | |
354 | # script exit) fail, because they hold references to objects that have |
|
354 | # script exit) fail, because they hold references to objects that have | |
355 | # become overwritten into None. The only solution I see right now is |
|
355 | # become overwritten into None. The only solution I see right now is | |
356 | # to protect every FakeModule used by %run by holding an internal |
|
356 | # to protect every FakeModule used by %run by holding an internal | |
357 | # reference to it. This private list will be used for that. The |
|
357 | # reference to it. This private list will be used for that. The | |
358 | # %reset command will flush it as well. |
|
358 | # %reset command will flush it as well. | |
359 | self._user_main_modules = [] |
|
359 | self._user_main_modules = [] | |
360 |
|
360 | |||
361 | # List of input with multi-line handling. |
|
361 | # List of input with multi-line handling. | |
362 | # Fill its zero entry, user counter starts at 1 |
|
362 | # Fill its zero entry, user counter starts at 1 | |
363 | self.input_hist = InputList(['\n']) |
|
363 | self.input_hist = InputList(['\n']) | |
364 | # This one will hold the 'raw' input history, without any |
|
364 | # This one will hold the 'raw' input history, without any | |
365 | # pre-processing. This will allow users to retrieve the input just as |
|
365 | # pre-processing. This will allow users to retrieve the input just as | |
366 | # it was exactly typed in by the user, with %hist -r. |
|
366 | # it was exactly typed in by the user, with %hist -r. | |
367 | self.input_hist_raw = InputList(['\n']) |
|
367 | self.input_hist_raw = InputList(['\n']) | |
368 |
|
368 | |||
369 | # list of visited directories |
|
369 | # list of visited directories | |
370 | try: |
|
370 | try: | |
371 | self.dir_hist = [os.getcwd()] |
|
371 | self.dir_hist = [os.getcwd()] | |
372 | except OSError: |
|
372 | except OSError: | |
373 | self.dir_hist = [] |
|
373 | self.dir_hist = [] | |
374 |
|
374 | |||
375 | # dict of output history |
|
375 | # dict of output history | |
376 | self.output_hist = {} |
|
376 | self.output_hist = {} | |
377 |
|
377 | |||
378 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
378 | # Get system encoding at startup time. Certain terminals (like Emacs | |
379 | # under Win32 have it set to None, and we need to have a known valid |
|
379 | # under Win32 have it set to None, and we need to have a known valid | |
380 | # encoding to use in the raw_input() method |
|
380 | # encoding to use in the raw_input() method | |
381 | try: |
|
381 | try: | |
382 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
382 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
383 | except AttributeError: |
|
383 | except AttributeError: | |
384 | self.stdin_encoding = 'ascii' |
|
384 | self.stdin_encoding = 'ascii' | |
385 |
|
385 | |||
386 | # dict of things NOT to alias (keywords, builtins and some magics) |
|
386 | # dict of things NOT to alias (keywords, builtins and some magics) | |
387 | no_alias = {} |
|
387 | no_alias = {} | |
388 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] |
|
388 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] | |
389 | for key in keyword.kwlist + no_alias_magics: |
|
389 | for key in keyword.kwlist + no_alias_magics: | |
390 | no_alias[key] = 1 |
|
390 | no_alias[key] = 1 | |
391 | no_alias.update(__builtin__.__dict__) |
|
391 | no_alias.update(__builtin__.__dict__) | |
392 | self.no_alias = no_alias |
|
392 | self.no_alias = no_alias | |
393 |
|
393 | |||
394 | # make global variables for user access to these |
|
394 | # make global variables for user access to these | |
395 | self.user_ns['_ih'] = self.input_hist |
|
395 | self.user_ns['_ih'] = self.input_hist | |
396 | self.user_ns['_oh'] = self.output_hist |
|
396 | self.user_ns['_oh'] = self.output_hist | |
397 | self.user_ns['_dh'] = self.dir_hist |
|
397 | self.user_ns['_dh'] = self.dir_hist | |
398 |
|
398 | |||
399 | # user aliases to input and output histories |
|
399 | # user aliases to input and output histories | |
400 | self.user_ns['In'] = self.input_hist |
|
400 | self.user_ns['In'] = self.input_hist | |
401 | self.user_ns['Out'] = self.output_hist |
|
401 | self.user_ns['Out'] = self.output_hist | |
402 |
|
402 | |||
403 | self.user_ns['_sh'] = IPython.shadowns |
|
403 | self.user_ns['_sh'] = IPython.shadowns | |
404 | # Object variable to store code object waiting execution. This is |
|
404 | # Object variable to store code object waiting execution. This is | |
405 | # used mainly by the multithreaded shells, but it can come in handy in |
|
405 | # used mainly by the multithreaded shells, but it can come in handy in | |
406 | # other situations. No need to use a Queue here, since it's a single |
|
406 | # other situations. No need to use a Queue here, since it's a single | |
407 | # item which gets cleared once run. |
|
407 | # item which gets cleared once run. | |
408 | self.code_to_run = None |
|
408 | self.code_to_run = None | |
409 |
|
409 | |||
410 | # escapes for automatic behavior on the command line |
|
410 | # escapes for automatic behavior on the command line | |
411 | self.ESC_SHELL = '!' |
|
411 | self.ESC_SHELL = '!' | |
412 | self.ESC_SH_CAP = '!!' |
|
412 | self.ESC_SH_CAP = '!!' | |
413 | self.ESC_HELP = '?' |
|
413 | self.ESC_HELP = '?' | |
414 | self.ESC_MAGIC = '%' |
|
414 | self.ESC_MAGIC = '%' | |
415 | self.ESC_QUOTE = ',' |
|
415 | self.ESC_QUOTE = ',' | |
416 | self.ESC_QUOTE2 = ';' |
|
416 | self.ESC_QUOTE2 = ';' | |
417 | self.ESC_PAREN = '/' |
|
417 | self.ESC_PAREN = '/' | |
418 |
|
418 | |||
419 | # And their associated handlers |
|
419 | # And their associated handlers | |
420 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, |
|
420 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, | |
421 | self.ESC_QUOTE : self.handle_auto, |
|
421 | self.ESC_QUOTE : self.handle_auto, | |
422 | self.ESC_QUOTE2 : self.handle_auto, |
|
422 | self.ESC_QUOTE2 : self.handle_auto, | |
423 | self.ESC_MAGIC : self.handle_magic, |
|
423 | self.ESC_MAGIC : self.handle_magic, | |
424 | self.ESC_HELP : self.handle_help, |
|
424 | self.ESC_HELP : self.handle_help, | |
425 | self.ESC_SHELL : self.handle_shell_escape, |
|
425 | self.ESC_SHELL : self.handle_shell_escape, | |
426 | self.ESC_SH_CAP : self.handle_shell_escape, |
|
426 | self.ESC_SH_CAP : self.handle_shell_escape, | |
427 | } |
|
427 | } | |
428 |
|
428 | |||
429 | # class initializations |
|
429 | # class initializations | |
430 | Magic.__init__(self,self) |
|
430 | Magic.__init__(self,self) | |
431 |
|
431 | |||
432 | # Python source parser/formatter for syntax highlighting |
|
432 | # Python source parser/formatter for syntax highlighting | |
433 | pyformat = PyColorize.Parser().format |
|
433 | pyformat = PyColorize.Parser().format | |
434 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) |
|
434 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) | |
435 |
|
435 | |||
436 | # hooks holds pointers used for user-side customizations |
|
436 | # hooks holds pointers used for user-side customizations | |
437 | self.hooks = Struct() |
|
437 | self.hooks = Struct() | |
438 |
|
438 | |||
439 | self.strdispatchers = {} |
|
439 | self.strdispatchers = {} | |
440 |
|
440 | |||
441 | # Set all default hooks, defined in the IPython.hooks module. |
|
441 | # Set all default hooks, defined in the IPython.hooks module. | |
442 | hooks = IPython.hooks |
|
442 | hooks = IPython.hooks | |
443 | for hook_name in hooks.__all__: |
|
443 | for hook_name in hooks.__all__: | |
444 | # default hooks have priority 100, i.e. low; user hooks should have |
|
444 | # default hooks have priority 100, i.e. low; user hooks should have | |
445 | # 0-100 priority |
|
445 | # 0-100 priority | |
446 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
446 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
447 | #print "bound hook",hook_name |
|
447 | #print "bound hook",hook_name | |
448 |
|
448 | |||
449 | # Flag to mark unconditional exit |
|
449 | # Flag to mark unconditional exit | |
450 | self.exit_now = False |
|
450 | self.exit_now = False | |
451 |
|
451 | |||
452 | self.usage_min = """\ |
|
452 | self.usage_min = """\ | |
453 | An enhanced console for Python. |
|
453 | An enhanced console for Python. | |
454 | Some of its features are: |
|
454 | Some of its features are: | |
455 | - Readline support if the readline library is present. |
|
455 | - Readline support if the readline library is present. | |
456 | - Tab completion in the local namespace. |
|
456 | - Tab completion in the local namespace. | |
457 | - Logging of input, see command-line options. |
|
457 | - Logging of input, see command-line options. | |
458 | - System shell escape via ! , eg !ls. |
|
458 | - System shell escape via ! , eg !ls. | |
459 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) |
|
459 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) | |
460 | - Keeps track of locally defined variables via %who, %whos. |
|
460 | - Keeps track of locally defined variables via %who, %whos. | |
461 | - Show object information with a ? eg ?x or x? (use ?? for more info). |
|
461 | - Show object information with a ? eg ?x or x? (use ?? for more info). | |
462 | """ |
|
462 | """ | |
463 | if usage: self.usage = usage |
|
463 | if usage: self.usage = usage | |
464 | else: self.usage = self.usage_min |
|
464 | else: self.usage = self.usage_min | |
465 |
|
465 | |||
466 | # Storage |
|
466 | # Storage | |
467 | self.rc = rc # This will hold all configuration information |
|
467 | self.rc = rc # This will hold all configuration information | |
468 | self.pager = 'less' |
|
468 | self.pager = 'less' | |
469 | # temporary files used for various purposes. Deleted at exit. |
|
469 | # temporary files used for various purposes. Deleted at exit. | |
470 | self.tempfiles = [] |
|
470 | self.tempfiles = [] | |
471 |
|
471 | |||
472 | # Keep track of readline usage (later set by init_readline) |
|
472 | # Keep track of readline usage (later set by init_readline) | |
473 | self.has_readline = False |
|
473 | self.has_readline = False | |
474 |
|
474 | |||
475 | # template for logfile headers. It gets resolved at runtime by the |
|
475 | # template for logfile headers. It gets resolved at runtime by the | |
476 | # logstart method. |
|
476 | # logstart method. | |
477 | self.loghead_tpl = \ |
|
477 | self.loghead_tpl = \ | |
478 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** |
|
478 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** | |
479 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW |
|
479 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW | |
480 | #log# opts = %s |
|
480 | #log# opts = %s | |
481 | #log# args = %s |
|
481 | #log# args = %s | |
482 | #log# It is safe to make manual edits below here. |
|
482 | #log# It is safe to make manual edits below here. | |
483 | #log#----------------------------------------------------------------------- |
|
483 | #log#----------------------------------------------------------------------- | |
484 | """ |
|
484 | """ | |
485 | # for pushd/popd management |
|
485 | # for pushd/popd management | |
486 | try: |
|
486 | try: | |
487 | self.home_dir = get_home_dir() |
|
487 | self.home_dir = get_home_dir() | |
488 | except HomeDirError,msg: |
|
488 | except HomeDirError,msg: | |
489 | fatal(msg) |
|
489 | fatal(msg) | |
490 |
|
490 | |||
491 | self.dir_stack = [] |
|
491 | self.dir_stack = [] | |
492 |
|
492 | |||
493 | # Functions to call the underlying shell. |
|
493 | # Functions to call the underlying shell. | |
494 |
|
494 | |||
495 | # The first is similar to os.system, but it doesn't return a value, |
|
495 | # The first is similar to os.system, but it doesn't return a value, | |
496 | # and it allows interpolation of variables in the user's namespace. |
|
496 | # and it allows interpolation of variables in the user's namespace. | |
497 | self.system = lambda cmd: \ |
|
497 | self.system = lambda cmd: \ | |
498 | self.hooks.shell_hook(self.var_expand(cmd,depth=2)) |
|
498 | self.hooks.shell_hook(self.var_expand(cmd,depth=2)) | |
499 |
|
499 | |||
500 | # These are for getoutput and getoutputerror: |
|
500 | # These are for getoutput and getoutputerror: | |
501 | self.getoutput = lambda cmd: \ |
|
501 | self.getoutput = lambda cmd: \ | |
502 | getoutput(self.var_expand(cmd,depth=2), |
|
502 | getoutput(self.var_expand(cmd,depth=2), | |
503 | header=self.rc.system_header, |
|
503 | header=self.rc.system_header, | |
504 | verbose=self.rc.system_verbose) |
|
504 | verbose=self.rc.system_verbose) | |
505 |
|
505 | |||
506 | self.getoutputerror = lambda cmd: \ |
|
506 | self.getoutputerror = lambda cmd: \ | |
507 | getoutputerror(self.var_expand(cmd,depth=2), |
|
507 | getoutputerror(self.var_expand(cmd,depth=2), | |
508 | header=self.rc.system_header, |
|
508 | header=self.rc.system_header, | |
509 | verbose=self.rc.system_verbose) |
|
509 | verbose=self.rc.system_verbose) | |
510 |
|
510 | |||
511 |
|
511 | |||
512 | # keep track of where we started running (mainly for crash post-mortem) |
|
512 | # keep track of where we started running (mainly for crash post-mortem) | |
513 | self.starting_dir = os.getcwd() |
|
513 | self.starting_dir = os.getcwd() | |
514 |
|
514 | |||
515 | # Various switches which can be set |
|
515 | # Various switches which can be set | |
516 | self.CACHELENGTH = 5000 # this is cheap, it's just text |
|
516 | self.CACHELENGTH = 5000 # this is cheap, it's just text | |
517 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ |
|
517 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ | |
518 | self.banner2 = banner2 |
|
518 | self.banner2 = banner2 | |
519 |
|
519 | |||
520 | # TraceBack handlers: |
|
520 | # TraceBack handlers: | |
521 |
|
521 | |||
522 | # Syntax error handler. |
|
522 | # Syntax error handler. | |
523 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
523 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') | |
524 |
|
524 | |||
525 | # The interactive one is initialized with an offset, meaning we always |
|
525 | # The interactive one is initialized with an offset, meaning we always | |
526 | # want to remove the topmost item in the traceback, which is our own |
|
526 | # want to remove the topmost item in the traceback, which is our own | |
527 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
527 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
528 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', |
|
528 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', | |
529 | color_scheme='NoColor', |
|
529 | color_scheme='NoColor', | |
530 | tb_offset = 1) |
|
530 | tb_offset = 1) | |
531 |
|
531 | |||
532 | # IPython itself shouldn't crash. This will produce a detailed |
|
532 | # IPython itself shouldn't crash. This will produce a detailed | |
533 | # post-mortem if it does. But we only install the crash handler for |
|
533 | # post-mortem if it does. But we only install the crash handler for | |
534 | # non-threaded shells, the threaded ones use a normal verbose reporter |
|
534 | # non-threaded shells, the threaded ones use a normal verbose reporter | |
535 | # and lose the crash handler. This is because exceptions in the main |
|
535 | # and lose the crash handler. This is because exceptions in the main | |
536 | # thread (such as in GUI code) propagate directly to sys.excepthook, |
|
536 | # thread (such as in GUI code) propagate directly to sys.excepthook, | |
537 | # and there's no point in printing crash dumps for every user exception. |
|
537 | # and there's no point in printing crash dumps for every user exception. | |
538 | if self.isthreaded: |
|
538 | if self.isthreaded: | |
539 | ipCrashHandler = ultraTB.FormattedTB() |
|
539 | ipCrashHandler = ultraTB.FormattedTB() | |
540 | else: |
|
540 | else: | |
541 | from IPython import CrashHandler |
|
541 | from IPython import CrashHandler | |
542 | ipCrashHandler = CrashHandler.IPythonCrashHandler(self) |
|
542 | ipCrashHandler = CrashHandler.IPythonCrashHandler(self) | |
543 | self.set_crash_handler(ipCrashHandler) |
|
543 | self.set_crash_handler(ipCrashHandler) | |
544 |
|
544 | |||
545 | # and add any custom exception handlers the user may have specified |
|
545 | # and add any custom exception handlers the user may have specified | |
546 | self.set_custom_exc(*custom_exceptions) |
|
546 | self.set_custom_exc(*custom_exceptions) | |
547 |
|
547 | |||
548 | # indentation management |
|
548 | # indentation management | |
549 | self.autoindent = False |
|
549 | self.autoindent = False | |
550 | self.indent_current_nsp = 0 |
|
550 | self.indent_current_nsp = 0 | |
551 |
|
551 | |||
552 | # Make some aliases automatically |
|
552 | # Make some aliases automatically | |
553 | # Prepare list of shell aliases to auto-define |
|
553 | # Prepare list of shell aliases to auto-define | |
554 | if os.name == 'posix': |
|
554 | if os.name == 'posix': | |
555 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', |
|
555 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', | |
556 | 'mv mv -i','rm rm -i','cp cp -i', |
|
556 | 'mv mv -i','rm rm -i','cp cp -i', | |
557 | 'cat cat','less less','clear clear', |
|
557 | 'cat cat','less less','clear clear', | |
558 | # a better ls |
|
558 | # a better ls | |
559 | 'ls ls -F', |
|
559 | 'ls ls -F', | |
560 | # long ls |
|
560 | # long ls | |
561 | 'll ls -lF') |
|
561 | 'll ls -lF') | |
562 | # Extra ls aliases with color, which need special treatment on BSD |
|
562 | # Extra ls aliases with color, which need special treatment on BSD | |
563 | # variants |
|
563 | # variants | |
564 | ls_extra = ( # color ls |
|
564 | ls_extra = ( # color ls | |
565 | 'lc ls -F -o --color', |
|
565 | 'lc ls -F -o --color', | |
566 | # ls normal files only |
|
566 | # ls normal files only | |
567 | 'lf ls -F -o --color %l | grep ^-', |
|
567 | 'lf ls -F -o --color %l | grep ^-', | |
568 | # ls symbolic links |
|
568 | # ls symbolic links | |
569 | 'lk ls -F -o --color %l | grep ^l', |
|
569 | 'lk ls -F -o --color %l | grep ^l', | |
570 | # directories or links to directories, |
|
570 | # directories or links to directories, | |
571 | 'ldir ls -F -o --color %l | grep /$', |
|
571 | 'ldir ls -F -o --color %l | grep /$', | |
572 | # things which are executable |
|
572 | # things which are executable | |
573 | 'lx ls -F -o --color %l | grep ^-..x', |
|
573 | 'lx ls -F -o --color %l | grep ^-..x', | |
574 | ) |
|
574 | ) | |
575 | # The BSDs don't ship GNU ls, so they don't understand the |
|
575 | # The BSDs don't ship GNU ls, so they don't understand the | |
576 | # --color switch out of the box |
|
576 | # --color switch out of the box | |
577 | if 'bsd' in sys.platform: |
|
577 | if 'bsd' in sys.platform: | |
578 | ls_extra = ( # ls normal files only |
|
578 | ls_extra = ( # ls normal files only | |
579 | 'lf ls -lF | grep ^-', |
|
579 | 'lf ls -lF | grep ^-', | |
580 | # ls symbolic links |
|
580 | # ls symbolic links | |
581 | 'lk ls -lF | grep ^l', |
|
581 | 'lk ls -lF | grep ^l', | |
582 | # directories or links to directories, |
|
582 | # directories or links to directories, | |
583 | 'ldir ls -lF | grep /$', |
|
583 | 'ldir ls -lF | grep /$', | |
584 | # things which are executable |
|
584 | # things which are executable | |
585 | 'lx ls -lF | grep ^-..x', |
|
585 | 'lx ls -lF | grep ^-..x', | |
586 | ) |
|
586 | ) | |
587 | auto_alias = auto_alias + ls_extra |
|
587 | auto_alias = auto_alias + ls_extra | |
588 | elif os.name in ['nt','dos']: |
|
588 | elif os.name in ['nt','dos']: | |
589 | auto_alias = ('ls dir /on', |
|
589 | auto_alias = ('ls dir /on', | |
590 | 'ddir dir /ad /on', 'ldir dir /ad /on', |
|
590 | 'ddir dir /ad /on', 'ldir dir /ad /on', | |
591 | 'mkdir mkdir','rmdir rmdir','echo echo', |
|
591 | 'mkdir mkdir','rmdir rmdir','echo echo', | |
592 | 'ren ren','cls cls','copy copy') |
|
592 | 'ren ren','cls cls','copy copy') | |
593 | else: |
|
593 | else: | |
594 | auto_alias = () |
|
594 | auto_alias = () | |
595 | self.auto_alias = [s.split(None,1) for s in auto_alias] |
|
595 | self.auto_alias = [s.split(None,1) for s in auto_alias] | |
596 |
|
596 | |||
597 |
|
597 | |||
598 | # Produce a public API instance |
|
598 | # Produce a public API instance | |
599 | self.api = IPython.ipapi.IPApi(self) |
|
599 | self.api = IPython.ipapi.IPApi(self) | |
600 |
|
600 | |||
601 | # Call the actual (public) initializer |
|
601 | # Call the actual (public) initializer | |
602 | self.init_auto_alias() |
|
602 | self.init_auto_alias() | |
603 |
|
603 | |||
604 | # track which builtins we add, so we can clean up later |
|
604 | # track which builtins we add, so we can clean up later | |
605 | self.builtins_added = {} |
|
605 | self.builtins_added = {} | |
606 | # This method will add the necessary builtins for operation, but |
|
606 | # This method will add the necessary builtins for operation, but | |
607 | # tracking what it did via the builtins_added dict. |
|
607 | # tracking what it did via the builtins_added dict. | |
608 |
|
608 | |||
609 | #TODO: remove this, redundant |
|
609 | #TODO: remove this, redundant | |
610 | self.add_builtins() |
|
610 | self.add_builtins() | |
611 |
|
611 | |||
612 |
|
612 | |||
613 |
|
613 | |||
614 |
|
614 | |||
615 | # end __init__ |
|
615 | # end __init__ | |
616 |
|
616 | |||
617 | def var_expand(self,cmd,depth=0): |
|
617 | def var_expand(self,cmd,depth=0): | |
618 | """Expand python variables in a string. |
|
618 | """Expand python variables in a string. | |
619 |
|
619 | |||
620 | The depth argument indicates how many frames above the caller should |
|
620 | The depth argument indicates how many frames above the caller should | |
621 | be walked to look for the local namespace where to expand variables. |
|
621 | be walked to look for the local namespace where to expand variables. | |
622 |
|
622 | |||
623 | The global namespace for expansion is always the user's interactive |
|
623 | The global namespace for expansion is always the user's interactive | |
624 | namespace. |
|
624 | namespace. | |
625 | """ |
|
625 | """ | |
626 |
|
626 | |||
627 | return str(ItplNS(cmd, |
|
627 | return str(ItplNS(cmd, | |
628 | self.user_ns, # globals |
|
628 | self.user_ns, # globals | |
629 | # Skip our own frame in searching for locals: |
|
629 | # Skip our own frame in searching for locals: | |
630 | sys._getframe(depth+1).f_locals # locals |
|
630 | sys._getframe(depth+1).f_locals # locals | |
631 | )) |
|
631 | )) | |
632 |
|
632 | |||
633 | def pre_config_initialization(self): |
|
633 | def pre_config_initialization(self): | |
634 | """Pre-configuration init method |
|
634 | """Pre-configuration init method | |
635 |
|
635 | |||
636 | This is called before the configuration files are processed to |
|
636 | This is called before the configuration files are processed to | |
637 | prepare the services the config files might need. |
|
637 | prepare the services the config files might need. | |
638 |
|
638 | |||
639 | self.rc already has reasonable default values at this point. |
|
639 | self.rc already has reasonable default values at this point. | |
640 | """ |
|
640 | """ | |
641 | rc = self.rc |
|
641 | rc = self.rc | |
642 | try: |
|
642 | try: | |
643 | self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db") |
|
643 | self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db") | |
644 | except exceptions.UnicodeDecodeError: |
|
644 | except exceptions.UnicodeDecodeError: | |
645 | print "Your ipythondir can't be decoded to unicode!" |
|
645 | print "Your ipythondir can't be decoded to unicode!" | |
646 | print "Please set HOME environment variable to something that" |
|
646 | print "Please set HOME environment variable to something that" | |
647 | print r"only has ASCII characters, e.g. c:\home" |
|
647 | print r"only has ASCII characters, e.g. c:\home" | |
648 | print "Now it is",rc.ipythondir |
|
648 | print "Now it is",rc.ipythondir | |
649 | sys.exit() |
|
649 | sys.exit() | |
650 | self.shadowhist = IPython.history.ShadowHist(self.db) |
|
650 | self.shadowhist = IPython.history.ShadowHist(self.db) | |
651 |
|
651 | |||
652 |
|
652 | |||
653 | def post_config_initialization(self): |
|
653 | def post_config_initialization(self): | |
654 | """Post configuration init method |
|
654 | """Post configuration init method | |
655 |
|
655 | |||
656 | This is called after the configuration files have been processed to |
|
656 | This is called after the configuration files have been processed to | |
657 | 'finalize' the initialization.""" |
|
657 | 'finalize' the initialization.""" | |
658 |
|
658 | |||
659 | rc = self.rc |
|
659 | rc = self.rc | |
660 |
|
660 | |||
661 | # Object inspector |
|
661 | # Object inspector | |
662 | self.inspector = OInspect.Inspector(OInspect.InspectColors, |
|
662 | self.inspector = OInspect.Inspector(OInspect.InspectColors, | |
663 | PyColorize.ANSICodeColors, |
|
663 | PyColorize.ANSICodeColors, | |
664 | 'NoColor', |
|
664 | 'NoColor', | |
665 | rc.object_info_string_level) |
|
665 | rc.object_info_string_level) | |
666 |
|
666 | |||
667 | self.rl_next_input = None |
|
667 | self.rl_next_input = None | |
668 | self.rl_do_indent = False |
|
668 | self.rl_do_indent = False | |
669 | # Load readline proper |
|
669 | # Load readline proper | |
670 | if rc.readline: |
|
670 | if rc.readline: | |
671 | self.init_readline() |
|
671 | self.init_readline() | |
672 |
|
672 | |||
673 |
|
673 | |||
674 | # local shortcut, this is used a LOT |
|
674 | # local shortcut, this is used a LOT | |
675 | self.log = self.logger.log |
|
675 | self.log = self.logger.log | |
676 |
|
676 | |||
677 | # Initialize cache, set in/out prompts and printing system |
|
677 | # Initialize cache, set in/out prompts and printing system | |
678 | self.outputcache = CachedOutput(self, |
|
678 | self.outputcache = CachedOutput(self, | |
679 | rc.cache_size, |
|
679 | rc.cache_size, | |
680 | rc.pprint, |
|
680 | rc.pprint, | |
681 | input_sep = rc.separate_in, |
|
681 | input_sep = rc.separate_in, | |
682 | output_sep = rc.separate_out, |
|
682 | output_sep = rc.separate_out, | |
683 | output_sep2 = rc.separate_out2, |
|
683 | output_sep2 = rc.separate_out2, | |
684 | ps1 = rc.prompt_in1, |
|
684 | ps1 = rc.prompt_in1, | |
685 | ps2 = rc.prompt_in2, |
|
685 | ps2 = rc.prompt_in2, | |
686 | ps_out = rc.prompt_out, |
|
686 | ps_out = rc.prompt_out, | |
687 | pad_left = rc.prompts_pad_left) |
|
687 | pad_left = rc.prompts_pad_left) | |
688 |
|
688 | |||
689 | # user may have over-ridden the default print hook: |
|
689 | # user may have over-ridden the default print hook: | |
690 | try: |
|
690 | try: | |
691 | self.outputcache.__class__.display = self.hooks.display |
|
691 | self.outputcache.__class__.display = self.hooks.display | |
692 | except AttributeError: |
|
692 | except AttributeError: | |
693 | pass |
|
693 | pass | |
694 |
|
694 | |||
695 | # I don't like assigning globally to sys, because it means when |
|
695 | # I don't like assigning globally to sys, because it means when | |
696 | # embedding instances, each embedded instance overrides the previous |
|
696 | # embedding instances, each embedded instance overrides the previous | |
697 | # choice. But sys.displayhook seems to be called internally by exec, |
|
697 | # choice. But sys.displayhook seems to be called internally by exec, | |
698 | # so I don't see a way around it. We first save the original and then |
|
698 | # so I don't see a way around it. We first save the original and then | |
699 | # overwrite it. |
|
699 | # overwrite it. | |
700 | self.sys_displayhook = sys.displayhook |
|
700 | self.sys_displayhook = sys.displayhook | |
701 | sys.displayhook = self.outputcache |
|
701 | sys.displayhook = self.outputcache | |
702 |
|
702 | |||
703 | # Do a proper resetting of doctest, including the necessary displayhook |
|
703 | # Do a proper resetting of doctest, including the necessary displayhook | |
704 | # monkeypatching |
|
704 | # monkeypatching | |
705 | doctest_reload() |
|
705 | try: | |
|
706 | doctest_reload() | |||
|
707 | except ImportError: | |||
|
708 | warn("doctest module does not exist.") | |||
706 |
|
709 | |||
707 | # Set user colors (don't do it in the constructor above so that it |
|
710 | # Set user colors (don't do it in the constructor above so that it | |
708 | # doesn't crash if colors option is invalid) |
|
711 | # doesn't crash if colors option is invalid) | |
709 | self.magic_colors(rc.colors) |
|
712 | self.magic_colors(rc.colors) | |
710 |
|
713 | |||
711 | # Set calling of pdb on exceptions |
|
714 | # Set calling of pdb on exceptions | |
712 | self.call_pdb = rc.pdb |
|
715 | self.call_pdb = rc.pdb | |
713 |
|
716 | |||
714 | # Load user aliases |
|
717 | # Load user aliases | |
715 | for alias in rc.alias: |
|
718 | for alias in rc.alias: | |
716 | self.magic_alias(alias) |
|
719 | self.magic_alias(alias) | |
717 |
|
720 | |||
718 | self.hooks.late_startup_hook() |
|
721 | self.hooks.late_startup_hook() | |
719 |
|
722 | |||
720 | for cmd in self.rc.autoexec: |
|
723 | for cmd in self.rc.autoexec: | |
721 | #print "autoexec>",cmd #dbg |
|
724 | #print "autoexec>",cmd #dbg | |
722 | self.api.runlines(cmd) |
|
725 | self.api.runlines(cmd) | |
723 |
|
726 | |||
724 | batchrun = False |
|
727 | batchrun = False | |
725 | for batchfile in [path(arg) for arg in self.rc.args |
|
728 | for batchfile in [path(arg) for arg in self.rc.args | |
726 | if arg.lower().endswith('.ipy')]: |
|
729 | if arg.lower().endswith('.ipy')]: | |
727 | if not batchfile.isfile(): |
|
730 | if not batchfile.isfile(): | |
728 | print "No such batch file:", batchfile |
|
731 | print "No such batch file:", batchfile | |
729 | continue |
|
732 | continue | |
730 | self.api.runlines(batchfile.text()) |
|
733 | self.api.runlines(batchfile.text()) | |
731 | batchrun = True |
|
734 | batchrun = True | |
732 | # without -i option, exit after running the batch file |
|
735 | # without -i option, exit after running the batch file | |
733 | if batchrun and not self.rc.interact: |
|
736 | if batchrun and not self.rc.interact: | |
734 | self.exit_now = True |
|
737 | self.exit_now = True | |
735 |
|
738 | |||
736 | def add_builtins(self): |
|
739 | def add_builtins(self): | |
737 | """Store ipython references into the builtin namespace. |
|
740 | """Store ipython references into the builtin namespace. | |
738 |
|
741 | |||
739 | Some parts of ipython operate via builtins injected here, which hold a |
|
742 | Some parts of ipython operate via builtins injected here, which hold a | |
740 | reference to IPython itself.""" |
|
743 | reference to IPython itself.""" | |
741 |
|
744 | |||
742 | # TODO: deprecate all of these, they are unsafe |
|
745 | # TODO: deprecate all of these, they are unsafe | |
743 | builtins_new = dict(__IPYTHON__ = self, |
|
746 | builtins_new = dict(__IPYTHON__ = self, | |
744 | ip_set_hook = self.set_hook, |
|
747 | ip_set_hook = self.set_hook, | |
745 | jobs = self.jobs, |
|
748 | jobs = self.jobs, | |
746 | ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'), |
|
749 | ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'), | |
747 | ipalias = wrap_deprecated(self.ipalias), |
|
750 | ipalias = wrap_deprecated(self.ipalias), | |
748 | ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'), |
|
751 | ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'), | |
749 | #_ip = self.api |
|
752 | #_ip = self.api | |
750 | ) |
|
753 | ) | |
751 | for biname,bival in builtins_new.items(): |
|
754 | for biname,bival in builtins_new.items(): | |
752 | try: |
|
755 | try: | |
753 | # store the orignal value so we can restore it |
|
756 | # store the orignal value so we can restore it | |
754 | self.builtins_added[biname] = __builtin__.__dict__[biname] |
|
757 | self.builtins_added[biname] = __builtin__.__dict__[biname] | |
755 | except KeyError: |
|
758 | except KeyError: | |
756 | # or mark that it wasn't defined, and we'll just delete it at |
|
759 | # or mark that it wasn't defined, and we'll just delete it at | |
757 | # cleanup |
|
760 | # cleanup | |
758 | self.builtins_added[biname] = Undefined |
|
761 | self.builtins_added[biname] = Undefined | |
759 | __builtin__.__dict__[biname] = bival |
|
762 | __builtin__.__dict__[biname] = bival | |
760 |
|
763 | |||
761 | # Keep in the builtins a flag for when IPython is active. We set it |
|
764 | # Keep in the builtins a flag for when IPython is active. We set it | |
762 | # with setdefault so that multiple nested IPythons don't clobber one |
|
765 | # with setdefault so that multiple nested IPythons don't clobber one | |
763 | # another. Each will increase its value by one upon being activated, |
|
766 | # another. Each will increase its value by one upon being activated, | |
764 | # which also gives us a way to determine the nesting level. |
|
767 | # which also gives us a way to determine the nesting level. | |
765 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) |
|
768 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) | |
766 |
|
769 | |||
767 | def clean_builtins(self): |
|
770 | def clean_builtins(self): | |
768 | """Remove any builtins which might have been added by add_builtins, or |
|
771 | """Remove any builtins which might have been added by add_builtins, or | |
769 | restore overwritten ones to their previous values.""" |
|
772 | restore overwritten ones to their previous values.""" | |
770 | for biname,bival in self.builtins_added.items(): |
|
773 | for biname,bival in self.builtins_added.items(): | |
771 | if bival is Undefined: |
|
774 | if bival is Undefined: | |
772 | del __builtin__.__dict__[biname] |
|
775 | del __builtin__.__dict__[biname] | |
773 | else: |
|
776 | else: | |
774 | __builtin__.__dict__[biname] = bival |
|
777 | __builtin__.__dict__[biname] = bival | |
775 | self.builtins_added.clear() |
|
778 | self.builtins_added.clear() | |
776 |
|
779 | |||
777 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
780 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
778 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
781 | """set_hook(name,hook) -> sets an internal IPython hook. | |
779 |
|
782 | |||
780 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
783 | IPython exposes some of its internal API as user-modifiable hooks. By | |
781 | adding your function to one of these hooks, you can modify IPython's |
|
784 | adding your function to one of these hooks, you can modify IPython's | |
782 | behavior to call at runtime your own routines.""" |
|
785 | behavior to call at runtime your own routines.""" | |
783 |
|
786 | |||
784 | # At some point in the future, this should validate the hook before it |
|
787 | # At some point in the future, this should validate the hook before it | |
785 | # accepts it. Probably at least check that the hook takes the number |
|
788 | # accepts it. Probably at least check that the hook takes the number | |
786 | # of args it's supposed to. |
|
789 | # of args it's supposed to. | |
787 |
|
790 | |||
788 | f = new.instancemethod(hook,self,self.__class__) |
|
791 | f = new.instancemethod(hook,self,self.__class__) | |
789 |
|
792 | |||
790 | # check if the hook is for strdispatcher first |
|
793 | # check if the hook is for strdispatcher first | |
791 | if str_key is not None: |
|
794 | if str_key is not None: | |
792 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
795 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
793 | sdp.add_s(str_key, f, priority ) |
|
796 | sdp.add_s(str_key, f, priority ) | |
794 | self.strdispatchers[name] = sdp |
|
797 | self.strdispatchers[name] = sdp | |
795 | return |
|
798 | return | |
796 | if re_key is not None: |
|
799 | if re_key is not None: | |
797 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
800 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
798 | sdp.add_re(re.compile(re_key), f, priority ) |
|
801 | sdp.add_re(re.compile(re_key), f, priority ) | |
799 | self.strdispatchers[name] = sdp |
|
802 | self.strdispatchers[name] = sdp | |
800 | return |
|
803 | return | |
801 |
|
804 | |||
802 | dp = getattr(self.hooks, name, None) |
|
805 | dp = getattr(self.hooks, name, None) | |
803 | if name not in IPython.hooks.__all__: |
|
806 | if name not in IPython.hooks.__all__: | |
804 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ ) |
|
807 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ ) | |
805 | if not dp: |
|
808 | if not dp: | |
806 | dp = IPython.hooks.CommandChainDispatcher() |
|
809 | dp = IPython.hooks.CommandChainDispatcher() | |
807 |
|
810 | |||
808 | try: |
|
811 | try: | |
809 | dp.add(f,priority) |
|
812 | dp.add(f,priority) | |
810 | except AttributeError: |
|
813 | except AttributeError: | |
811 | # it was not commandchain, plain old func - replace |
|
814 | # it was not commandchain, plain old func - replace | |
812 | dp = f |
|
815 | dp = f | |
813 |
|
816 | |||
814 | setattr(self.hooks,name, dp) |
|
817 | setattr(self.hooks,name, dp) | |
815 |
|
818 | |||
816 |
|
819 | |||
817 | #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) |
|
820 | #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) | |
818 |
|
821 | |||
819 | def set_crash_handler(self,crashHandler): |
|
822 | def set_crash_handler(self,crashHandler): | |
820 | """Set the IPython crash handler. |
|
823 | """Set the IPython crash handler. | |
821 |
|
824 | |||
822 | This must be a callable with a signature suitable for use as |
|
825 | This must be a callable with a signature suitable for use as | |
823 | sys.excepthook.""" |
|
826 | sys.excepthook.""" | |
824 |
|
827 | |||
825 | # Install the given crash handler as the Python exception hook |
|
828 | # Install the given crash handler as the Python exception hook | |
826 | sys.excepthook = crashHandler |
|
829 | sys.excepthook = crashHandler | |
827 |
|
830 | |||
828 | # The instance will store a pointer to this, so that runtime code |
|
831 | # The instance will store a pointer to this, so that runtime code | |
829 | # (such as magics) can access it. This is because during the |
|
832 | # (such as magics) can access it. This is because during the | |
830 | # read-eval loop, it gets temporarily overwritten (to deal with GUI |
|
833 | # read-eval loop, it gets temporarily overwritten (to deal with GUI | |
831 | # frameworks). |
|
834 | # frameworks). | |
832 | self.sys_excepthook = sys.excepthook |
|
835 | self.sys_excepthook = sys.excepthook | |
833 |
|
836 | |||
834 |
|
837 | |||
835 | def set_custom_exc(self,exc_tuple,handler): |
|
838 | def set_custom_exc(self,exc_tuple,handler): | |
836 | """set_custom_exc(exc_tuple,handler) |
|
839 | """set_custom_exc(exc_tuple,handler) | |
837 |
|
840 | |||
838 | Set a custom exception handler, which will be called if any of the |
|
841 | Set a custom exception handler, which will be called if any of the | |
839 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
842 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
840 | runcode() method. |
|
843 | runcode() method. | |
841 |
|
844 | |||
842 | Inputs: |
|
845 | Inputs: | |
843 |
|
846 | |||
844 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
847 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
845 | handler for. It is very important that you use a tuple, and NOT A |
|
848 | handler for. It is very important that you use a tuple, and NOT A | |
846 | LIST here, because of the way Python's except statement works. If |
|
849 | LIST here, because of the way Python's except statement works. If | |
847 | you only want to trap a single exception, use a singleton tuple: |
|
850 | you only want to trap a single exception, use a singleton tuple: | |
848 |
|
851 | |||
849 | exc_tuple == (MyCustomException,) |
|
852 | exc_tuple == (MyCustomException,) | |
850 |
|
853 | |||
851 | - handler: this must be defined as a function with the following |
|
854 | - handler: this must be defined as a function with the following | |
852 | basic interface: def my_handler(self,etype,value,tb). |
|
855 | basic interface: def my_handler(self,etype,value,tb). | |
853 |
|
856 | |||
854 | This will be made into an instance method (via new.instancemethod) |
|
857 | This will be made into an instance method (via new.instancemethod) | |
855 | of IPython itself, and it will be called if any of the exceptions |
|
858 | of IPython itself, and it will be called if any of the exceptions | |
856 | listed in the exc_tuple are caught. If the handler is None, an |
|
859 | listed in the exc_tuple are caught. If the handler is None, an | |
857 | internal basic one is used, which just prints basic info. |
|
860 | internal basic one is used, which just prints basic info. | |
858 |
|
861 | |||
859 | WARNING: by putting in your own exception handler into IPython's main |
|
862 | WARNING: by putting in your own exception handler into IPython's main | |
860 | execution loop, you run a very good chance of nasty crashes. This |
|
863 | execution loop, you run a very good chance of nasty crashes. This | |
861 | facility should only be used if you really know what you are doing.""" |
|
864 | facility should only be used if you really know what you are doing.""" | |
862 |
|
865 | |||
863 | assert type(exc_tuple)==type(()) , \ |
|
866 | assert type(exc_tuple)==type(()) , \ | |
864 | "The custom exceptions must be given AS A TUPLE." |
|
867 | "The custom exceptions must be given AS A TUPLE." | |
865 |
|
868 | |||
866 | def dummy_handler(self,etype,value,tb): |
|
869 | def dummy_handler(self,etype,value,tb): | |
867 | print '*** Simple custom exception handler ***' |
|
870 | print '*** Simple custom exception handler ***' | |
868 | print 'Exception type :',etype |
|
871 | print 'Exception type :',etype | |
869 | print 'Exception value:',value |
|
872 | print 'Exception value:',value | |
870 | print 'Traceback :',tb |
|
873 | print 'Traceback :',tb | |
871 | print 'Source code :','\n'.join(self.buffer) |
|
874 | print 'Source code :','\n'.join(self.buffer) | |
872 |
|
875 | |||
873 | if handler is None: handler = dummy_handler |
|
876 | if handler is None: handler = dummy_handler | |
874 |
|
877 | |||
875 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
878 | self.CustomTB = new.instancemethod(handler,self,self.__class__) | |
876 | self.custom_exceptions = exc_tuple |
|
879 | self.custom_exceptions = exc_tuple | |
877 |
|
880 | |||
878 | def set_custom_completer(self,completer,pos=0): |
|
881 | def set_custom_completer(self,completer,pos=0): | |
879 | """set_custom_completer(completer,pos=0) |
|
882 | """set_custom_completer(completer,pos=0) | |
880 |
|
883 | |||
881 | Adds a new custom completer function. |
|
884 | Adds a new custom completer function. | |
882 |
|
885 | |||
883 | The position argument (defaults to 0) is the index in the completers |
|
886 | The position argument (defaults to 0) is the index in the completers | |
884 | list where you want the completer to be inserted.""" |
|
887 | list where you want the completer to be inserted.""" | |
885 |
|
888 | |||
886 | newcomp = new.instancemethod(completer,self.Completer, |
|
889 | newcomp = new.instancemethod(completer,self.Completer, | |
887 | self.Completer.__class__) |
|
890 | self.Completer.__class__) | |
888 | self.Completer.matchers.insert(pos,newcomp) |
|
891 | self.Completer.matchers.insert(pos,newcomp) | |
889 |
|
892 | |||
890 | def set_completer(self): |
|
893 | def set_completer(self): | |
891 | """reset readline's completer to be our own.""" |
|
894 | """reset readline's completer to be our own.""" | |
892 | self.readline.set_completer(self.Completer.complete) |
|
895 | self.readline.set_completer(self.Completer.complete) | |
893 |
|
896 | |||
894 | def _get_call_pdb(self): |
|
897 | def _get_call_pdb(self): | |
895 | return self._call_pdb |
|
898 | return self._call_pdb | |
896 |
|
899 | |||
897 | def _set_call_pdb(self,val): |
|
900 | def _set_call_pdb(self,val): | |
898 |
|
901 | |||
899 | if val not in (0,1,False,True): |
|
902 | if val not in (0,1,False,True): | |
900 | raise ValueError,'new call_pdb value must be boolean' |
|
903 | raise ValueError,'new call_pdb value must be boolean' | |
901 |
|
904 | |||
902 | # store value in instance |
|
905 | # store value in instance | |
903 | self._call_pdb = val |
|
906 | self._call_pdb = val | |
904 |
|
907 | |||
905 | # notify the actual exception handlers |
|
908 | # notify the actual exception handlers | |
906 | self.InteractiveTB.call_pdb = val |
|
909 | self.InteractiveTB.call_pdb = val | |
907 | if self.isthreaded: |
|
910 | if self.isthreaded: | |
908 | try: |
|
911 | try: | |
909 | self.sys_excepthook.call_pdb = val |
|
912 | self.sys_excepthook.call_pdb = val | |
910 | except: |
|
913 | except: | |
911 | warn('Failed to activate pdb for threaded exception handler') |
|
914 | warn('Failed to activate pdb for threaded exception handler') | |
912 |
|
915 | |||
913 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
916 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
914 | 'Control auto-activation of pdb at exceptions') |
|
917 | 'Control auto-activation of pdb at exceptions') | |
915 |
|
918 | |||
916 |
|
919 | |||
917 | # These special functions get installed in the builtin namespace, to |
|
920 | # These special functions get installed in the builtin namespace, to | |
918 | # provide programmatic (pure python) access to magics, aliases and system |
|
921 | # provide programmatic (pure python) access to magics, aliases and system | |
919 | # calls. This is important for logging, user scripting, and more. |
|
922 | # calls. This is important for logging, user scripting, and more. | |
920 |
|
923 | |||
921 | # We are basically exposing, via normal python functions, the three |
|
924 | # We are basically exposing, via normal python functions, the three | |
922 | # mechanisms in which ipython offers special call modes (magics for |
|
925 | # mechanisms in which ipython offers special call modes (magics for | |
923 | # internal control, aliases for direct system access via pre-selected |
|
926 | # internal control, aliases for direct system access via pre-selected | |
924 | # names, and !cmd for calling arbitrary system commands). |
|
927 | # names, and !cmd for calling arbitrary system commands). | |
925 |
|
928 | |||
926 | def ipmagic(self,arg_s): |
|
929 | def ipmagic(self,arg_s): | |
927 | """Call a magic function by name. |
|
930 | """Call a magic function by name. | |
928 |
|
931 | |||
929 | Input: a string containing the name of the magic function to call and any |
|
932 | Input: a string containing the name of the magic function to call and any | |
930 | additional arguments to be passed to the magic. |
|
933 | additional arguments to be passed to the magic. | |
931 |
|
934 | |||
932 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython |
|
935 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython | |
933 | prompt: |
|
936 | prompt: | |
934 |
|
937 | |||
935 | In[1]: %name -opt foo bar |
|
938 | In[1]: %name -opt foo bar | |
936 |
|
939 | |||
937 | To call a magic without arguments, simply use ipmagic('name'). |
|
940 | To call a magic without arguments, simply use ipmagic('name'). | |
938 |
|
941 | |||
939 | This provides a proper Python function to call IPython's magics in any |
|
942 | This provides a proper Python function to call IPython's magics in any | |
940 | valid Python code you can type at the interpreter, including loops and |
|
943 | valid Python code you can type at the interpreter, including loops and | |
941 | compound statements. It is added by IPython to the Python builtin |
|
944 | compound statements. It is added by IPython to the Python builtin | |
942 | namespace upon initialization.""" |
|
945 | namespace upon initialization.""" | |
943 |
|
946 | |||
944 | args = arg_s.split(' ',1) |
|
947 | args = arg_s.split(' ',1) | |
945 | magic_name = args[0] |
|
948 | magic_name = args[0] | |
946 | magic_name = magic_name.lstrip(self.ESC_MAGIC) |
|
949 | magic_name = magic_name.lstrip(self.ESC_MAGIC) | |
947 |
|
950 | |||
948 | try: |
|
951 | try: | |
949 | magic_args = args[1] |
|
952 | magic_args = args[1] | |
950 | except IndexError: |
|
953 | except IndexError: | |
951 | magic_args = '' |
|
954 | magic_args = '' | |
952 | fn = getattr(self,'magic_'+magic_name,None) |
|
955 | fn = getattr(self,'magic_'+magic_name,None) | |
953 | if fn is None: |
|
956 | if fn is None: | |
954 | error("Magic function `%s` not found." % magic_name) |
|
957 | error("Magic function `%s` not found." % magic_name) | |
955 | else: |
|
958 | else: | |
956 | magic_args = self.var_expand(magic_args,1) |
|
959 | magic_args = self.var_expand(magic_args,1) | |
957 | return fn(magic_args) |
|
960 | return fn(magic_args) | |
958 |
|
961 | |||
959 | def ipalias(self,arg_s): |
|
962 | def ipalias(self,arg_s): | |
960 | """Call an alias by name. |
|
963 | """Call an alias by name. | |
961 |
|
964 | |||
962 | Input: a string containing the name of the alias to call and any |
|
965 | Input: a string containing the name of the alias to call and any | |
963 | additional arguments to be passed to the magic. |
|
966 | additional arguments to be passed to the magic. | |
964 |
|
967 | |||
965 | ipalias('name -opt foo bar') is equivalent to typing at the ipython |
|
968 | ipalias('name -opt foo bar') is equivalent to typing at the ipython | |
966 | prompt: |
|
969 | prompt: | |
967 |
|
970 | |||
968 | In[1]: name -opt foo bar |
|
971 | In[1]: name -opt foo bar | |
969 |
|
972 | |||
970 | To call an alias without arguments, simply use ipalias('name'). |
|
973 | To call an alias without arguments, simply use ipalias('name'). | |
971 |
|
974 | |||
972 | This provides a proper Python function to call IPython's aliases in any |
|
975 | This provides a proper Python function to call IPython's aliases in any | |
973 | valid Python code you can type at the interpreter, including loops and |
|
976 | valid Python code you can type at the interpreter, including loops and | |
974 | compound statements. It is added by IPython to the Python builtin |
|
977 | compound statements. It is added by IPython to the Python builtin | |
975 | namespace upon initialization.""" |
|
978 | namespace upon initialization.""" | |
976 |
|
979 | |||
977 | args = arg_s.split(' ',1) |
|
980 | args = arg_s.split(' ',1) | |
978 | alias_name = args[0] |
|
981 | alias_name = args[0] | |
979 | try: |
|
982 | try: | |
980 | alias_args = args[1] |
|
983 | alias_args = args[1] | |
981 | except IndexError: |
|
984 | except IndexError: | |
982 | alias_args = '' |
|
985 | alias_args = '' | |
983 | if alias_name in self.alias_table: |
|
986 | if alias_name in self.alias_table: | |
984 | self.call_alias(alias_name,alias_args) |
|
987 | self.call_alias(alias_name,alias_args) | |
985 | else: |
|
988 | else: | |
986 | error("Alias `%s` not found." % alias_name) |
|
989 | error("Alias `%s` not found." % alias_name) | |
987 |
|
990 | |||
988 | def ipsystem(self,arg_s): |
|
991 | def ipsystem(self,arg_s): | |
989 | """Make a system call, using IPython.""" |
|
992 | """Make a system call, using IPython.""" | |
990 |
|
993 | |||
991 | self.system(arg_s) |
|
994 | self.system(arg_s) | |
992 |
|
995 | |||
993 | def complete(self,text): |
|
996 | def complete(self,text): | |
994 | """Return a sorted list of all possible completions on text. |
|
997 | """Return a sorted list of all possible completions on text. | |
995 |
|
998 | |||
996 | Inputs: |
|
999 | Inputs: | |
997 |
|
1000 | |||
998 | - text: a string of text to be completed on. |
|
1001 | - text: a string of text to be completed on. | |
999 |
|
1002 | |||
1000 | This is a wrapper around the completion mechanism, similar to what |
|
1003 | This is a wrapper around the completion mechanism, similar to what | |
1001 | readline does at the command line when the TAB key is hit. By |
|
1004 | readline does at the command line when the TAB key is hit. By | |
1002 | exposing it as a method, it can be used by other non-readline |
|
1005 | exposing it as a method, it can be used by other non-readline | |
1003 | environments (such as GUIs) for text completion. |
|
1006 | environments (such as GUIs) for text completion. | |
1004 |
|
1007 | |||
1005 | Simple usage example: |
|
1008 | Simple usage example: | |
1006 |
|
1009 | |||
1007 | In [1]: x = 'hello' |
|
1010 | In [1]: x = 'hello' | |
1008 |
|
1011 | |||
1009 | In [2]: __IP.complete('x.l') |
|
1012 | In [2]: __IP.complete('x.l') | |
1010 | Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']""" |
|
1013 | Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']""" | |
1011 |
|
1014 | |||
1012 | complete = self.Completer.complete |
|
1015 | complete = self.Completer.complete | |
1013 | state = 0 |
|
1016 | state = 0 | |
1014 | # use a dict so we get unique keys, since ipyhton's multiple |
|
1017 | # use a dict so we get unique keys, since ipyhton's multiple | |
1015 | # completers can return duplicates. When we make 2.4 a requirement, |
|
1018 | # completers can return duplicates. When we make 2.4 a requirement, | |
1016 | # start using sets instead, which are faster. |
|
1019 | # start using sets instead, which are faster. | |
1017 | comps = {} |
|
1020 | comps = {} | |
1018 | while True: |
|
1021 | while True: | |
1019 | newcomp = complete(text,state,line_buffer=text) |
|
1022 | newcomp = complete(text,state,line_buffer=text) | |
1020 | if newcomp is None: |
|
1023 | if newcomp is None: | |
1021 | break |
|
1024 | break | |
1022 | comps[newcomp] = 1 |
|
1025 | comps[newcomp] = 1 | |
1023 | state += 1 |
|
1026 | state += 1 | |
1024 | outcomps = comps.keys() |
|
1027 | outcomps = comps.keys() | |
1025 | outcomps.sort() |
|
1028 | outcomps.sort() | |
1026 | return outcomps |
|
1029 | return outcomps | |
1027 |
|
1030 | |||
1028 | def set_completer_frame(self, frame=None): |
|
1031 | def set_completer_frame(self, frame=None): | |
1029 | if frame: |
|
1032 | if frame: | |
1030 | self.Completer.namespace = frame.f_locals |
|
1033 | self.Completer.namespace = frame.f_locals | |
1031 | self.Completer.global_namespace = frame.f_globals |
|
1034 | self.Completer.global_namespace = frame.f_globals | |
1032 | else: |
|
1035 | else: | |
1033 | self.Completer.namespace = self.user_ns |
|
1036 | self.Completer.namespace = self.user_ns | |
1034 | self.Completer.global_namespace = self.user_global_ns |
|
1037 | self.Completer.global_namespace = self.user_global_ns | |
1035 |
|
1038 | |||
1036 | def init_auto_alias(self): |
|
1039 | def init_auto_alias(self): | |
1037 | """Define some aliases automatically. |
|
1040 | """Define some aliases automatically. | |
1038 |
|
1041 | |||
1039 | These are ALL parameter-less aliases""" |
|
1042 | These are ALL parameter-less aliases""" | |
1040 |
|
1043 | |||
1041 | for alias,cmd in self.auto_alias: |
|
1044 | for alias,cmd in self.auto_alias: | |
1042 | self.getapi().defalias(alias,cmd) |
|
1045 | self.getapi().defalias(alias,cmd) | |
1043 |
|
1046 | |||
1044 |
|
1047 | |||
1045 | def alias_table_validate(self,verbose=0): |
|
1048 | def alias_table_validate(self,verbose=0): | |
1046 | """Update information about the alias table. |
|
1049 | """Update information about the alias table. | |
1047 |
|
1050 | |||
1048 | In particular, make sure no Python keywords/builtins are in it.""" |
|
1051 | In particular, make sure no Python keywords/builtins are in it.""" | |
1049 |
|
1052 | |||
1050 | no_alias = self.no_alias |
|
1053 | no_alias = self.no_alias | |
1051 | for k in self.alias_table.keys(): |
|
1054 | for k in self.alias_table.keys(): | |
1052 | if k in no_alias: |
|
1055 | if k in no_alias: | |
1053 | del self.alias_table[k] |
|
1056 | del self.alias_table[k] | |
1054 | if verbose: |
|
1057 | if verbose: | |
1055 | print ("Deleting alias <%s>, it's a Python " |
|
1058 | print ("Deleting alias <%s>, it's a Python " | |
1056 | "keyword or builtin." % k) |
|
1059 | "keyword or builtin." % k) | |
1057 |
|
1060 | |||
1058 | def set_autoindent(self,value=None): |
|
1061 | def set_autoindent(self,value=None): | |
1059 | """Set the autoindent flag, checking for readline support. |
|
1062 | """Set the autoindent flag, checking for readline support. | |
1060 |
|
1063 | |||
1061 | If called with no arguments, it acts as a toggle.""" |
|
1064 | If called with no arguments, it acts as a toggle.""" | |
1062 |
|
1065 | |||
1063 | if not self.has_readline: |
|
1066 | if not self.has_readline: | |
1064 | if os.name == 'posix': |
|
1067 | if os.name == 'posix': | |
1065 | warn("The auto-indent feature requires the readline library") |
|
1068 | warn("The auto-indent feature requires the readline library") | |
1066 | self.autoindent = 0 |
|
1069 | self.autoindent = 0 | |
1067 | return |
|
1070 | return | |
1068 | if value is None: |
|
1071 | if value is None: | |
1069 | self.autoindent = not self.autoindent |
|
1072 | self.autoindent = not self.autoindent | |
1070 | else: |
|
1073 | else: | |
1071 | self.autoindent = value |
|
1074 | self.autoindent = value | |
1072 |
|
1075 | |||
1073 | def rc_set_toggle(self,rc_field,value=None): |
|
1076 | def rc_set_toggle(self,rc_field,value=None): | |
1074 | """Set or toggle a field in IPython's rc config. structure. |
|
1077 | """Set or toggle a field in IPython's rc config. structure. | |
1075 |
|
1078 | |||
1076 | If called with no arguments, it acts as a toggle. |
|
1079 | If called with no arguments, it acts as a toggle. | |
1077 |
|
1080 | |||
1078 | If called with a non-existent field, the resulting AttributeError |
|
1081 | If called with a non-existent field, the resulting AttributeError | |
1079 | exception will propagate out.""" |
|
1082 | exception will propagate out.""" | |
1080 |
|
1083 | |||
1081 | rc_val = getattr(self.rc,rc_field) |
|
1084 | rc_val = getattr(self.rc,rc_field) | |
1082 | if value is None: |
|
1085 | if value is None: | |
1083 | value = not rc_val |
|
1086 | value = not rc_val | |
1084 | setattr(self.rc,rc_field,value) |
|
1087 | setattr(self.rc,rc_field,value) | |
1085 |
|
1088 | |||
1086 | def user_setup(self,ipythondir,rc_suffix,mode='install'): |
|
1089 | def user_setup(self,ipythondir,rc_suffix,mode='install'): | |
1087 | """Install the user configuration directory. |
|
1090 | """Install the user configuration directory. | |
1088 |
|
1091 | |||
1089 | Can be called when running for the first time or to upgrade the user's |
|
1092 | Can be called when running for the first time or to upgrade the user's | |
1090 | .ipython/ directory with the mode parameter. Valid modes are 'install' |
|
1093 | .ipython/ directory with the mode parameter. Valid modes are 'install' | |
1091 | and 'upgrade'.""" |
|
1094 | and 'upgrade'.""" | |
1092 |
|
1095 | |||
1093 | def wait(): |
|
1096 | def wait(): | |
1094 | try: |
|
1097 | try: | |
1095 | raw_input("Please press <RETURN> to start IPython.") |
|
1098 | raw_input("Please press <RETURN> to start IPython.") | |
1096 | except EOFError: |
|
1099 | except EOFError: | |
1097 | print >> Term.cout |
|
1100 | print >> Term.cout | |
1098 | print '*'*70 |
|
1101 | print '*'*70 | |
1099 |
|
1102 | |||
1100 | cwd = os.getcwd() # remember where we started |
|
1103 | cwd = os.getcwd() # remember where we started | |
1101 | glb = glob.glob |
|
1104 | glb = glob.glob | |
1102 | print '*'*70 |
|
1105 | print '*'*70 | |
1103 | if mode == 'install': |
|
1106 | if mode == 'install': | |
1104 | print \ |
|
1107 | print \ | |
1105 | """Welcome to IPython. I will try to create a personal configuration directory |
|
1108 | """Welcome to IPython. I will try to create a personal configuration directory | |
1106 | where you can customize many aspects of IPython's functionality in:\n""" |
|
1109 | where you can customize many aspects of IPython's functionality in:\n""" | |
1107 | else: |
|
1110 | else: | |
1108 | print 'I am going to upgrade your configuration in:' |
|
1111 | print 'I am going to upgrade your configuration in:' | |
1109 |
|
1112 | |||
1110 | print ipythondir |
|
1113 | print ipythondir | |
1111 |
|
1114 | |||
1112 | rcdirend = os.path.join('IPython','UserConfig') |
|
1115 | rcdirend = os.path.join('IPython','UserConfig') | |
1113 | cfg = lambda d: os.path.join(d,rcdirend) |
|
1116 | cfg = lambda d: os.path.join(d,rcdirend) | |
1114 | try: |
|
1117 | try: | |
1115 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] |
|
1118 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] | |
1116 | print "Initializing from configuration",rcdir |
|
1119 | print "Initializing from configuration",rcdir | |
1117 | except IndexError: |
|
1120 | except IndexError: | |
1118 | warning = """ |
|
1121 | warning = """ | |
1119 | Installation error. IPython's directory was not found. |
|
1122 | Installation error. IPython's directory was not found. | |
1120 |
|
1123 | |||
1121 | Check the following: |
|
1124 | Check the following: | |
1122 |
|
1125 | |||
1123 | The ipython/IPython directory should be in a directory belonging to your |
|
1126 | The ipython/IPython directory should be in a directory belonging to your | |
1124 | PYTHONPATH environment variable (that is, it should be in a directory |
|
1127 | PYTHONPATH environment variable (that is, it should be in a directory | |
1125 | belonging to sys.path). You can copy it explicitly there or just link to it. |
|
1128 | belonging to sys.path). You can copy it explicitly there or just link to it. | |
1126 |
|
1129 | |||
1127 | IPython will create a minimal default configuration for you. |
|
1130 | IPython will create a minimal default configuration for you. | |
1128 |
|
1131 | |||
1129 | """ |
|
1132 | """ | |
1130 | warn(warning) |
|
1133 | warn(warning) | |
1131 | wait() |
|
1134 | wait() | |
1132 |
|
1135 | |||
1133 | if sys.platform =='win32': |
|
1136 | if sys.platform =='win32': | |
1134 | inif = 'ipythonrc.ini' |
|
1137 | inif = 'ipythonrc.ini' | |
1135 | else: |
|
1138 | else: | |
1136 | inif = 'ipythonrc' |
|
1139 | inif = 'ipythonrc' | |
1137 | minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', inif : '# intentionally left blank' } |
|
1140 | minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', inif : '# intentionally left blank' } | |
1138 | os.makedirs(ipythondir, mode = 0777) |
|
1141 | os.makedirs(ipythondir, mode = 0777) | |
1139 | for f, cont in minimal_setup.items(): |
|
1142 | for f, cont in minimal_setup.items(): | |
1140 | open(ipythondir + '/' + f,'w').write(cont) |
|
1143 | open(ipythondir + '/' + f,'w').write(cont) | |
1141 |
|
1144 | |||
1142 | return |
|
1145 | return | |
1143 |
|
1146 | |||
1144 | if mode == 'install': |
|
1147 | if mode == 'install': | |
1145 | try: |
|
1148 | try: | |
1146 | shutil.copytree(rcdir,ipythondir) |
|
1149 | shutil.copytree(rcdir,ipythondir) | |
1147 | os.chdir(ipythondir) |
|
1150 | os.chdir(ipythondir) | |
1148 | rc_files = glb("ipythonrc*") |
|
1151 | rc_files = glb("ipythonrc*") | |
1149 | for rc_file in rc_files: |
|
1152 | for rc_file in rc_files: | |
1150 | os.rename(rc_file,rc_file+rc_suffix) |
|
1153 | os.rename(rc_file,rc_file+rc_suffix) | |
1151 | except: |
|
1154 | except: | |
1152 | warning = """ |
|
1155 | warning = """ | |
1153 |
|
1156 | |||
1154 | There was a problem with the installation: |
|
1157 | There was a problem with the installation: | |
1155 | %s |
|
1158 | %s | |
1156 | Try to correct it or contact the developers if you think it's a bug. |
|
1159 | Try to correct it or contact the developers if you think it's a bug. | |
1157 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] |
|
1160 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] | |
1158 | warn(warning) |
|
1161 | warn(warning) | |
1159 | wait() |
|
1162 | wait() | |
1160 | return |
|
1163 | return | |
1161 |
|
1164 | |||
1162 | elif mode == 'upgrade': |
|
1165 | elif mode == 'upgrade': | |
1163 | try: |
|
1166 | try: | |
1164 | os.chdir(ipythondir) |
|
1167 | os.chdir(ipythondir) | |
1165 | except: |
|
1168 | except: | |
1166 | print """ |
|
1169 | print """ | |
1167 | Can not upgrade: changing to directory %s failed. Details: |
|
1170 | Can not upgrade: changing to directory %s failed. Details: | |
1168 | %s |
|
1171 | %s | |
1169 | """ % (ipythondir,sys.exc_info()[1]) |
|
1172 | """ % (ipythondir,sys.exc_info()[1]) | |
1170 | wait() |
|
1173 | wait() | |
1171 | return |
|
1174 | return | |
1172 | else: |
|
1175 | else: | |
1173 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) |
|
1176 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) | |
1174 | for new_full_path in sources: |
|
1177 | for new_full_path in sources: | |
1175 | new_filename = os.path.basename(new_full_path) |
|
1178 | new_filename = os.path.basename(new_full_path) | |
1176 | if new_filename.startswith('ipythonrc'): |
|
1179 | if new_filename.startswith('ipythonrc'): | |
1177 | new_filename = new_filename + rc_suffix |
|
1180 | new_filename = new_filename + rc_suffix | |
1178 | # The config directory should only contain files, skip any |
|
1181 | # The config directory should only contain files, skip any | |
1179 | # directories which may be there (like CVS) |
|
1182 | # directories which may be there (like CVS) | |
1180 | if os.path.isdir(new_full_path): |
|
1183 | if os.path.isdir(new_full_path): | |
1181 | continue |
|
1184 | continue | |
1182 | if os.path.exists(new_filename): |
|
1185 | if os.path.exists(new_filename): | |
1183 | old_file = new_filename+'.old' |
|
1186 | old_file = new_filename+'.old' | |
1184 | if os.path.exists(old_file): |
|
1187 | if os.path.exists(old_file): | |
1185 | os.remove(old_file) |
|
1188 | os.remove(old_file) | |
1186 | os.rename(new_filename,old_file) |
|
1189 | os.rename(new_filename,old_file) | |
1187 | shutil.copy(new_full_path,new_filename) |
|
1190 | shutil.copy(new_full_path,new_filename) | |
1188 | else: |
|
1191 | else: | |
1189 | raise ValueError,'unrecognized mode for install:',`mode` |
|
1192 | raise ValueError,'unrecognized mode for install:',`mode` | |
1190 |
|
1193 | |||
1191 | # Fix line-endings to those native to each platform in the config |
|
1194 | # Fix line-endings to those native to each platform in the config | |
1192 | # directory. |
|
1195 | # directory. | |
1193 | try: |
|
1196 | try: | |
1194 | os.chdir(ipythondir) |
|
1197 | os.chdir(ipythondir) | |
1195 | except: |
|
1198 | except: | |
1196 | print """ |
|
1199 | print """ | |
1197 | Problem: changing to directory %s failed. |
|
1200 | Problem: changing to directory %s failed. | |
1198 | Details: |
|
1201 | Details: | |
1199 | %s |
|
1202 | %s | |
1200 |
|
1203 | |||
1201 | Some configuration files may have incorrect line endings. This should not |
|
1204 | Some configuration files may have incorrect line endings. This should not | |
1202 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) |
|
1205 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) | |
1203 | wait() |
|
1206 | wait() | |
1204 | else: |
|
1207 | else: | |
1205 | for fname in glb('ipythonrc*'): |
|
1208 | for fname in glb('ipythonrc*'): | |
1206 | try: |
|
1209 | try: | |
1207 | native_line_ends(fname,backup=0) |
|
1210 | native_line_ends(fname,backup=0) | |
1208 | except IOError: |
|
1211 | except IOError: | |
1209 | pass |
|
1212 | pass | |
1210 |
|
1213 | |||
1211 | if mode == 'install': |
|
1214 | if mode == 'install': | |
1212 | print """ |
|
1215 | print """ | |
1213 | Successful installation! |
|
1216 | Successful installation! | |
1214 |
|
1217 | |||
1215 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the |
|
1218 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the | |
1216 | IPython manual (there are both HTML and PDF versions supplied with the |
|
1219 | IPython manual (there are both HTML and PDF versions supplied with the | |
1217 | distribution) to make sure that your system environment is properly configured |
|
1220 | distribution) to make sure that your system environment is properly configured | |
1218 | to take advantage of IPython's features. |
|
1221 | to take advantage of IPython's features. | |
1219 |
|
1222 | |||
1220 | Important note: the configuration system has changed! The old system is |
|
1223 | Important note: the configuration system has changed! The old system is | |
1221 | still in place, but its setting may be partly overridden by the settings in |
|
1224 | still in place, but its setting may be partly overridden by the settings in | |
1222 | "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file |
|
1225 | "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file | |
1223 | if some of the new settings bother you. |
|
1226 | if some of the new settings bother you. | |
1224 |
|
1227 | |||
1225 | """ |
|
1228 | """ | |
1226 | else: |
|
1229 | else: | |
1227 | print """ |
|
1230 | print """ | |
1228 | Successful upgrade! |
|
1231 | Successful upgrade! | |
1229 |
|
1232 | |||
1230 | All files in your directory: |
|
1233 | All files in your directory: | |
1231 | %(ipythondir)s |
|
1234 | %(ipythondir)s | |
1232 | which would have been overwritten by the upgrade were backed up with a .old |
|
1235 | which would have been overwritten by the upgrade were backed up with a .old | |
1233 | extension. If you had made particular customizations in those files you may |
|
1236 | extension. If you had made particular customizations in those files you may | |
1234 | want to merge them back into the new files.""" % locals() |
|
1237 | want to merge them back into the new files.""" % locals() | |
1235 | wait() |
|
1238 | wait() | |
1236 | os.chdir(cwd) |
|
1239 | os.chdir(cwd) | |
1237 | # end user_setup() |
|
1240 | # end user_setup() | |
1238 |
|
1241 | |||
1239 | def atexit_operations(self): |
|
1242 | def atexit_operations(self): | |
1240 | """This will be executed at the time of exit. |
|
1243 | """This will be executed at the time of exit. | |
1241 |
|
1244 | |||
1242 | Saving of persistent data should be performed here. """ |
|
1245 | Saving of persistent data should be performed here. """ | |
1243 |
|
1246 | |||
1244 | #print '*** IPython exit cleanup ***' # dbg |
|
1247 | #print '*** IPython exit cleanup ***' # dbg | |
1245 | # input history |
|
1248 | # input history | |
1246 | self.savehist() |
|
1249 | self.savehist() | |
1247 |
|
1250 | |||
1248 | # Cleanup all tempfiles left around |
|
1251 | # Cleanup all tempfiles left around | |
1249 | for tfile in self.tempfiles: |
|
1252 | for tfile in self.tempfiles: | |
1250 | try: |
|
1253 | try: | |
1251 | os.unlink(tfile) |
|
1254 | os.unlink(tfile) | |
1252 | except OSError: |
|
1255 | except OSError: | |
1253 | pass |
|
1256 | pass | |
1254 |
|
1257 | |||
1255 | self.hooks.shutdown_hook() |
|
1258 | self.hooks.shutdown_hook() | |
1256 |
|
1259 | |||
1257 | def savehist(self): |
|
1260 | def savehist(self): | |
1258 | """Save input history to a file (via readline library).""" |
|
1261 | """Save input history to a file (via readline library).""" | |
1259 |
|
1262 | |||
1260 | if not self.has_readline: |
|
1263 | if not self.has_readline: | |
1261 | return |
|
1264 | return | |
1262 |
|
1265 | |||
1263 | try: |
|
1266 | try: | |
1264 | self.readline.write_history_file(self.histfile) |
|
1267 | self.readline.write_history_file(self.histfile) | |
1265 | except: |
|
1268 | except: | |
1266 | print 'Unable to save IPython command history to file: ' + \ |
|
1269 | print 'Unable to save IPython command history to file: ' + \ | |
1267 | `self.histfile` |
|
1270 | `self.histfile` | |
1268 |
|
1271 | |||
1269 | def reloadhist(self): |
|
1272 | def reloadhist(self): | |
1270 | """Reload the input history from disk file.""" |
|
1273 | """Reload the input history from disk file.""" | |
1271 |
|
1274 | |||
1272 | if self.has_readline: |
|
1275 | if self.has_readline: | |
1273 | try: |
|
1276 | try: | |
1274 | self.readline.clear_history() |
|
1277 | self.readline.clear_history() | |
1275 | self.readline.read_history_file(self.shell.histfile) |
|
1278 | self.readline.read_history_file(self.shell.histfile) | |
1276 | except AttributeError: |
|
1279 | except AttributeError: | |
1277 | pass |
|
1280 | pass | |
1278 |
|
1281 | |||
1279 |
|
1282 | |||
1280 | def history_saving_wrapper(self, func): |
|
1283 | def history_saving_wrapper(self, func): | |
1281 | """ Wrap func for readline history saving |
|
1284 | """ Wrap func for readline history saving | |
1282 |
|
1285 | |||
1283 | Convert func into callable that saves & restores |
|
1286 | Convert func into callable that saves & restores | |
1284 | history around the call """ |
|
1287 | history around the call """ | |
1285 |
|
1288 | |||
1286 | if not self.has_readline: |
|
1289 | if not self.has_readline: | |
1287 | return func |
|
1290 | return func | |
1288 |
|
1291 | |||
1289 | def wrapper(): |
|
1292 | def wrapper(): | |
1290 | self.savehist() |
|
1293 | self.savehist() | |
1291 | try: |
|
1294 | try: | |
1292 | func() |
|
1295 | func() | |
1293 | finally: |
|
1296 | finally: | |
1294 | readline.read_history_file(self.histfile) |
|
1297 | readline.read_history_file(self.histfile) | |
1295 | return wrapper |
|
1298 | return wrapper | |
1296 |
|
1299 | |||
1297 |
|
1300 | |||
1298 | def pre_readline(self): |
|
1301 | def pre_readline(self): | |
1299 | """readline hook to be used at the start of each line. |
|
1302 | """readline hook to be used at the start of each line. | |
1300 |
|
1303 | |||
1301 | Currently it handles auto-indent only.""" |
|
1304 | Currently it handles auto-indent only.""" | |
1302 |
|
1305 | |||
1303 | #debugx('self.indent_current_nsp','pre_readline:') |
|
1306 | #debugx('self.indent_current_nsp','pre_readline:') | |
1304 |
|
1307 | |||
1305 | if self.rl_do_indent: |
|
1308 | if self.rl_do_indent: | |
1306 | self.readline.insert_text(self.indent_current_str()) |
|
1309 | self.readline.insert_text(self.indent_current_str()) | |
1307 | if self.rl_next_input is not None: |
|
1310 | if self.rl_next_input is not None: | |
1308 | self.readline.insert_text(self.rl_next_input) |
|
1311 | self.readline.insert_text(self.rl_next_input) | |
1309 | self.rl_next_input = None |
|
1312 | self.rl_next_input = None | |
1310 |
|
1313 | |||
1311 | def init_readline(self): |
|
1314 | def init_readline(self): | |
1312 | """Command history completion/saving/reloading.""" |
|
1315 | """Command history completion/saving/reloading.""" | |
1313 |
|
1316 | |||
1314 |
|
1317 | |||
1315 | import IPython.rlineimpl as readline |
|
1318 | import IPython.rlineimpl as readline | |
1316 |
|
1319 | |||
1317 | if not readline.have_readline: |
|
1320 | if not readline.have_readline: | |
1318 | self.has_readline = 0 |
|
1321 | self.has_readline = 0 | |
1319 | self.readline = None |
|
1322 | self.readline = None | |
1320 | # no point in bugging windows users with this every time: |
|
1323 | # no point in bugging windows users with this every time: | |
1321 | warn('Readline services not available on this platform.') |
|
1324 | warn('Readline services not available on this platform.') | |
1322 | else: |
|
1325 | else: | |
1323 | sys.modules['readline'] = readline |
|
1326 | sys.modules['readline'] = readline | |
1324 | import atexit |
|
1327 | import atexit | |
1325 | from IPython.completer import IPCompleter |
|
1328 | from IPython.completer import IPCompleter | |
1326 | self.Completer = IPCompleter(self, |
|
1329 | self.Completer = IPCompleter(self, | |
1327 | self.user_ns, |
|
1330 | self.user_ns, | |
1328 | self.user_global_ns, |
|
1331 | self.user_global_ns, | |
1329 | self.rc.readline_omit__names, |
|
1332 | self.rc.readline_omit__names, | |
1330 | self.alias_table) |
|
1333 | self.alias_table) | |
1331 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1334 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1332 | self.strdispatchers['complete_command'] = sdisp |
|
1335 | self.strdispatchers['complete_command'] = sdisp | |
1333 | self.Completer.custom_completers = sdisp |
|
1336 | self.Completer.custom_completers = sdisp | |
1334 | # Platform-specific configuration |
|
1337 | # Platform-specific configuration | |
1335 | if os.name == 'nt': |
|
1338 | if os.name == 'nt': | |
1336 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1339 | self.readline_startup_hook = readline.set_pre_input_hook | |
1337 | else: |
|
1340 | else: | |
1338 | self.readline_startup_hook = readline.set_startup_hook |
|
1341 | self.readline_startup_hook = readline.set_startup_hook | |
1339 |
|
1342 | |||
1340 | # Load user's initrc file (readline config) |
|
1343 | # Load user's initrc file (readline config) | |
1341 | # Or if libedit is used, load editrc. |
|
1344 | # Or if libedit is used, load editrc. | |
1342 | inputrc_name = os.environ.get('INPUTRC') |
|
1345 | inputrc_name = os.environ.get('INPUTRC') | |
1343 | if inputrc_name is None: |
|
1346 | if inputrc_name is None: | |
1344 | home_dir = get_home_dir() |
|
1347 | home_dir = get_home_dir() | |
1345 | if home_dir is not None: |
|
1348 | if home_dir is not None: | |
1346 | inputrc_name = '.inputrc' |
|
1349 | inputrc_name = '.inputrc' | |
1347 | if readline.uses_libedit: |
|
1350 | if readline.uses_libedit: | |
1348 | inputrc_name = '.editrc' |
|
1351 | inputrc_name = '.editrc' | |
1349 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1352 | inputrc_name = os.path.join(home_dir, inputrc_name) | |
1350 | if os.path.isfile(inputrc_name): |
|
1353 | if os.path.isfile(inputrc_name): | |
1351 | try: |
|
1354 | try: | |
1352 | readline.read_init_file(inputrc_name) |
|
1355 | readline.read_init_file(inputrc_name) | |
1353 | except: |
|
1356 | except: | |
1354 | warn('Problems reading readline initialization file <%s>' |
|
1357 | warn('Problems reading readline initialization file <%s>' | |
1355 | % inputrc_name) |
|
1358 | % inputrc_name) | |
1356 |
|
1359 | |||
1357 | self.has_readline = 1 |
|
1360 | self.has_readline = 1 | |
1358 | self.readline = readline |
|
1361 | self.readline = readline | |
1359 | # save this in sys so embedded copies can restore it properly |
|
1362 | # save this in sys so embedded copies can restore it properly | |
1360 | sys.ipcompleter = self.Completer.complete |
|
1363 | sys.ipcompleter = self.Completer.complete | |
1361 | self.set_completer() |
|
1364 | self.set_completer() | |
1362 |
|
1365 | |||
1363 | # Configure readline according to user's prefs |
|
1366 | # Configure readline according to user's prefs | |
1364 | # This is only done if GNU readline is being used. If libedit |
|
1367 | # This is only done if GNU readline is being used. If libedit | |
1365 | # is being used (as on Leopard) the readline config is |
|
1368 | # is being used (as on Leopard) the readline config is | |
1366 | # not run as the syntax for libedit is different. |
|
1369 | # not run as the syntax for libedit is different. | |
1367 | if not readline.uses_libedit: |
|
1370 | if not readline.uses_libedit: | |
1368 | for rlcommand in self.rc.readline_parse_and_bind: |
|
1371 | for rlcommand in self.rc.readline_parse_and_bind: | |
1369 | readline.parse_and_bind(rlcommand) |
|
1372 | readline.parse_and_bind(rlcommand) | |
1370 |
|
1373 | |||
1371 | # remove some chars from the delimiters list |
|
1374 | # remove some chars from the delimiters list | |
1372 | delims = readline.get_completer_delims() |
|
1375 | delims = readline.get_completer_delims() | |
1373 | delims = delims.translate(string._idmap, |
|
1376 | delims = delims.translate(string._idmap, | |
1374 | self.rc.readline_remove_delims) |
|
1377 | self.rc.readline_remove_delims) | |
1375 | readline.set_completer_delims(delims) |
|
1378 | readline.set_completer_delims(delims) | |
1376 | # otherwise we end up with a monster history after a while: |
|
1379 | # otherwise we end up with a monster history after a while: | |
1377 | readline.set_history_length(1000) |
|
1380 | readline.set_history_length(1000) | |
1378 | try: |
|
1381 | try: | |
1379 | #print '*** Reading readline history' # dbg |
|
1382 | #print '*** Reading readline history' # dbg | |
1380 | readline.read_history_file(self.histfile) |
|
1383 | readline.read_history_file(self.histfile) | |
1381 | except IOError: |
|
1384 | except IOError: | |
1382 | pass # It doesn't exist yet. |
|
1385 | pass # It doesn't exist yet. | |
1383 |
|
1386 | |||
1384 | atexit.register(self.atexit_operations) |
|
1387 | atexit.register(self.atexit_operations) | |
1385 | del atexit |
|
1388 | del atexit | |
1386 |
|
1389 | |||
1387 | # Configure auto-indent for all platforms |
|
1390 | # Configure auto-indent for all platforms | |
1388 | self.set_autoindent(self.rc.autoindent) |
|
1391 | self.set_autoindent(self.rc.autoindent) | |
1389 |
|
1392 | |||
1390 | def ask_yes_no(self,prompt,default=True): |
|
1393 | def ask_yes_no(self,prompt,default=True): | |
1391 | if self.rc.quiet: |
|
1394 | if self.rc.quiet: | |
1392 | return True |
|
1395 | return True | |
1393 | return ask_yes_no(prompt,default) |
|
1396 | return ask_yes_no(prompt,default) | |
1394 |
|
1397 | |||
1395 | def _should_recompile(self,e): |
|
1398 | def _should_recompile(self,e): | |
1396 | """Utility routine for edit_syntax_error""" |
|
1399 | """Utility routine for edit_syntax_error""" | |
1397 |
|
1400 | |||
1398 | if e.filename in ('<ipython console>','<input>','<string>', |
|
1401 | if e.filename in ('<ipython console>','<input>','<string>', | |
1399 | '<console>','<BackgroundJob compilation>', |
|
1402 | '<console>','<BackgroundJob compilation>', | |
1400 | None): |
|
1403 | None): | |
1401 |
|
1404 | |||
1402 | return False |
|
1405 | return False | |
1403 | try: |
|
1406 | try: | |
1404 | if (self.rc.autoedit_syntax and |
|
1407 | if (self.rc.autoedit_syntax and | |
1405 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
1408 | not self.ask_yes_no('Return to editor to correct syntax error? ' | |
1406 | '[Y/n] ','y')): |
|
1409 | '[Y/n] ','y')): | |
1407 | return False |
|
1410 | return False | |
1408 | except EOFError: |
|
1411 | except EOFError: | |
1409 | return False |
|
1412 | return False | |
1410 |
|
1413 | |||
1411 | def int0(x): |
|
1414 | def int0(x): | |
1412 | try: |
|
1415 | try: | |
1413 | return int(x) |
|
1416 | return int(x) | |
1414 | except TypeError: |
|
1417 | except TypeError: | |
1415 | return 0 |
|
1418 | return 0 | |
1416 | # always pass integer line and offset values to editor hook |
|
1419 | # always pass integer line and offset values to editor hook | |
1417 | self.hooks.fix_error_editor(e.filename, |
|
1420 | self.hooks.fix_error_editor(e.filename, | |
1418 | int0(e.lineno),int0(e.offset),e.msg) |
|
1421 | int0(e.lineno),int0(e.offset),e.msg) | |
1419 | return True |
|
1422 | return True | |
1420 |
|
1423 | |||
1421 | def edit_syntax_error(self): |
|
1424 | def edit_syntax_error(self): | |
1422 | """The bottom half of the syntax error handler called in the main loop. |
|
1425 | """The bottom half of the syntax error handler called in the main loop. | |
1423 |
|
1426 | |||
1424 | Loop until syntax error is fixed or user cancels. |
|
1427 | Loop until syntax error is fixed or user cancels. | |
1425 | """ |
|
1428 | """ | |
1426 |
|
1429 | |||
1427 | while self.SyntaxTB.last_syntax_error: |
|
1430 | while self.SyntaxTB.last_syntax_error: | |
1428 | # copy and clear last_syntax_error |
|
1431 | # copy and clear last_syntax_error | |
1429 | err = self.SyntaxTB.clear_err_state() |
|
1432 | err = self.SyntaxTB.clear_err_state() | |
1430 | if not self._should_recompile(err): |
|
1433 | if not self._should_recompile(err): | |
1431 | return |
|
1434 | return | |
1432 | try: |
|
1435 | try: | |
1433 | # may set last_syntax_error again if a SyntaxError is raised |
|
1436 | # may set last_syntax_error again if a SyntaxError is raised | |
1434 | self.safe_execfile(err.filename,self.user_ns) |
|
1437 | self.safe_execfile(err.filename,self.user_ns) | |
1435 | except: |
|
1438 | except: | |
1436 | self.showtraceback() |
|
1439 | self.showtraceback() | |
1437 | else: |
|
1440 | else: | |
1438 | try: |
|
1441 | try: | |
1439 | f = file(err.filename) |
|
1442 | f = file(err.filename) | |
1440 | try: |
|
1443 | try: | |
1441 | sys.displayhook(f.read()) |
|
1444 | sys.displayhook(f.read()) | |
1442 | finally: |
|
1445 | finally: | |
1443 | f.close() |
|
1446 | f.close() | |
1444 | except: |
|
1447 | except: | |
1445 | self.showtraceback() |
|
1448 | self.showtraceback() | |
1446 |
|
1449 | |||
1447 | def showsyntaxerror(self, filename=None): |
|
1450 | def showsyntaxerror(self, filename=None): | |
1448 | """Display the syntax error that just occurred. |
|
1451 | """Display the syntax error that just occurred. | |
1449 |
|
1452 | |||
1450 | This doesn't display a stack trace because there isn't one. |
|
1453 | This doesn't display a stack trace because there isn't one. | |
1451 |
|
1454 | |||
1452 | If a filename is given, it is stuffed in the exception instead |
|
1455 | If a filename is given, it is stuffed in the exception instead | |
1453 | of what was there before (because Python's parser always uses |
|
1456 | of what was there before (because Python's parser always uses | |
1454 | "<string>" when reading from a string). |
|
1457 | "<string>" when reading from a string). | |
1455 | """ |
|
1458 | """ | |
1456 | etype, value, last_traceback = sys.exc_info() |
|
1459 | etype, value, last_traceback = sys.exc_info() | |
1457 |
|
1460 | |||
1458 | # See note about these variables in showtraceback() below |
|
1461 | # See note about these variables in showtraceback() below | |
1459 | sys.last_type = etype |
|
1462 | sys.last_type = etype | |
1460 | sys.last_value = value |
|
1463 | sys.last_value = value | |
1461 | sys.last_traceback = last_traceback |
|
1464 | sys.last_traceback = last_traceback | |
1462 |
|
1465 | |||
1463 | if filename and etype is SyntaxError: |
|
1466 | if filename and etype is SyntaxError: | |
1464 | # Work hard to stuff the correct filename in the exception |
|
1467 | # Work hard to stuff the correct filename in the exception | |
1465 | try: |
|
1468 | try: | |
1466 | msg, (dummy_filename, lineno, offset, line) = value |
|
1469 | msg, (dummy_filename, lineno, offset, line) = value | |
1467 | except: |
|
1470 | except: | |
1468 | # Not the format we expect; leave it alone |
|
1471 | # Not the format we expect; leave it alone | |
1469 | pass |
|
1472 | pass | |
1470 | else: |
|
1473 | else: | |
1471 | # Stuff in the right filename |
|
1474 | # Stuff in the right filename | |
1472 | try: |
|
1475 | try: | |
1473 | # Assume SyntaxError is a class exception |
|
1476 | # Assume SyntaxError is a class exception | |
1474 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1477 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1475 | except: |
|
1478 | except: | |
1476 | # If that failed, assume SyntaxError is a string |
|
1479 | # If that failed, assume SyntaxError is a string | |
1477 | value = msg, (filename, lineno, offset, line) |
|
1480 | value = msg, (filename, lineno, offset, line) | |
1478 | self.SyntaxTB(etype,value,[]) |
|
1481 | self.SyntaxTB(etype,value,[]) | |
1479 |
|
1482 | |||
1480 | def debugger(self,force=False): |
|
1483 | def debugger(self,force=False): | |
1481 | """Call the pydb/pdb debugger. |
|
1484 | """Call the pydb/pdb debugger. | |
1482 |
|
1485 | |||
1483 | Keywords: |
|
1486 | Keywords: | |
1484 |
|
1487 | |||
1485 | - force(False): by default, this routine checks the instance call_pdb |
|
1488 | - force(False): by default, this routine checks the instance call_pdb | |
1486 | flag and does not actually invoke the debugger if the flag is false. |
|
1489 | flag and does not actually invoke the debugger if the flag is false. | |
1487 | The 'force' option forces the debugger to activate even if the flag |
|
1490 | The 'force' option forces the debugger to activate even if the flag | |
1488 | is false. |
|
1491 | is false. | |
1489 | """ |
|
1492 | """ | |
1490 |
|
1493 | |||
1491 | if not (force or self.call_pdb): |
|
1494 | if not (force or self.call_pdb): | |
1492 | return |
|
1495 | return | |
1493 |
|
1496 | |||
1494 | if not hasattr(sys,'last_traceback'): |
|
1497 | if not hasattr(sys,'last_traceback'): | |
1495 | error('No traceback has been produced, nothing to debug.') |
|
1498 | error('No traceback has been produced, nothing to debug.') | |
1496 | return |
|
1499 | return | |
1497 |
|
1500 | |||
1498 | # use pydb if available |
|
1501 | # use pydb if available | |
1499 | if Debugger.has_pydb: |
|
1502 | if Debugger.has_pydb: | |
1500 | from pydb import pm |
|
1503 | from pydb import pm | |
1501 | else: |
|
1504 | else: | |
1502 | # fallback to our internal debugger |
|
1505 | # fallback to our internal debugger | |
1503 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
1506 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
1504 | self.history_saving_wrapper(pm)() |
|
1507 | self.history_saving_wrapper(pm)() | |
1505 |
|
1508 | |||
1506 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): |
|
1509 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): | |
1507 | """Display the exception that just occurred. |
|
1510 | """Display the exception that just occurred. | |
1508 |
|
1511 | |||
1509 | If nothing is known about the exception, this is the method which |
|
1512 | If nothing is known about the exception, this is the method which | |
1510 | should be used throughout the code for presenting user tracebacks, |
|
1513 | should be used throughout the code for presenting user tracebacks, | |
1511 | rather than directly invoking the InteractiveTB object. |
|
1514 | rather than directly invoking the InteractiveTB object. | |
1512 |
|
1515 | |||
1513 | A specific showsyntaxerror() also exists, but this method can take |
|
1516 | A specific showsyntaxerror() also exists, but this method can take | |
1514 | care of calling it if needed, so unless you are explicitly catching a |
|
1517 | care of calling it if needed, so unless you are explicitly catching a | |
1515 | SyntaxError exception, don't try to analyze the stack manually and |
|
1518 | SyntaxError exception, don't try to analyze the stack manually and | |
1516 | simply call this method.""" |
|
1519 | simply call this method.""" | |
1517 |
|
1520 | |||
1518 |
|
1521 | |||
1519 | # Though this won't be called by syntax errors in the input line, |
|
1522 | # Though this won't be called by syntax errors in the input line, | |
1520 | # there may be SyntaxError cases whith imported code. |
|
1523 | # there may be SyntaxError cases whith imported code. | |
1521 |
|
1524 | |||
1522 | try: |
|
1525 | try: | |
1523 | if exc_tuple is None: |
|
1526 | if exc_tuple is None: | |
1524 | etype, value, tb = sys.exc_info() |
|
1527 | etype, value, tb = sys.exc_info() | |
1525 | else: |
|
1528 | else: | |
1526 | etype, value, tb = exc_tuple |
|
1529 | etype, value, tb = exc_tuple | |
1527 |
|
1530 | |||
1528 | if etype is SyntaxError: |
|
1531 | if etype is SyntaxError: | |
1529 | self.showsyntaxerror(filename) |
|
1532 | self.showsyntaxerror(filename) | |
1530 | elif etype is IPython.ipapi.UsageError: |
|
1533 | elif etype is IPython.ipapi.UsageError: | |
1531 | print "UsageError:", value |
|
1534 | print "UsageError:", value | |
1532 | else: |
|
1535 | else: | |
1533 | # WARNING: these variables are somewhat deprecated and not |
|
1536 | # WARNING: these variables are somewhat deprecated and not | |
1534 | # necessarily safe to use in a threaded environment, but tools |
|
1537 | # necessarily safe to use in a threaded environment, but tools | |
1535 | # like pdb depend on their existence, so let's set them. If we |
|
1538 | # like pdb depend on their existence, so let's set them. If we | |
1536 | # find problems in the field, we'll need to revisit their use. |
|
1539 | # find problems in the field, we'll need to revisit their use. | |
1537 | sys.last_type = etype |
|
1540 | sys.last_type = etype | |
1538 | sys.last_value = value |
|
1541 | sys.last_value = value | |
1539 | sys.last_traceback = tb |
|
1542 | sys.last_traceback = tb | |
1540 |
|
1543 | |||
1541 | if etype in self.custom_exceptions: |
|
1544 | if etype in self.custom_exceptions: | |
1542 | self.CustomTB(etype,value,tb) |
|
1545 | self.CustomTB(etype,value,tb) | |
1543 | else: |
|
1546 | else: | |
1544 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) |
|
1547 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) | |
1545 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1548 | if self.InteractiveTB.call_pdb and self.has_readline: | |
1546 | # pdb mucks up readline, fix it back |
|
1549 | # pdb mucks up readline, fix it back | |
1547 | self.set_completer() |
|
1550 | self.set_completer() | |
1548 | except KeyboardInterrupt: |
|
1551 | except KeyboardInterrupt: | |
1549 | self.write("\nKeyboardInterrupt\n") |
|
1552 | self.write("\nKeyboardInterrupt\n") | |
1550 |
|
1553 | |||
1551 |
|
1554 | |||
1552 |
|
1555 | |||
1553 | def mainloop(self,banner=None): |
|
1556 | def mainloop(self,banner=None): | |
1554 | """Creates the local namespace and starts the mainloop. |
|
1557 | """Creates the local namespace and starts the mainloop. | |
1555 |
|
1558 | |||
1556 | If an optional banner argument is given, it will override the |
|
1559 | If an optional banner argument is given, it will override the | |
1557 | internally created default banner.""" |
|
1560 | internally created default banner.""" | |
1558 |
|
1561 | |||
1559 | if self.rc.c: # Emulate Python's -c option |
|
1562 | if self.rc.c: # Emulate Python's -c option | |
1560 | self.exec_init_cmd() |
|
1563 | self.exec_init_cmd() | |
1561 | if banner is None: |
|
1564 | if banner is None: | |
1562 | if not self.rc.banner: |
|
1565 | if not self.rc.banner: | |
1563 | banner = '' |
|
1566 | banner = '' | |
1564 | # banner is string? Use it directly! |
|
1567 | # banner is string? Use it directly! | |
1565 | elif isinstance(self.rc.banner,basestring): |
|
1568 | elif isinstance(self.rc.banner,basestring): | |
1566 | banner = self.rc.banner |
|
1569 | banner = self.rc.banner | |
1567 | else: |
|
1570 | else: | |
1568 | banner = self.BANNER+self.banner2 |
|
1571 | banner = self.BANNER+self.banner2 | |
1569 |
|
1572 | |||
1570 | while 1: |
|
1573 | while 1: | |
1571 | try: |
|
1574 | try: | |
1572 | self.interact(banner) |
|
1575 | self.interact(banner) | |
1573 | #self.interact_with_readline() |
|
1576 | #self.interact_with_readline() | |
1574 | # XXX for testing of a readline-decoupled repl loop, call interact_with_readline above |
|
1577 | # XXX for testing of a readline-decoupled repl loop, call interact_with_readline above | |
1575 |
|
1578 | |||
1576 | break |
|
1579 | break | |
1577 | except KeyboardInterrupt: |
|
1580 | except KeyboardInterrupt: | |
1578 | # this should not be necessary, but KeyboardInterrupt |
|
1581 | # this should not be necessary, but KeyboardInterrupt | |
1579 | # handling seems rather unpredictable... |
|
1582 | # handling seems rather unpredictable... | |
1580 | self.write("\nKeyboardInterrupt in interact()\n") |
|
1583 | self.write("\nKeyboardInterrupt in interact()\n") | |
1581 |
|
1584 | |||
1582 | def exec_init_cmd(self): |
|
1585 | def exec_init_cmd(self): | |
1583 | """Execute a command given at the command line. |
|
1586 | """Execute a command given at the command line. | |
1584 |
|
1587 | |||
1585 | This emulates Python's -c option.""" |
|
1588 | This emulates Python's -c option.""" | |
1586 |
|
1589 | |||
1587 | #sys.argv = ['-c'] |
|
1590 | #sys.argv = ['-c'] | |
1588 | self.push(self.prefilter(self.rc.c, False)) |
|
1591 | self.push(self.prefilter(self.rc.c, False)) | |
1589 | if not self.rc.interact: |
|
1592 | if not self.rc.interact: | |
1590 | self.exit_now = True |
|
1593 | self.exit_now = True | |
1591 |
|
1594 | |||
1592 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): |
|
1595 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): | |
1593 | """Embeds IPython into a running python program. |
|
1596 | """Embeds IPython into a running python program. | |
1594 |
|
1597 | |||
1595 | Input: |
|
1598 | Input: | |
1596 |
|
1599 | |||
1597 | - header: An optional header message can be specified. |
|
1600 | - header: An optional header message can be specified. | |
1598 |
|
1601 | |||
1599 | - local_ns, global_ns: working namespaces. If given as None, the |
|
1602 | - local_ns, global_ns: working namespaces. If given as None, the | |
1600 | IPython-initialized one is updated with __main__.__dict__, so that |
|
1603 | IPython-initialized one is updated with __main__.__dict__, so that | |
1601 | program variables become visible but user-specific configuration |
|
1604 | program variables become visible but user-specific configuration | |
1602 | remains possible. |
|
1605 | remains possible. | |
1603 |
|
1606 | |||
1604 | - stack_depth: specifies how many levels in the stack to go to |
|
1607 | - stack_depth: specifies how many levels in the stack to go to | |
1605 | looking for namespaces (when local_ns and global_ns are None). This |
|
1608 | looking for namespaces (when local_ns and global_ns are None). This | |
1606 | allows an intermediate caller to make sure that this function gets |
|
1609 | allows an intermediate caller to make sure that this function gets | |
1607 | the namespace from the intended level in the stack. By default (0) |
|
1610 | the namespace from the intended level in the stack. By default (0) | |
1608 | it will get its locals and globals from the immediate caller. |
|
1611 | it will get its locals and globals from the immediate caller. | |
1609 |
|
1612 | |||
1610 | Warning: it's possible to use this in a program which is being run by |
|
1613 | Warning: it's possible to use this in a program which is being run by | |
1611 | IPython itself (via %run), but some funny things will happen (a few |
|
1614 | IPython itself (via %run), but some funny things will happen (a few | |
1612 | globals get overwritten). In the future this will be cleaned up, as |
|
1615 | globals get overwritten). In the future this will be cleaned up, as | |
1613 | there is no fundamental reason why it can't work perfectly.""" |
|
1616 | there is no fundamental reason why it can't work perfectly.""" | |
1614 |
|
1617 | |||
1615 | # Get locals and globals from caller |
|
1618 | # Get locals and globals from caller | |
1616 | if local_ns is None or global_ns is None: |
|
1619 | if local_ns is None or global_ns is None: | |
1617 | call_frame = sys._getframe(stack_depth).f_back |
|
1620 | call_frame = sys._getframe(stack_depth).f_back | |
1618 |
|
1621 | |||
1619 | if local_ns is None: |
|
1622 | if local_ns is None: | |
1620 | local_ns = call_frame.f_locals |
|
1623 | local_ns = call_frame.f_locals | |
1621 | if global_ns is None: |
|
1624 | if global_ns is None: | |
1622 | global_ns = call_frame.f_globals |
|
1625 | global_ns = call_frame.f_globals | |
1623 |
|
1626 | |||
1624 | # Update namespaces and fire up interpreter |
|
1627 | # Update namespaces and fire up interpreter | |
1625 |
|
1628 | |||
1626 | # The global one is easy, we can just throw it in |
|
1629 | # The global one is easy, we can just throw it in | |
1627 | self.user_global_ns = global_ns |
|
1630 | self.user_global_ns = global_ns | |
1628 |
|
1631 | |||
1629 | # but the user/local one is tricky: ipython needs it to store internal |
|
1632 | # but the user/local one is tricky: ipython needs it to store internal | |
1630 | # data, but we also need the locals. We'll copy locals in the user |
|
1633 | # data, but we also need the locals. We'll copy locals in the user | |
1631 | # one, but will track what got copied so we can delete them at exit. |
|
1634 | # one, but will track what got copied so we can delete them at exit. | |
1632 | # This is so that a later embedded call doesn't see locals from a |
|
1635 | # This is so that a later embedded call doesn't see locals from a | |
1633 | # previous call (which most likely existed in a separate scope). |
|
1636 | # previous call (which most likely existed in a separate scope). | |
1634 | local_varnames = local_ns.keys() |
|
1637 | local_varnames = local_ns.keys() | |
1635 | self.user_ns.update(local_ns) |
|
1638 | self.user_ns.update(local_ns) | |
1636 |
|
1639 | |||
1637 | # Patch for global embedding to make sure that things don't overwrite |
|
1640 | # Patch for global embedding to make sure that things don't overwrite | |
1638 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> |
|
1641 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> | |
1639 | # FIXME. Test this a bit more carefully (the if.. is new) |
|
1642 | # FIXME. Test this a bit more carefully (the if.. is new) | |
1640 | if local_ns is None and global_ns is None: |
|
1643 | if local_ns is None and global_ns is None: | |
1641 | self.user_global_ns.update(__main__.__dict__) |
|
1644 | self.user_global_ns.update(__main__.__dict__) | |
1642 |
|
1645 | |||
1643 | # make sure the tab-completer has the correct frame information, so it |
|
1646 | # make sure the tab-completer has the correct frame information, so it | |
1644 | # actually completes using the frame's locals/globals |
|
1647 | # actually completes using the frame's locals/globals | |
1645 | self.set_completer_frame() |
|
1648 | self.set_completer_frame() | |
1646 |
|
1649 | |||
1647 | # before activating the interactive mode, we need to make sure that |
|
1650 | # before activating the interactive mode, we need to make sure that | |
1648 | # all names in the builtin namespace needed by ipython point to |
|
1651 | # all names in the builtin namespace needed by ipython point to | |
1649 | # ourselves, and not to other instances. |
|
1652 | # ourselves, and not to other instances. | |
1650 | self.add_builtins() |
|
1653 | self.add_builtins() | |
1651 |
|
1654 | |||
1652 | self.interact(header) |
|
1655 | self.interact(header) | |
1653 |
|
1656 | |||
1654 | # now, purge out the user namespace from anything we might have added |
|
1657 | # now, purge out the user namespace from anything we might have added | |
1655 | # from the caller's local namespace |
|
1658 | # from the caller's local namespace | |
1656 | delvar = self.user_ns.pop |
|
1659 | delvar = self.user_ns.pop | |
1657 | for var in local_varnames: |
|
1660 | for var in local_varnames: | |
1658 | delvar(var,None) |
|
1661 | delvar(var,None) | |
1659 | # and clean builtins we may have overridden |
|
1662 | # and clean builtins we may have overridden | |
1660 | self.clean_builtins() |
|
1663 | self.clean_builtins() | |
1661 |
|
1664 | |||
1662 | def interact_prompt(self): |
|
1665 | def interact_prompt(self): | |
1663 | """ Print the prompt (in read-eval-print loop) |
|
1666 | """ Print the prompt (in read-eval-print loop) | |
1664 |
|
1667 | |||
1665 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1668 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not | |
1666 | used in standard IPython flow. |
|
1669 | used in standard IPython flow. | |
1667 | """ |
|
1670 | """ | |
1668 | if self.more: |
|
1671 | if self.more: | |
1669 | try: |
|
1672 | try: | |
1670 | prompt = self.hooks.generate_prompt(True) |
|
1673 | prompt = self.hooks.generate_prompt(True) | |
1671 | except: |
|
1674 | except: | |
1672 | self.showtraceback() |
|
1675 | self.showtraceback() | |
1673 | if self.autoindent: |
|
1676 | if self.autoindent: | |
1674 | self.rl_do_indent = True |
|
1677 | self.rl_do_indent = True | |
1675 |
|
1678 | |||
1676 | else: |
|
1679 | else: | |
1677 | try: |
|
1680 | try: | |
1678 | prompt = self.hooks.generate_prompt(False) |
|
1681 | prompt = self.hooks.generate_prompt(False) | |
1679 | except: |
|
1682 | except: | |
1680 | self.showtraceback() |
|
1683 | self.showtraceback() | |
1681 | self.write(prompt) |
|
1684 | self.write(prompt) | |
1682 |
|
1685 | |||
1683 | def interact_handle_input(self,line): |
|
1686 | def interact_handle_input(self,line): | |
1684 | """ Handle the input line (in read-eval-print loop) |
|
1687 | """ Handle the input line (in read-eval-print loop) | |
1685 |
|
1688 | |||
1686 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1689 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not | |
1687 | used in standard IPython flow. |
|
1690 | used in standard IPython flow. | |
1688 | """ |
|
1691 | """ | |
1689 | if line.lstrip() == line: |
|
1692 | if line.lstrip() == line: | |
1690 | self.shadowhist.add(line.strip()) |
|
1693 | self.shadowhist.add(line.strip()) | |
1691 | lineout = self.prefilter(line,self.more) |
|
1694 | lineout = self.prefilter(line,self.more) | |
1692 |
|
1695 | |||
1693 | if line.strip(): |
|
1696 | if line.strip(): | |
1694 | if self.more: |
|
1697 | if self.more: | |
1695 | self.input_hist_raw[-1] += '%s\n' % line |
|
1698 | self.input_hist_raw[-1] += '%s\n' % line | |
1696 | else: |
|
1699 | else: | |
1697 | self.input_hist_raw.append('%s\n' % line) |
|
1700 | self.input_hist_raw.append('%s\n' % line) | |
1698 |
|
1701 | |||
1699 |
|
1702 | |||
1700 | self.more = self.push(lineout) |
|
1703 | self.more = self.push(lineout) | |
1701 | if (self.SyntaxTB.last_syntax_error and |
|
1704 | if (self.SyntaxTB.last_syntax_error and | |
1702 | self.rc.autoedit_syntax): |
|
1705 | self.rc.autoedit_syntax): | |
1703 | self.edit_syntax_error() |
|
1706 | self.edit_syntax_error() | |
1704 |
|
1707 | |||
1705 | def interact_with_readline(self): |
|
1708 | def interact_with_readline(self): | |
1706 | """ Demo of using interact_handle_input, interact_prompt |
|
1709 | """ Demo of using interact_handle_input, interact_prompt | |
1707 |
|
1710 | |||
1708 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), |
|
1711 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), | |
1709 | it should work like this. |
|
1712 | it should work like this. | |
1710 | """ |
|
1713 | """ | |
1711 | self.readline_startup_hook(self.pre_readline) |
|
1714 | self.readline_startup_hook(self.pre_readline) | |
1712 | while not self.exit_now: |
|
1715 | while not self.exit_now: | |
1713 | self.interact_prompt() |
|
1716 | self.interact_prompt() | |
1714 | if self.more: |
|
1717 | if self.more: | |
1715 | self.rl_do_indent = True |
|
1718 | self.rl_do_indent = True | |
1716 | else: |
|
1719 | else: | |
1717 | self.rl_do_indent = False |
|
1720 | self.rl_do_indent = False | |
1718 | line = raw_input_original().decode(self.stdin_encoding) |
|
1721 | line = raw_input_original().decode(self.stdin_encoding) | |
1719 | self.interact_handle_input(line) |
|
1722 | self.interact_handle_input(line) | |
1720 |
|
1723 | |||
1721 |
|
1724 | |||
1722 | def interact(self, banner=None): |
|
1725 | def interact(self, banner=None): | |
1723 | """Closely emulate the interactive Python console. |
|
1726 | """Closely emulate the interactive Python console. | |
1724 |
|
1727 | |||
1725 | The optional banner argument specify the banner to print |
|
1728 | The optional banner argument specify the banner to print | |
1726 | before the first interaction; by default it prints a banner |
|
1729 | before the first interaction; by default it prints a banner | |
1727 | similar to the one printed by the real Python interpreter, |
|
1730 | similar to the one printed by the real Python interpreter, | |
1728 | followed by the current class name in parentheses (so as not |
|
1731 | followed by the current class name in parentheses (so as not | |
1729 | to confuse this with the real interpreter -- since it's so |
|
1732 | to confuse this with the real interpreter -- since it's so | |
1730 | close!). |
|
1733 | close!). | |
1731 |
|
1734 | |||
1732 | """ |
|
1735 | """ | |
1733 |
|
1736 | |||
1734 | if self.exit_now: |
|
1737 | if self.exit_now: | |
1735 | # batch run -> do not interact |
|
1738 | # batch run -> do not interact | |
1736 | return |
|
1739 | return | |
1737 | cprt = 'Type "copyright", "credits" or "license" for more information.' |
|
1740 | cprt = 'Type "copyright", "credits" or "license" for more information.' | |
1738 | if banner is None: |
|
1741 | if banner is None: | |
1739 | self.write("Python %s on %s\n%s\n(%s)\n" % |
|
1742 | self.write("Python %s on %s\n%s\n(%s)\n" % | |
1740 | (sys.version, sys.platform, cprt, |
|
1743 | (sys.version, sys.platform, cprt, | |
1741 | self.__class__.__name__)) |
|
1744 | self.__class__.__name__)) | |
1742 | else: |
|
1745 | else: | |
1743 | self.write(banner) |
|
1746 | self.write(banner) | |
1744 |
|
1747 | |||
1745 | more = 0 |
|
1748 | more = 0 | |
1746 |
|
1749 | |||
1747 | # Mark activity in the builtins |
|
1750 | # Mark activity in the builtins | |
1748 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1751 | __builtin__.__dict__['__IPYTHON__active'] += 1 | |
1749 |
|
1752 | |||
1750 | if self.has_readline: |
|
1753 | if self.has_readline: | |
1751 | self.readline_startup_hook(self.pre_readline) |
|
1754 | self.readline_startup_hook(self.pre_readline) | |
1752 | # exit_now is set by a call to %Exit or %Quit |
|
1755 | # exit_now is set by a call to %Exit or %Quit | |
1753 |
|
1756 | |||
1754 | while not self.exit_now: |
|
1757 | while not self.exit_now: | |
1755 | self.hooks.pre_prompt_hook() |
|
1758 | self.hooks.pre_prompt_hook() | |
1756 | if more: |
|
1759 | if more: | |
1757 | try: |
|
1760 | try: | |
1758 | prompt = self.hooks.generate_prompt(True) |
|
1761 | prompt = self.hooks.generate_prompt(True) | |
1759 | except: |
|
1762 | except: | |
1760 | self.showtraceback() |
|
1763 | self.showtraceback() | |
1761 | if self.autoindent: |
|
1764 | if self.autoindent: | |
1762 | self.rl_do_indent = True |
|
1765 | self.rl_do_indent = True | |
1763 |
|
1766 | |||
1764 | else: |
|
1767 | else: | |
1765 | try: |
|
1768 | try: | |
1766 | prompt = self.hooks.generate_prompt(False) |
|
1769 | prompt = self.hooks.generate_prompt(False) | |
1767 | except: |
|
1770 | except: | |
1768 | self.showtraceback() |
|
1771 | self.showtraceback() | |
1769 | try: |
|
1772 | try: | |
1770 | line = self.raw_input(prompt,more) |
|
1773 | line = self.raw_input(prompt,more) | |
1771 | if self.exit_now: |
|
1774 | if self.exit_now: | |
1772 | # quick exit on sys.std[in|out] close |
|
1775 | # quick exit on sys.std[in|out] close | |
1773 | break |
|
1776 | break | |
1774 | if self.autoindent: |
|
1777 | if self.autoindent: | |
1775 | self.rl_do_indent = False |
|
1778 | self.rl_do_indent = False | |
1776 |
|
1779 | |||
1777 | except KeyboardInterrupt: |
|
1780 | except KeyboardInterrupt: | |
1778 | #double-guard against keyboardinterrupts during kbdint handling |
|
1781 | #double-guard against keyboardinterrupts during kbdint handling | |
1779 | try: |
|
1782 | try: | |
1780 | self.write('\nKeyboardInterrupt\n') |
|
1783 | self.write('\nKeyboardInterrupt\n') | |
1781 | self.resetbuffer() |
|
1784 | self.resetbuffer() | |
1782 | # keep cache in sync with the prompt counter: |
|
1785 | # keep cache in sync with the prompt counter: | |
1783 | self.outputcache.prompt_count -= 1 |
|
1786 | self.outputcache.prompt_count -= 1 | |
1784 |
|
1787 | |||
1785 | if self.autoindent: |
|
1788 | if self.autoindent: | |
1786 | self.indent_current_nsp = 0 |
|
1789 | self.indent_current_nsp = 0 | |
1787 | more = 0 |
|
1790 | more = 0 | |
1788 | except KeyboardInterrupt: |
|
1791 | except KeyboardInterrupt: | |
1789 | pass |
|
1792 | pass | |
1790 | except EOFError: |
|
1793 | except EOFError: | |
1791 | if self.autoindent: |
|
1794 | if self.autoindent: | |
1792 | self.rl_do_indent = False |
|
1795 | self.rl_do_indent = False | |
1793 | self.readline_startup_hook(None) |
|
1796 | self.readline_startup_hook(None) | |
1794 | self.write('\n') |
|
1797 | self.write('\n') | |
1795 | self.exit() |
|
1798 | self.exit() | |
1796 | except bdb.BdbQuit: |
|
1799 | except bdb.BdbQuit: | |
1797 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
1800 | warn('The Python debugger has exited with a BdbQuit exception.\n' | |
1798 | 'Because of how pdb handles the stack, it is impossible\n' |
|
1801 | 'Because of how pdb handles the stack, it is impossible\n' | |
1799 | 'for IPython to properly format this particular exception.\n' |
|
1802 | 'for IPython to properly format this particular exception.\n' | |
1800 | 'IPython will resume normal operation.') |
|
1803 | 'IPython will resume normal operation.') | |
1801 | except: |
|
1804 | except: | |
1802 | # exceptions here are VERY RARE, but they can be triggered |
|
1805 | # exceptions here are VERY RARE, but they can be triggered | |
1803 | # asynchronously by signal handlers, for example. |
|
1806 | # asynchronously by signal handlers, for example. | |
1804 | self.showtraceback() |
|
1807 | self.showtraceback() | |
1805 | else: |
|
1808 | else: | |
1806 | more = self.push(line) |
|
1809 | more = self.push(line) | |
1807 | if (self.SyntaxTB.last_syntax_error and |
|
1810 | if (self.SyntaxTB.last_syntax_error and | |
1808 | self.rc.autoedit_syntax): |
|
1811 | self.rc.autoedit_syntax): | |
1809 | self.edit_syntax_error() |
|
1812 | self.edit_syntax_error() | |
1810 |
|
1813 | |||
1811 | # We are off again... |
|
1814 | # We are off again... | |
1812 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
1815 | __builtin__.__dict__['__IPYTHON__active'] -= 1 | |
1813 |
|
1816 | |||
1814 | def excepthook(self, etype, value, tb): |
|
1817 | def excepthook(self, etype, value, tb): | |
1815 | """One more defense for GUI apps that call sys.excepthook. |
|
1818 | """One more defense for GUI apps that call sys.excepthook. | |
1816 |
|
1819 | |||
1817 | GUI frameworks like wxPython trap exceptions and call |
|
1820 | GUI frameworks like wxPython trap exceptions and call | |
1818 | sys.excepthook themselves. I guess this is a feature that |
|
1821 | sys.excepthook themselves. I guess this is a feature that | |
1819 | enables them to keep running after exceptions that would |
|
1822 | enables them to keep running after exceptions that would | |
1820 | otherwise kill their mainloop. This is a bother for IPython |
|
1823 | otherwise kill their mainloop. This is a bother for IPython | |
1821 | which excepts to catch all of the program exceptions with a try: |
|
1824 | which excepts to catch all of the program exceptions with a try: | |
1822 | except: statement. |
|
1825 | except: statement. | |
1823 |
|
1826 | |||
1824 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1827 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1825 | any app directly invokes sys.excepthook, it will look to the user like |
|
1828 | any app directly invokes sys.excepthook, it will look to the user like | |
1826 | IPython crashed. In order to work around this, we can disable the |
|
1829 | IPython crashed. In order to work around this, we can disable the | |
1827 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1830 | CrashHandler and replace it with this excepthook instead, which prints a | |
1828 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1831 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1829 | call sys.excepthook will generate a regular-looking exception from |
|
1832 | call sys.excepthook will generate a regular-looking exception from | |
1830 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1833 | IPython, and the CrashHandler will only be triggered by real IPython | |
1831 | crashes. |
|
1834 | crashes. | |
1832 |
|
1835 | |||
1833 | This hook should be used sparingly, only in places which are not likely |
|
1836 | This hook should be used sparingly, only in places which are not likely | |
1834 | to be true IPython errors. |
|
1837 | to be true IPython errors. | |
1835 | """ |
|
1838 | """ | |
1836 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1839 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1837 |
|
1840 | |||
1838 | def expand_aliases(self,fn,rest): |
|
1841 | def expand_aliases(self,fn,rest): | |
1839 | """ Expand multiple levels of aliases: |
|
1842 | """ Expand multiple levels of aliases: | |
1840 |
|
1843 | |||
1841 | if: |
|
1844 | if: | |
1842 |
|
1845 | |||
1843 | alias foo bar /tmp |
|
1846 | alias foo bar /tmp | |
1844 | alias baz foo |
|
1847 | alias baz foo | |
1845 |
|
1848 | |||
1846 | then: |
|
1849 | then: | |
1847 |
|
1850 | |||
1848 | baz huhhahhei -> bar /tmp huhhahhei |
|
1851 | baz huhhahhei -> bar /tmp huhhahhei | |
1849 |
|
1852 | |||
1850 | """ |
|
1853 | """ | |
1851 | line = fn + " " + rest |
|
1854 | line = fn + " " + rest | |
1852 |
|
1855 | |||
1853 | done = Set() |
|
1856 | done = Set() | |
1854 | while 1: |
|
1857 | while 1: | |
1855 | pre,fn,rest = prefilter.splitUserInput(line, |
|
1858 | pre,fn,rest = prefilter.splitUserInput(line, | |
1856 | prefilter.shell_line_split) |
|
1859 | prefilter.shell_line_split) | |
1857 | if fn in self.alias_table: |
|
1860 | if fn in self.alias_table: | |
1858 | if fn in done: |
|
1861 | if fn in done: | |
1859 | warn("Cyclic alias definition, repeated '%s'" % fn) |
|
1862 | warn("Cyclic alias definition, repeated '%s'" % fn) | |
1860 | return "" |
|
1863 | return "" | |
1861 | done.add(fn) |
|
1864 | done.add(fn) | |
1862 |
|
1865 | |||
1863 | l2 = self.transform_alias(fn,rest) |
|
1866 | l2 = self.transform_alias(fn,rest) | |
1864 | # dir -> dir |
|
1867 | # dir -> dir | |
1865 | # print "alias",line, "->",l2 #dbg |
|
1868 | # print "alias",line, "->",l2 #dbg | |
1866 | if l2 == line: |
|
1869 | if l2 == line: | |
1867 | break |
|
1870 | break | |
1868 | # ls -> ls -F should not recurse forever |
|
1871 | # ls -> ls -F should not recurse forever | |
1869 | if l2.split(None,1)[0] == line.split(None,1)[0]: |
|
1872 | if l2.split(None,1)[0] == line.split(None,1)[0]: | |
1870 | line = l2 |
|
1873 | line = l2 | |
1871 | break |
|
1874 | break | |
1872 |
|
1875 | |||
1873 | line=l2 |
|
1876 | line=l2 | |
1874 |
|
1877 | |||
1875 |
|
1878 | |||
1876 | # print "al expand to",line #dbg |
|
1879 | # print "al expand to",line #dbg | |
1877 | else: |
|
1880 | else: | |
1878 | break |
|
1881 | break | |
1879 |
|
1882 | |||
1880 | return line |
|
1883 | return line | |
1881 |
|
1884 | |||
1882 | def transform_alias(self, alias,rest=''): |
|
1885 | def transform_alias(self, alias,rest=''): | |
1883 | """ Transform alias to system command string. |
|
1886 | """ Transform alias to system command string. | |
1884 | """ |
|
1887 | """ | |
1885 | trg = self.alias_table[alias] |
|
1888 | trg = self.alias_table[alias] | |
1886 |
|
1889 | |||
1887 | nargs,cmd = trg |
|
1890 | nargs,cmd = trg | |
1888 | # print trg #dbg |
|
1891 | # print trg #dbg | |
1889 | if ' ' in cmd and os.path.isfile(cmd): |
|
1892 | if ' ' in cmd and os.path.isfile(cmd): | |
1890 | cmd = '"%s"' % cmd |
|
1893 | cmd = '"%s"' % cmd | |
1891 |
|
1894 | |||
1892 | # Expand the %l special to be the user's input line |
|
1895 | # Expand the %l special to be the user's input line | |
1893 | if cmd.find('%l') >= 0: |
|
1896 | if cmd.find('%l') >= 0: | |
1894 | cmd = cmd.replace('%l',rest) |
|
1897 | cmd = cmd.replace('%l',rest) | |
1895 | rest = '' |
|
1898 | rest = '' | |
1896 | if nargs==0: |
|
1899 | if nargs==0: | |
1897 | # Simple, argument-less aliases |
|
1900 | # Simple, argument-less aliases | |
1898 | cmd = '%s %s' % (cmd,rest) |
|
1901 | cmd = '%s %s' % (cmd,rest) | |
1899 | else: |
|
1902 | else: | |
1900 | # Handle aliases with positional arguments |
|
1903 | # Handle aliases with positional arguments | |
1901 | args = rest.split(None,nargs) |
|
1904 | args = rest.split(None,nargs) | |
1902 | if len(args)< nargs: |
|
1905 | if len(args)< nargs: | |
1903 | error('Alias <%s> requires %s arguments, %s given.' % |
|
1906 | error('Alias <%s> requires %s arguments, %s given.' % | |
1904 | (alias,nargs,len(args))) |
|
1907 | (alias,nargs,len(args))) | |
1905 | return None |
|
1908 | return None | |
1906 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) |
|
1909 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) | |
1907 | # Now call the macro, evaluating in the user's namespace |
|
1910 | # Now call the macro, evaluating in the user's namespace | |
1908 | #print 'new command: <%r>' % cmd # dbg |
|
1911 | #print 'new command: <%r>' % cmd # dbg | |
1909 | return cmd |
|
1912 | return cmd | |
1910 |
|
1913 | |||
1911 | def call_alias(self,alias,rest=''): |
|
1914 | def call_alias(self,alias,rest=''): | |
1912 | """Call an alias given its name and the rest of the line. |
|
1915 | """Call an alias given its name and the rest of the line. | |
1913 |
|
1916 | |||
1914 | This is only used to provide backwards compatibility for users of |
|
1917 | This is only used to provide backwards compatibility for users of | |
1915 | ipalias(), use of which is not recommended for anymore.""" |
|
1918 | ipalias(), use of which is not recommended for anymore.""" | |
1916 |
|
1919 | |||
1917 | # Now call the macro, evaluating in the user's namespace |
|
1920 | # Now call the macro, evaluating in the user's namespace | |
1918 | cmd = self.transform_alias(alias, rest) |
|
1921 | cmd = self.transform_alias(alias, rest) | |
1919 | try: |
|
1922 | try: | |
1920 | self.system(cmd) |
|
1923 | self.system(cmd) | |
1921 | except: |
|
1924 | except: | |
1922 | self.showtraceback() |
|
1925 | self.showtraceback() | |
1923 |
|
1926 | |||
1924 | def indent_current_str(self): |
|
1927 | def indent_current_str(self): | |
1925 | """return the current level of indentation as a string""" |
|
1928 | """return the current level of indentation as a string""" | |
1926 | return self.indent_current_nsp * ' ' |
|
1929 | return self.indent_current_nsp * ' ' | |
1927 |
|
1930 | |||
1928 | def autoindent_update(self,line): |
|
1931 | def autoindent_update(self,line): | |
1929 | """Keep track of the indent level.""" |
|
1932 | """Keep track of the indent level.""" | |
1930 |
|
1933 | |||
1931 | #debugx('line') |
|
1934 | #debugx('line') | |
1932 | #debugx('self.indent_current_nsp') |
|
1935 | #debugx('self.indent_current_nsp') | |
1933 | if self.autoindent: |
|
1936 | if self.autoindent: | |
1934 | if line: |
|
1937 | if line: | |
1935 | inisp = num_ini_spaces(line) |
|
1938 | inisp = num_ini_spaces(line) | |
1936 | if inisp < self.indent_current_nsp: |
|
1939 | if inisp < self.indent_current_nsp: | |
1937 | self.indent_current_nsp = inisp |
|
1940 | self.indent_current_nsp = inisp | |
1938 |
|
1941 | |||
1939 | if line[-1] == ':': |
|
1942 | if line[-1] == ':': | |
1940 | self.indent_current_nsp += 4 |
|
1943 | self.indent_current_nsp += 4 | |
1941 | elif dedent_re.match(line): |
|
1944 | elif dedent_re.match(line): | |
1942 | self.indent_current_nsp -= 4 |
|
1945 | self.indent_current_nsp -= 4 | |
1943 | else: |
|
1946 | else: | |
1944 | self.indent_current_nsp = 0 |
|
1947 | self.indent_current_nsp = 0 | |
1945 |
|
1948 | |||
1946 | def runlines(self,lines): |
|
1949 | def runlines(self,lines): | |
1947 | """Run a string of one or more lines of source. |
|
1950 | """Run a string of one or more lines of source. | |
1948 |
|
1951 | |||
1949 | This method is capable of running a string containing multiple source |
|
1952 | This method is capable of running a string containing multiple source | |
1950 | lines, as if they had been entered at the IPython prompt. Since it |
|
1953 | lines, as if they had been entered at the IPython prompt. Since it | |
1951 | exposes IPython's processing machinery, the given strings can contain |
|
1954 | exposes IPython's processing machinery, the given strings can contain | |
1952 | magic calls (%magic), special shell access (!cmd), etc.""" |
|
1955 | magic calls (%magic), special shell access (!cmd), etc.""" | |
1953 |
|
1956 | |||
1954 | # We must start with a clean buffer, in case this is run from an |
|
1957 | # We must start with a clean buffer, in case this is run from an | |
1955 | # interactive IPython session (via a magic, for example). |
|
1958 | # interactive IPython session (via a magic, for example). | |
1956 | self.resetbuffer() |
|
1959 | self.resetbuffer() | |
1957 | lines = lines.split('\n') |
|
1960 | lines = lines.split('\n') | |
1958 | more = 0 |
|
1961 | more = 0 | |
1959 |
|
1962 | |||
1960 | for line in lines: |
|
1963 | for line in lines: | |
1961 | # skip blank lines so we don't mess up the prompt counter, but do |
|
1964 | # skip blank lines so we don't mess up the prompt counter, but do | |
1962 | # NOT skip even a blank line if we are in a code block (more is |
|
1965 | # NOT skip even a blank line if we are in a code block (more is | |
1963 | # true) |
|
1966 | # true) | |
1964 |
|
1967 | |||
1965 |
|
1968 | |||
1966 | if line or more: |
|
1969 | if line or more: | |
1967 | # push to raw history, so hist line numbers stay in sync |
|
1970 | # push to raw history, so hist line numbers stay in sync | |
1968 | self.input_hist_raw.append("# " + line + "\n") |
|
1971 | self.input_hist_raw.append("# " + line + "\n") | |
1969 | more = self.push(self.prefilter(line,more)) |
|
1972 | more = self.push(self.prefilter(line,more)) | |
1970 | # IPython's runsource returns None if there was an error |
|
1973 | # IPython's runsource returns None if there was an error | |
1971 | # compiling the code. This allows us to stop processing right |
|
1974 | # compiling the code. This allows us to stop processing right | |
1972 | # away, so the user gets the error message at the right place. |
|
1975 | # away, so the user gets the error message at the right place. | |
1973 | if more is None: |
|
1976 | if more is None: | |
1974 | break |
|
1977 | break | |
1975 | else: |
|
1978 | else: | |
1976 | self.input_hist_raw.append("\n") |
|
1979 | self.input_hist_raw.append("\n") | |
1977 | # final newline in case the input didn't have it, so that the code |
|
1980 | # final newline in case the input didn't have it, so that the code | |
1978 | # actually does get executed |
|
1981 | # actually does get executed | |
1979 | if more: |
|
1982 | if more: | |
1980 | self.push('\n') |
|
1983 | self.push('\n') | |
1981 |
|
1984 | |||
1982 | def runsource(self, source, filename='<input>', symbol='single'): |
|
1985 | def runsource(self, source, filename='<input>', symbol='single'): | |
1983 | """Compile and run some source in the interpreter. |
|
1986 | """Compile and run some source in the interpreter. | |
1984 |
|
1987 | |||
1985 | Arguments are as for compile_command(). |
|
1988 | Arguments are as for compile_command(). | |
1986 |
|
1989 | |||
1987 | One several things can happen: |
|
1990 | One several things can happen: | |
1988 |
|
1991 | |||
1989 | 1) The input is incorrect; compile_command() raised an |
|
1992 | 1) The input is incorrect; compile_command() raised an | |
1990 | exception (SyntaxError or OverflowError). A syntax traceback |
|
1993 | exception (SyntaxError or OverflowError). A syntax traceback | |
1991 | will be printed by calling the showsyntaxerror() method. |
|
1994 | will be printed by calling the showsyntaxerror() method. | |
1992 |
|
1995 | |||
1993 | 2) The input is incomplete, and more input is required; |
|
1996 | 2) The input is incomplete, and more input is required; | |
1994 | compile_command() returned None. Nothing happens. |
|
1997 | compile_command() returned None. Nothing happens. | |
1995 |
|
1998 | |||
1996 | 3) The input is complete; compile_command() returned a code |
|
1999 | 3) The input is complete; compile_command() returned a code | |
1997 | object. The code is executed by calling self.runcode() (which |
|
2000 | object. The code is executed by calling self.runcode() (which | |
1998 | also handles run-time exceptions, except for SystemExit). |
|
2001 | also handles run-time exceptions, except for SystemExit). | |
1999 |
|
2002 | |||
2000 | The return value is: |
|
2003 | The return value is: | |
2001 |
|
2004 | |||
2002 | - True in case 2 |
|
2005 | - True in case 2 | |
2003 |
|
2006 | |||
2004 | - False in the other cases, unless an exception is raised, where |
|
2007 | - False in the other cases, unless an exception is raised, where | |
2005 | None is returned instead. This can be used by external callers to |
|
2008 | None is returned instead. This can be used by external callers to | |
2006 | know whether to continue feeding input or not. |
|
2009 | know whether to continue feeding input or not. | |
2007 |
|
2010 | |||
2008 | The return value can be used to decide whether to use sys.ps1 or |
|
2011 | The return value can be used to decide whether to use sys.ps1 or | |
2009 | sys.ps2 to prompt the next line.""" |
|
2012 | sys.ps2 to prompt the next line.""" | |
2010 |
|
2013 | |||
2011 | # if the source code has leading blanks, add 'if 1:\n' to it |
|
2014 | # if the source code has leading blanks, add 'if 1:\n' to it | |
2012 | # this allows execution of indented pasted code. It is tempting |
|
2015 | # this allows execution of indented pasted code. It is tempting | |
2013 | # to add '\n' at the end of source to run commands like ' a=1' |
|
2016 | # to add '\n' at the end of source to run commands like ' a=1' | |
2014 | # directly, but this fails for more complicated scenarios |
|
2017 | # directly, but this fails for more complicated scenarios | |
2015 | source=source.encode(self.stdin_encoding) |
|
2018 | source=source.encode(self.stdin_encoding) | |
2016 | if source[:1] in [' ', '\t']: |
|
2019 | if source[:1] in [' ', '\t']: | |
2017 | source = 'if 1:\n%s' % source |
|
2020 | source = 'if 1:\n%s' % source | |
2018 |
|
2021 | |||
2019 | try: |
|
2022 | try: | |
2020 | code = self.compile(source,filename,symbol) |
|
2023 | code = self.compile(source,filename,symbol) | |
2021 | except (OverflowError, SyntaxError, ValueError, TypeError): |
|
2024 | except (OverflowError, SyntaxError, ValueError, TypeError): | |
2022 | # Case 1 |
|
2025 | # Case 1 | |
2023 | self.showsyntaxerror(filename) |
|
2026 | self.showsyntaxerror(filename) | |
2024 | return None |
|
2027 | return None | |
2025 |
|
2028 | |||
2026 | if code is None: |
|
2029 | if code is None: | |
2027 | # Case 2 |
|
2030 | # Case 2 | |
2028 | return True |
|
2031 | return True | |
2029 |
|
2032 | |||
2030 | # Case 3 |
|
2033 | # Case 3 | |
2031 | # We store the code object so that threaded shells and |
|
2034 | # We store the code object so that threaded shells and | |
2032 | # custom exception handlers can access all this info if needed. |
|
2035 | # custom exception handlers can access all this info if needed. | |
2033 | # The source corresponding to this can be obtained from the |
|
2036 | # The source corresponding to this can be obtained from the | |
2034 | # buffer attribute as '\n'.join(self.buffer). |
|
2037 | # buffer attribute as '\n'.join(self.buffer). | |
2035 | self.code_to_run = code |
|
2038 | self.code_to_run = code | |
2036 | # now actually execute the code object |
|
2039 | # now actually execute the code object | |
2037 | if self.runcode(code) == 0: |
|
2040 | if self.runcode(code) == 0: | |
2038 | return False |
|
2041 | return False | |
2039 | else: |
|
2042 | else: | |
2040 | return None |
|
2043 | return None | |
2041 |
|
2044 | |||
2042 | def runcode(self,code_obj): |
|
2045 | def runcode(self,code_obj): | |
2043 | """Execute a code object. |
|
2046 | """Execute a code object. | |
2044 |
|
2047 | |||
2045 | When an exception occurs, self.showtraceback() is called to display a |
|
2048 | When an exception occurs, self.showtraceback() is called to display a | |
2046 | traceback. |
|
2049 | traceback. | |
2047 |
|
2050 | |||
2048 | Return value: a flag indicating whether the code to be run completed |
|
2051 | Return value: a flag indicating whether the code to be run completed | |
2049 | successfully: |
|
2052 | successfully: | |
2050 |
|
2053 | |||
2051 | - 0: successful execution. |
|
2054 | - 0: successful execution. | |
2052 | - 1: an error occurred. |
|
2055 | - 1: an error occurred. | |
2053 | """ |
|
2056 | """ | |
2054 |
|
2057 | |||
2055 | # Set our own excepthook in case the user code tries to call it |
|
2058 | # Set our own excepthook in case the user code tries to call it | |
2056 | # directly, so that the IPython crash handler doesn't get triggered |
|
2059 | # directly, so that the IPython crash handler doesn't get triggered | |
2057 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2060 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
2058 |
|
2061 | |||
2059 | # we save the original sys.excepthook in the instance, in case config |
|
2062 | # we save the original sys.excepthook in the instance, in case config | |
2060 | # code (such as magics) needs access to it. |
|
2063 | # code (such as magics) needs access to it. | |
2061 | self.sys_excepthook = old_excepthook |
|
2064 | self.sys_excepthook = old_excepthook | |
2062 | outflag = 1 # happens in more places, so it's easier as default |
|
2065 | outflag = 1 # happens in more places, so it's easier as default | |
2063 | try: |
|
2066 | try: | |
2064 | try: |
|
2067 | try: | |
2065 | self.hooks.pre_runcode_hook() |
|
2068 | self.hooks.pre_runcode_hook() | |
2066 | # Embedded instances require separate global/local namespaces |
|
2069 | # Embedded instances require separate global/local namespaces | |
2067 | # so they can see both the surrounding (local) namespace and |
|
2070 | # so they can see both the surrounding (local) namespace and | |
2068 | # the module-level globals when called inside another function. |
|
2071 | # the module-level globals when called inside another function. | |
2069 | if self.embedded: |
|
2072 | if self.embedded: | |
2070 | exec code_obj in self.user_global_ns, self.user_ns |
|
2073 | exec code_obj in self.user_global_ns, self.user_ns | |
2071 | # Normal (non-embedded) instances should only have a single |
|
2074 | # Normal (non-embedded) instances should only have a single | |
2072 | # namespace for user code execution, otherwise functions won't |
|
2075 | # namespace for user code execution, otherwise functions won't | |
2073 | # see interactive top-level globals. |
|
2076 | # see interactive top-level globals. | |
2074 | else: |
|
2077 | else: | |
2075 | exec code_obj in self.user_ns |
|
2078 | exec code_obj in self.user_ns | |
2076 | finally: |
|
2079 | finally: | |
2077 | # Reset our crash handler in place |
|
2080 | # Reset our crash handler in place | |
2078 | sys.excepthook = old_excepthook |
|
2081 | sys.excepthook = old_excepthook | |
2079 | except SystemExit: |
|
2082 | except SystemExit: | |
2080 | self.resetbuffer() |
|
2083 | self.resetbuffer() | |
2081 | self.showtraceback() |
|
2084 | self.showtraceback() | |
2082 | warn("Type %exit or %quit to exit IPython " |
|
2085 | warn("Type %exit or %quit to exit IPython " | |
2083 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
2086 | "(%Exit or %Quit do so unconditionally).",level=1) | |
2084 | except self.custom_exceptions: |
|
2087 | except self.custom_exceptions: | |
2085 | etype,value,tb = sys.exc_info() |
|
2088 | etype,value,tb = sys.exc_info() | |
2086 | self.CustomTB(etype,value,tb) |
|
2089 | self.CustomTB(etype,value,tb) | |
2087 | except: |
|
2090 | except: | |
2088 | self.showtraceback() |
|
2091 | self.showtraceback() | |
2089 | else: |
|
2092 | else: | |
2090 | outflag = 0 |
|
2093 | outflag = 0 | |
2091 | if softspace(sys.stdout, 0): |
|
2094 | if softspace(sys.stdout, 0): | |
2092 |
|
2095 | |||
2093 | # Flush out code object which has been run (and source) |
|
2096 | # Flush out code object which has been run (and source) | |
2094 | self.code_to_run = None |
|
2097 | self.code_to_run = None | |
2095 | return outflag |
|
2098 | return outflag | |
2096 |
|
2099 | |||
2097 | def push(self, line): |
|
2100 | def push(self, line): | |
2098 | """Push a line to the interpreter. |
|
2101 | """Push a line to the interpreter. | |
2099 |
|
2102 | |||
2100 | The line should not have a trailing newline; it may have |
|
2103 | The line should not have a trailing newline; it may have | |
2101 | internal newlines. The line is appended to a buffer and the |
|
2104 | internal newlines. The line is appended to a buffer and the | |
2102 | interpreter's runsource() method is called with the |
|
2105 | interpreter's runsource() method is called with the | |
2103 | concatenated contents of the buffer as source. If this |
|
2106 | concatenated contents of the buffer as source. If this | |
2104 | indicates that the command was executed or invalid, the buffer |
|
2107 | indicates that the command was executed or invalid, the buffer | |
2105 | is reset; otherwise, the command is incomplete, and the buffer |
|
2108 | is reset; otherwise, the command is incomplete, and the buffer | |
2106 | is left as it was after the line was appended. The return |
|
2109 | is left as it was after the line was appended. The return | |
2107 | value is 1 if more input is required, 0 if the line was dealt |
|
2110 | value is 1 if more input is required, 0 if the line was dealt | |
2108 | with in some way (this is the same as runsource()). |
|
2111 | with in some way (this is the same as runsource()). | |
2109 | """ |
|
2112 | """ | |
2110 |
|
2113 | |||
2111 | # autoindent management should be done here, and not in the |
|
2114 | # autoindent management should be done here, and not in the | |
2112 | # interactive loop, since that one is only seen by keyboard input. We |
|
2115 | # interactive loop, since that one is only seen by keyboard input. We | |
2113 | # need this done correctly even for code run via runlines (which uses |
|
2116 | # need this done correctly even for code run via runlines (which uses | |
2114 | # push). |
|
2117 | # push). | |
2115 |
|
2118 | |||
2116 | #print 'push line: <%s>' % line # dbg |
|
2119 | #print 'push line: <%s>' % line # dbg | |
2117 | for subline in line.splitlines(): |
|
2120 | for subline in line.splitlines(): | |
2118 | self.autoindent_update(subline) |
|
2121 | self.autoindent_update(subline) | |
2119 | self.buffer.append(line) |
|
2122 | self.buffer.append(line) | |
2120 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
2123 | more = self.runsource('\n'.join(self.buffer), self.filename) | |
2121 | if not more: |
|
2124 | if not more: | |
2122 | self.resetbuffer() |
|
2125 | self.resetbuffer() | |
2123 | return more |
|
2126 | return more | |
2124 |
|
2127 | |||
2125 | def split_user_input(self, line): |
|
2128 | def split_user_input(self, line): | |
2126 | # This is really a hold-over to support ipapi and some extensions |
|
2129 | # This is really a hold-over to support ipapi and some extensions | |
2127 | return prefilter.splitUserInput(line) |
|
2130 | return prefilter.splitUserInput(line) | |
2128 |
|
2131 | |||
2129 | def resetbuffer(self): |
|
2132 | def resetbuffer(self): | |
2130 | """Reset the input buffer.""" |
|
2133 | """Reset the input buffer.""" | |
2131 | self.buffer[:] = [] |
|
2134 | self.buffer[:] = [] | |
2132 |
|
2135 | |||
2133 | def raw_input(self,prompt='',continue_prompt=False): |
|
2136 | def raw_input(self,prompt='',continue_prompt=False): | |
2134 | """Write a prompt and read a line. |
|
2137 | """Write a prompt and read a line. | |
2135 |
|
2138 | |||
2136 | The returned line does not include the trailing newline. |
|
2139 | The returned line does not include the trailing newline. | |
2137 | When the user enters the EOF key sequence, EOFError is raised. |
|
2140 | When the user enters the EOF key sequence, EOFError is raised. | |
2138 |
|
2141 | |||
2139 | Optional inputs: |
|
2142 | Optional inputs: | |
2140 |
|
2143 | |||
2141 | - prompt(''): a string to be printed to prompt the user. |
|
2144 | - prompt(''): a string to be printed to prompt the user. | |
2142 |
|
2145 | |||
2143 | - continue_prompt(False): whether this line is the first one or a |
|
2146 | - continue_prompt(False): whether this line is the first one or a | |
2144 | continuation in a sequence of inputs. |
|
2147 | continuation in a sequence of inputs. | |
2145 | """ |
|
2148 | """ | |
2146 |
|
2149 | |||
2147 | # Code run by the user may have modified the readline completer state. |
|
2150 | # Code run by the user may have modified the readline completer state. | |
2148 | # We must ensure that our completer is back in place. |
|
2151 | # We must ensure that our completer is back in place. | |
2149 | if self.has_readline: |
|
2152 | if self.has_readline: | |
2150 | self.set_completer() |
|
2153 | self.set_completer() | |
2151 |
|
2154 | |||
2152 | try: |
|
2155 | try: | |
2153 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
2156 | line = raw_input_original(prompt).decode(self.stdin_encoding) | |
2154 | except ValueError: |
|
2157 | except ValueError: | |
2155 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
2158 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" | |
2156 | " or sys.stdout.close()!\nExiting IPython!") |
|
2159 | " or sys.stdout.close()!\nExiting IPython!") | |
2157 | self.exit_now = True |
|
2160 | self.exit_now = True | |
2158 | return "" |
|
2161 | return "" | |
2159 |
|
2162 | |||
2160 | # Try to be reasonably smart about not re-indenting pasted input more |
|
2163 | # Try to be reasonably smart about not re-indenting pasted input more | |
2161 | # than necessary. We do this by trimming out the auto-indent initial |
|
2164 | # than necessary. We do this by trimming out the auto-indent initial | |
2162 | # spaces, if the user's actual input started itself with whitespace. |
|
2165 | # spaces, if the user's actual input started itself with whitespace. | |
2163 | #debugx('self.buffer[-1]') |
|
2166 | #debugx('self.buffer[-1]') | |
2164 |
|
2167 | |||
2165 | if self.autoindent: |
|
2168 | if self.autoindent: | |
2166 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
2169 | if num_ini_spaces(line) > self.indent_current_nsp: | |
2167 | line = line[self.indent_current_nsp:] |
|
2170 | line = line[self.indent_current_nsp:] | |
2168 | self.indent_current_nsp = 0 |
|
2171 | self.indent_current_nsp = 0 | |
2169 |
|
2172 | |||
2170 | # store the unfiltered input before the user has any chance to modify |
|
2173 | # store the unfiltered input before the user has any chance to modify | |
2171 | # it. |
|
2174 | # it. | |
2172 | if line.strip(): |
|
2175 | if line.strip(): | |
2173 | if continue_prompt: |
|
2176 | if continue_prompt: | |
2174 | self.input_hist_raw[-1] += '%s\n' % line |
|
2177 | self.input_hist_raw[-1] += '%s\n' % line | |
2175 | if self.has_readline: # and some config option is set? |
|
2178 | if self.has_readline: # and some config option is set? | |
2176 | try: |
|
2179 | try: | |
2177 | histlen = self.readline.get_current_history_length() |
|
2180 | histlen = self.readline.get_current_history_length() | |
2178 | if histlen > 1: |
|
2181 | if histlen > 1: | |
2179 | newhist = self.input_hist_raw[-1].rstrip() |
|
2182 | newhist = self.input_hist_raw[-1].rstrip() | |
2180 | self.readline.remove_history_item(histlen-1) |
|
2183 | self.readline.remove_history_item(histlen-1) | |
2181 | self.readline.replace_history_item(histlen-2, |
|
2184 | self.readline.replace_history_item(histlen-2, | |
2182 | newhist.encode(self.stdin_encoding)) |
|
2185 | newhist.encode(self.stdin_encoding)) | |
2183 | except AttributeError: |
|
2186 | except AttributeError: | |
2184 | pass # re{move,place}_history_item are new in 2.4. |
|
2187 | pass # re{move,place}_history_item are new in 2.4. | |
2185 | else: |
|
2188 | else: | |
2186 | self.input_hist_raw.append('%s\n' % line) |
|
2189 | self.input_hist_raw.append('%s\n' % line) | |
2187 | # only entries starting at first column go to shadow history |
|
2190 | # only entries starting at first column go to shadow history | |
2188 | if line.lstrip() == line: |
|
2191 | if line.lstrip() == line: | |
2189 | self.shadowhist.add(line.strip()) |
|
2192 | self.shadowhist.add(line.strip()) | |
2190 | elif not continue_prompt: |
|
2193 | elif not continue_prompt: | |
2191 | self.input_hist_raw.append('\n') |
|
2194 | self.input_hist_raw.append('\n') | |
2192 | try: |
|
2195 | try: | |
2193 | lineout = self.prefilter(line,continue_prompt) |
|
2196 | lineout = self.prefilter(line,continue_prompt) | |
2194 | except: |
|
2197 | except: | |
2195 | # blanket except, in case a user-defined prefilter crashes, so it |
|
2198 | # blanket except, in case a user-defined prefilter crashes, so it | |
2196 | # can't take all of ipython with it. |
|
2199 | # can't take all of ipython with it. | |
2197 | self.showtraceback() |
|
2200 | self.showtraceback() | |
2198 | return '' |
|
2201 | return '' | |
2199 | else: |
|
2202 | else: | |
2200 | return lineout |
|
2203 | return lineout | |
2201 |
|
2204 | |||
2202 | def _prefilter(self, line, continue_prompt): |
|
2205 | def _prefilter(self, line, continue_prompt): | |
2203 | """Calls different preprocessors, depending on the form of line.""" |
|
2206 | """Calls different preprocessors, depending on the form of line.""" | |
2204 |
|
2207 | |||
2205 | # All handlers *must* return a value, even if it's blank (''). |
|
2208 | # All handlers *must* return a value, even if it's blank (''). | |
2206 |
|
2209 | |||
2207 | # Lines are NOT logged here. Handlers should process the line as |
|
2210 | # Lines are NOT logged here. Handlers should process the line as | |
2208 | # needed, update the cache AND log it (so that the input cache array |
|
2211 | # needed, update the cache AND log it (so that the input cache array | |
2209 | # stays synced). |
|
2212 | # stays synced). | |
2210 |
|
2213 | |||
2211 | #..................................................................... |
|
2214 | #..................................................................... | |
2212 | # Code begins |
|
2215 | # Code begins | |
2213 |
|
2216 | |||
2214 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg |
|
2217 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg | |
2215 |
|
2218 | |||
2216 | # save the line away in case we crash, so the post-mortem handler can |
|
2219 | # save the line away in case we crash, so the post-mortem handler can | |
2217 | # record it |
|
2220 | # record it | |
2218 | self._last_input_line = line |
|
2221 | self._last_input_line = line | |
2219 |
|
2222 | |||
2220 | #print '***line: <%s>' % line # dbg |
|
2223 | #print '***line: <%s>' % line # dbg | |
2221 |
|
2224 | |||
2222 | if not line: |
|
2225 | if not line: | |
2223 | # Return immediately on purely empty lines, so that if the user |
|
2226 | # Return immediately on purely empty lines, so that if the user | |
2224 | # previously typed some whitespace that started a continuation |
|
2227 | # previously typed some whitespace that started a continuation | |
2225 | # prompt, he can break out of that loop with just an empty line. |
|
2228 | # prompt, he can break out of that loop with just an empty line. | |
2226 | # This is how the default python prompt works. |
|
2229 | # This is how the default python prompt works. | |
2227 |
|
2230 | |||
2228 | # Only return if the accumulated input buffer was just whitespace! |
|
2231 | # Only return if the accumulated input buffer was just whitespace! | |
2229 | if ''.join(self.buffer).isspace(): |
|
2232 | if ''.join(self.buffer).isspace(): | |
2230 | self.buffer[:] = [] |
|
2233 | self.buffer[:] = [] | |
2231 | return '' |
|
2234 | return '' | |
2232 |
|
2235 | |||
2233 | line_info = prefilter.LineInfo(line, continue_prompt) |
|
2236 | line_info = prefilter.LineInfo(line, continue_prompt) | |
2234 |
|
2237 | |||
2235 | # the input history needs to track even empty lines |
|
2238 | # the input history needs to track even empty lines | |
2236 | stripped = line.strip() |
|
2239 | stripped = line.strip() | |
2237 |
|
2240 | |||
2238 | if not stripped: |
|
2241 | if not stripped: | |
2239 | if not continue_prompt: |
|
2242 | if not continue_prompt: | |
2240 | self.outputcache.prompt_count -= 1 |
|
2243 | self.outputcache.prompt_count -= 1 | |
2241 | return self.handle_normal(line_info) |
|
2244 | return self.handle_normal(line_info) | |
2242 |
|
2245 | |||
2243 | # print '***cont',continue_prompt # dbg |
|
2246 | # print '***cont',continue_prompt # dbg | |
2244 | # special handlers are only allowed for single line statements |
|
2247 | # special handlers are only allowed for single line statements | |
2245 | if continue_prompt and not self.rc.multi_line_specials: |
|
2248 | if continue_prompt and not self.rc.multi_line_specials: | |
2246 | return self.handle_normal(line_info) |
|
2249 | return self.handle_normal(line_info) | |
2247 |
|
2250 | |||
2248 |
|
2251 | |||
2249 | # See whether any pre-existing handler can take care of it |
|
2252 | # See whether any pre-existing handler can take care of it | |
2250 | rewritten = self.hooks.input_prefilter(stripped) |
|
2253 | rewritten = self.hooks.input_prefilter(stripped) | |
2251 | if rewritten != stripped: # ok, some prefilter did something |
|
2254 | if rewritten != stripped: # ok, some prefilter did something | |
2252 | rewritten = line_info.pre + rewritten # add indentation |
|
2255 | rewritten = line_info.pre + rewritten # add indentation | |
2253 | return self.handle_normal(prefilter.LineInfo(rewritten, |
|
2256 | return self.handle_normal(prefilter.LineInfo(rewritten, | |
2254 | continue_prompt)) |
|
2257 | continue_prompt)) | |
2255 |
|
2258 | |||
2256 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2259 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
2257 |
|
2260 | |||
2258 | return prefilter.prefilter(line_info, self) |
|
2261 | return prefilter.prefilter(line_info, self) | |
2259 |
|
2262 | |||
2260 |
|
2263 | |||
2261 | def _prefilter_dumb(self, line, continue_prompt): |
|
2264 | def _prefilter_dumb(self, line, continue_prompt): | |
2262 | """simple prefilter function, for debugging""" |
|
2265 | """simple prefilter function, for debugging""" | |
2263 | return self.handle_normal(line,continue_prompt) |
|
2266 | return self.handle_normal(line,continue_prompt) | |
2264 |
|
2267 | |||
2265 |
|
2268 | |||
2266 | def multiline_prefilter(self, line, continue_prompt): |
|
2269 | def multiline_prefilter(self, line, continue_prompt): | |
2267 | """ Run _prefilter for each line of input |
|
2270 | """ Run _prefilter for each line of input | |
2268 |
|
2271 | |||
2269 | Covers cases where there are multiple lines in the user entry, |
|
2272 | Covers cases where there are multiple lines in the user entry, | |
2270 | which is the case when the user goes back to a multiline history |
|
2273 | which is the case when the user goes back to a multiline history | |
2271 | entry and presses enter. |
|
2274 | entry and presses enter. | |
2272 |
|
2275 | |||
2273 | """ |
|
2276 | """ | |
2274 | out = [] |
|
2277 | out = [] | |
2275 | for l in line.rstrip('\n').split('\n'): |
|
2278 | for l in line.rstrip('\n').split('\n'): | |
2276 | out.append(self._prefilter(l, continue_prompt)) |
|
2279 | out.append(self._prefilter(l, continue_prompt)) | |
2277 | return '\n'.join(out) |
|
2280 | return '\n'.join(out) | |
2278 |
|
2281 | |||
2279 | # Set the default prefilter() function (this can be user-overridden) |
|
2282 | # Set the default prefilter() function (this can be user-overridden) | |
2280 | prefilter = multiline_prefilter |
|
2283 | prefilter = multiline_prefilter | |
2281 |
|
2284 | |||
2282 | def handle_normal(self,line_info): |
|
2285 | def handle_normal(self,line_info): | |
2283 | """Handle normal input lines. Use as a template for handlers.""" |
|
2286 | """Handle normal input lines. Use as a template for handlers.""" | |
2284 |
|
2287 | |||
2285 | # With autoindent on, we need some way to exit the input loop, and I |
|
2288 | # With autoindent on, we need some way to exit the input loop, and I | |
2286 | # don't want to force the user to have to backspace all the way to |
|
2289 | # don't want to force the user to have to backspace all the way to | |
2287 | # clear the line. The rule will be in this case, that either two |
|
2290 | # clear the line. The rule will be in this case, that either two | |
2288 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
2291 | # lines of pure whitespace in a row, or a line of pure whitespace but | |
2289 | # of a size different to the indent level, will exit the input loop. |
|
2292 | # of a size different to the indent level, will exit the input loop. | |
2290 | line = line_info.line |
|
2293 | line = line_info.line | |
2291 | continue_prompt = line_info.continue_prompt |
|
2294 | continue_prompt = line_info.continue_prompt | |
2292 |
|
2295 | |||
2293 | if (continue_prompt and self.autoindent and line.isspace() and |
|
2296 | if (continue_prompt and self.autoindent and line.isspace() and | |
2294 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or |
|
2297 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or | |
2295 | (self.buffer[-1]).isspace() )): |
|
2298 | (self.buffer[-1]).isspace() )): | |
2296 | line = '' |
|
2299 | line = '' | |
2297 |
|
2300 | |||
2298 | self.log(line,line,continue_prompt) |
|
2301 | self.log(line,line,continue_prompt) | |
2299 | return line |
|
2302 | return line | |
2300 |
|
2303 | |||
2301 | def handle_alias(self,line_info): |
|
2304 | def handle_alias(self,line_info): | |
2302 | """Handle alias input lines. """ |
|
2305 | """Handle alias input lines. """ | |
2303 | tgt = self.alias_table[line_info.iFun] |
|
2306 | tgt = self.alias_table[line_info.iFun] | |
2304 | # print "=>",tgt #dbg |
|
2307 | # print "=>",tgt #dbg | |
2305 | if callable(tgt): |
|
2308 | if callable(tgt): | |
2306 | if '$' in line_info.line: |
|
2309 | if '$' in line_info.line: | |
2307 | call_meth = '(_ip, _ip.itpl(%s))' |
|
2310 | call_meth = '(_ip, _ip.itpl(%s))' | |
2308 | else: |
|
2311 | else: | |
2309 | call_meth = '(_ip,%s)' |
|
2312 | call_meth = '(_ip,%s)' | |
2310 | line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace, |
|
2313 | line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace, | |
2311 | line_info.iFun, |
|
2314 | line_info.iFun, | |
2312 | make_quoted_expr(line_info.line)) |
|
2315 | make_quoted_expr(line_info.line)) | |
2313 | else: |
|
2316 | else: | |
2314 | transformed = self.expand_aliases(line_info.iFun,line_info.theRest) |
|
2317 | transformed = self.expand_aliases(line_info.iFun,line_info.theRest) | |
2315 |
|
2318 | |||
2316 | # pre is needed, because it carries the leading whitespace. Otherwise |
|
2319 | # pre is needed, because it carries the leading whitespace. Otherwise | |
2317 | # aliases won't work in indented sections. |
|
2320 | # aliases won't work in indented sections. | |
2318 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2321 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, | |
2319 | make_quoted_expr( transformed )) |
|
2322 | make_quoted_expr( transformed )) | |
2320 |
|
2323 | |||
2321 | self.log(line_info.line,line_out,line_info.continue_prompt) |
|
2324 | self.log(line_info.line,line_out,line_info.continue_prompt) | |
2322 | #print 'line out:',line_out # dbg |
|
2325 | #print 'line out:',line_out # dbg | |
2323 | return line_out |
|
2326 | return line_out | |
2324 |
|
2327 | |||
2325 | def handle_shell_escape(self, line_info): |
|
2328 | def handle_shell_escape(self, line_info): | |
2326 | """Execute the line in a shell, empty return value""" |
|
2329 | """Execute the line in a shell, empty return value""" | |
2327 | #print 'line in :', `line` # dbg |
|
2330 | #print 'line in :', `line` # dbg | |
2328 | line = line_info.line |
|
2331 | line = line_info.line | |
2329 | if line.lstrip().startswith('!!'): |
|
2332 | if line.lstrip().startswith('!!'): | |
2330 | # rewrite LineInfo's line, iFun and theRest to properly hold the |
|
2333 | # rewrite LineInfo's line, iFun and theRest to properly hold the | |
2331 | # call to %sx and the actual command to be executed, so |
|
2334 | # call to %sx and the actual command to be executed, so | |
2332 | # handle_magic can work correctly. Note that this works even if |
|
2335 | # handle_magic can work correctly. Note that this works even if | |
2333 | # the line is indented, so it handles multi_line_specials |
|
2336 | # the line is indented, so it handles multi_line_specials | |
2334 | # properly. |
|
2337 | # properly. | |
2335 | new_rest = line.lstrip()[2:] |
|
2338 | new_rest = line.lstrip()[2:] | |
2336 | line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest) |
|
2339 | line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest) | |
2337 | line_info.iFun = 'sx' |
|
2340 | line_info.iFun = 'sx' | |
2338 | line_info.theRest = new_rest |
|
2341 | line_info.theRest = new_rest | |
2339 | return self.handle_magic(line_info) |
|
2342 | return self.handle_magic(line_info) | |
2340 | else: |
|
2343 | else: | |
2341 | cmd = line.lstrip().lstrip('!') |
|
2344 | cmd = line.lstrip().lstrip('!') | |
2342 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2345 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, | |
2343 | make_quoted_expr(cmd)) |
|
2346 | make_quoted_expr(cmd)) | |
2344 | # update cache/log and return |
|
2347 | # update cache/log and return | |
2345 | self.log(line,line_out,line_info.continue_prompt) |
|
2348 | self.log(line,line_out,line_info.continue_prompt) | |
2346 | return line_out |
|
2349 | return line_out | |
2347 |
|
2350 | |||
2348 | def handle_magic(self, line_info): |
|
2351 | def handle_magic(self, line_info): | |
2349 | """Execute magic functions.""" |
|
2352 | """Execute magic functions.""" | |
2350 | iFun = line_info.iFun |
|
2353 | iFun = line_info.iFun | |
2351 | theRest = line_info.theRest |
|
2354 | theRest = line_info.theRest | |
2352 | cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace, |
|
2355 | cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace, | |
2353 | make_quoted_expr(iFun + " " + theRest)) |
|
2356 | make_quoted_expr(iFun + " " + theRest)) | |
2354 | self.log(line_info.line,cmd,line_info.continue_prompt) |
|
2357 | self.log(line_info.line,cmd,line_info.continue_prompt) | |
2355 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg |
|
2358 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg | |
2356 | return cmd |
|
2359 | return cmd | |
2357 |
|
2360 | |||
2358 | def handle_auto(self, line_info): |
|
2361 | def handle_auto(self, line_info): | |
2359 | """Hande lines which can be auto-executed, quoting if requested.""" |
|
2362 | """Hande lines which can be auto-executed, quoting if requested.""" | |
2360 |
|
2363 | |||
2361 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2364 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
2362 | line = line_info.line |
|
2365 | line = line_info.line | |
2363 | iFun = line_info.iFun |
|
2366 | iFun = line_info.iFun | |
2364 | theRest = line_info.theRest |
|
2367 | theRest = line_info.theRest | |
2365 | pre = line_info.pre |
|
2368 | pre = line_info.pre | |
2366 | continue_prompt = line_info.continue_prompt |
|
2369 | continue_prompt = line_info.continue_prompt | |
2367 | obj = line_info.ofind(self)['obj'] |
|
2370 | obj = line_info.ofind(self)['obj'] | |
2368 |
|
2371 | |||
2369 | # This should only be active for single-line input! |
|
2372 | # This should only be active for single-line input! | |
2370 | if continue_prompt: |
|
2373 | if continue_prompt: | |
2371 | self.log(line,line,continue_prompt) |
|
2374 | self.log(line,line,continue_prompt) | |
2372 | return line |
|
2375 | return line | |
2373 |
|
2376 | |||
2374 | force_auto = isinstance(obj, IPython.ipapi.IPyAutocall) |
|
2377 | force_auto = isinstance(obj, IPython.ipapi.IPyAutocall) | |
2375 | auto_rewrite = True |
|
2378 | auto_rewrite = True | |
2376 |
|
2379 | |||
2377 | if pre == self.ESC_QUOTE: |
|
2380 | if pre == self.ESC_QUOTE: | |
2378 | # Auto-quote splitting on whitespace |
|
2381 | # Auto-quote splitting on whitespace | |
2379 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) |
|
2382 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) | |
2380 | elif pre == self.ESC_QUOTE2: |
|
2383 | elif pre == self.ESC_QUOTE2: | |
2381 | # Auto-quote whole string |
|
2384 | # Auto-quote whole string | |
2382 | newcmd = '%s("%s")' % (iFun,theRest) |
|
2385 | newcmd = '%s("%s")' % (iFun,theRest) | |
2383 | elif pre == self.ESC_PAREN: |
|
2386 | elif pre == self.ESC_PAREN: | |
2384 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) |
|
2387 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) | |
2385 | else: |
|
2388 | else: | |
2386 | # Auto-paren. |
|
2389 | # Auto-paren. | |
2387 | # We only apply it to argument-less calls if the autocall |
|
2390 | # We only apply it to argument-less calls if the autocall | |
2388 | # parameter is set to 2. We only need to check that autocall is < |
|
2391 | # parameter is set to 2. We only need to check that autocall is < | |
2389 | # 2, since this function isn't called unless it's at least 1. |
|
2392 | # 2, since this function isn't called unless it's at least 1. | |
2390 | if not theRest and (self.rc.autocall < 2) and not force_auto: |
|
2393 | if not theRest and (self.rc.autocall < 2) and not force_auto: | |
2391 | newcmd = '%s %s' % (iFun,theRest) |
|
2394 | newcmd = '%s %s' % (iFun,theRest) | |
2392 | auto_rewrite = False |
|
2395 | auto_rewrite = False | |
2393 | else: |
|
2396 | else: | |
2394 | if not force_auto and theRest.startswith('['): |
|
2397 | if not force_auto and theRest.startswith('['): | |
2395 | if hasattr(obj,'__getitem__'): |
|
2398 | if hasattr(obj,'__getitem__'): | |
2396 | # Don't autocall in this case: item access for an object |
|
2399 | # Don't autocall in this case: item access for an object | |
2397 | # which is BOTH callable and implements __getitem__. |
|
2400 | # which is BOTH callable and implements __getitem__. | |
2398 | newcmd = '%s %s' % (iFun,theRest) |
|
2401 | newcmd = '%s %s' % (iFun,theRest) | |
2399 | auto_rewrite = False |
|
2402 | auto_rewrite = False | |
2400 | else: |
|
2403 | else: | |
2401 | # if the object doesn't support [] access, go ahead and |
|
2404 | # if the object doesn't support [] access, go ahead and | |
2402 | # autocall |
|
2405 | # autocall | |
2403 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) |
|
2406 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) | |
2404 | elif theRest.endswith(';'): |
|
2407 | elif theRest.endswith(';'): | |
2405 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) |
|
2408 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) | |
2406 | else: |
|
2409 | else: | |
2407 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) |
|
2410 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) | |
2408 |
|
2411 | |||
2409 | if auto_rewrite: |
|
2412 | if auto_rewrite: | |
2410 | rw = self.outputcache.prompt1.auto_rewrite() + newcmd |
|
2413 | rw = self.outputcache.prompt1.auto_rewrite() + newcmd | |
2411 |
|
2414 | |||
2412 | try: |
|
2415 | try: | |
2413 | # plain ascii works better w/ pyreadline, on some machines, so |
|
2416 | # plain ascii works better w/ pyreadline, on some machines, so | |
2414 | # we use it and only print uncolored rewrite if we have unicode |
|
2417 | # we use it and only print uncolored rewrite if we have unicode | |
2415 | rw = str(rw) |
|
2418 | rw = str(rw) | |
2416 | print >>Term.cout, rw |
|
2419 | print >>Term.cout, rw | |
2417 | except UnicodeEncodeError: |
|
2420 | except UnicodeEncodeError: | |
2418 | print "-------------->" + newcmd |
|
2421 | print "-------------->" + newcmd | |
2419 |
|
2422 | |||
2420 | # log what is now valid Python, not the actual user input (without the |
|
2423 | # log what is now valid Python, not the actual user input (without the | |
2421 | # final newline) |
|
2424 | # final newline) | |
2422 | self.log(line,newcmd,continue_prompt) |
|
2425 | self.log(line,newcmd,continue_prompt) | |
2423 | return newcmd |
|
2426 | return newcmd | |
2424 |
|
2427 | |||
2425 | def handle_help(self, line_info): |
|
2428 | def handle_help(self, line_info): | |
2426 | """Try to get some help for the object. |
|
2429 | """Try to get some help for the object. | |
2427 |
|
2430 | |||
2428 | obj? or ?obj -> basic information. |
|
2431 | obj? or ?obj -> basic information. | |
2429 | obj?? or ??obj -> more details. |
|
2432 | obj?? or ??obj -> more details. | |
2430 | """ |
|
2433 | """ | |
2431 |
|
2434 | |||
2432 | line = line_info.line |
|
2435 | line = line_info.line | |
2433 | # We need to make sure that we don't process lines which would be |
|
2436 | # We need to make sure that we don't process lines which would be | |
2434 | # otherwise valid python, such as "x=1 # what?" |
|
2437 | # otherwise valid python, such as "x=1 # what?" | |
2435 | try: |
|
2438 | try: | |
2436 | codeop.compile_command(line) |
|
2439 | codeop.compile_command(line) | |
2437 | except SyntaxError: |
|
2440 | except SyntaxError: | |
2438 | # We should only handle as help stuff which is NOT valid syntax |
|
2441 | # We should only handle as help stuff which is NOT valid syntax | |
2439 | if line[0]==self.ESC_HELP: |
|
2442 | if line[0]==self.ESC_HELP: | |
2440 | line = line[1:] |
|
2443 | line = line[1:] | |
2441 | elif line[-1]==self.ESC_HELP: |
|
2444 | elif line[-1]==self.ESC_HELP: | |
2442 | line = line[:-1] |
|
2445 | line = line[:-1] | |
2443 | self.log(line,'#?'+line,line_info.continue_prompt) |
|
2446 | self.log(line,'#?'+line,line_info.continue_prompt) | |
2444 | if line: |
|
2447 | if line: | |
2445 | #print 'line:<%r>' % line # dbg |
|
2448 | #print 'line:<%r>' % line # dbg | |
2446 | self.magic_pinfo(line) |
|
2449 | self.magic_pinfo(line) | |
2447 | else: |
|
2450 | else: | |
2448 | page(self.usage,screen_lines=self.rc.screen_length) |
|
2451 | page(self.usage,screen_lines=self.rc.screen_length) | |
2449 | return '' # Empty string is needed here! |
|
2452 | return '' # Empty string is needed here! | |
2450 | except: |
|
2453 | except: | |
2451 | # Pass any other exceptions through to the normal handler |
|
2454 | # Pass any other exceptions through to the normal handler | |
2452 | return self.handle_normal(line_info) |
|
2455 | return self.handle_normal(line_info) | |
2453 | else: |
|
2456 | else: | |
2454 | # If the code compiles ok, we should handle it normally |
|
2457 | # If the code compiles ok, we should handle it normally | |
2455 | return self.handle_normal(line_info) |
|
2458 | return self.handle_normal(line_info) | |
2456 |
|
2459 | |||
2457 | def getapi(self): |
|
2460 | def getapi(self): | |
2458 | """ Get an IPApi object for this shell instance |
|
2461 | """ Get an IPApi object for this shell instance | |
2459 |
|
2462 | |||
2460 | Getting an IPApi object is always preferable to accessing the shell |
|
2463 | Getting an IPApi object is always preferable to accessing the shell | |
2461 | directly, but this holds true especially for extensions. |
|
2464 | directly, but this holds true especially for extensions. | |
2462 |
|
2465 | |||
2463 | It should always be possible to implement an extension with IPApi |
|
2466 | It should always be possible to implement an extension with IPApi | |
2464 | alone. If not, contact maintainer to request an addition. |
|
2467 | alone. If not, contact maintainer to request an addition. | |
2465 |
|
2468 | |||
2466 | """ |
|
2469 | """ | |
2467 | return self.api |
|
2470 | return self.api | |
2468 |
|
2471 | |||
2469 | def handle_emacs(self, line_info): |
|
2472 | def handle_emacs(self, line_info): | |
2470 | """Handle input lines marked by python-mode.""" |
|
2473 | """Handle input lines marked by python-mode.""" | |
2471 |
|
2474 | |||
2472 | # Currently, nothing is done. Later more functionality can be added |
|
2475 | # Currently, nothing is done. Later more functionality can be added | |
2473 | # here if needed. |
|
2476 | # here if needed. | |
2474 |
|
2477 | |||
2475 | # The input cache shouldn't be updated |
|
2478 | # The input cache shouldn't be updated | |
2476 | return line_info.line |
|
2479 | return line_info.line | |
2477 |
|
2480 | |||
2478 |
|
2481 | |||
2479 | def mktempfile(self,data=None): |
|
2482 | def mktempfile(self,data=None): | |
2480 | """Make a new tempfile and return its filename. |
|
2483 | """Make a new tempfile and return its filename. | |
2481 |
|
2484 | |||
2482 | This makes a call to tempfile.mktemp, but it registers the created |
|
2485 | This makes a call to tempfile.mktemp, but it registers the created | |
2483 | filename internally so ipython cleans it up at exit time. |
|
2486 | filename internally so ipython cleans it up at exit time. | |
2484 |
|
2487 | |||
2485 | Optional inputs: |
|
2488 | Optional inputs: | |
2486 |
|
2489 | |||
2487 | - data(None): if data is given, it gets written out to the temp file |
|
2490 | - data(None): if data is given, it gets written out to the temp file | |
2488 | immediately, and the file is closed again.""" |
|
2491 | immediately, and the file is closed again.""" | |
2489 |
|
2492 | |||
2490 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2493 | filename = tempfile.mktemp('.py','ipython_edit_') | |
2491 | self.tempfiles.append(filename) |
|
2494 | self.tempfiles.append(filename) | |
2492 |
|
2495 | |||
2493 | if data: |
|
2496 | if data: | |
2494 | tmp_file = open(filename,'w') |
|
2497 | tmp_file = open(filename,'w') | |
2495 | tmp_file.write(data) |
|
2498 | tmp_file.write(data) | |
2496 | tmp_file.close() |
|
2499 | tmp_file.close() | |
2497 | return filename |
|
2500 | return filename | |
2498 |
|
2501 | |||
2499 | def write(self,data): |
|
2502 | def write(self,data): | |
2500 | """Write a string to the default output""" |
|
2503 | """Write a string to the default output""" | |
2501 | Term.cout.write(data) |
|
2504 | Term.cout.write(data) | |
2502 |
|
2505 | |||
2503 | def write_err(self,data): |
|
2506 | def write_err(self,data): | |
2504 | """Write a string to the default error output""" |
|
2507 | """Write a string to the default error output""" | |
2505 | Term.cerr.write(data) |
|
2508 | Term.cerr.write(data) | |
2506 |
|
2509 | |||
2507 | def exit(self): |
|
2510 | def exit(self): | |
2508 | """Handle interactive exit. |
|
2511 | """Handle interactive exit. | |
2509 |
|
2512 | |||
2510 | This method sets the exit_now attribute.""" |
|
2513 | This method sets the exit_now attribute.""" | |
2511 |
|
2514 | |||
2512 | if self.rc.confirm_exit: |
|
2515 | if self.rc.confirm_exit: | |
2513 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
2516 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): | |
2514 | self.exit_now = True |
|
2517 | self.exit_now = True | |
2515 | else: |
|
2518 | else: | |
2516 | self.exit_now = True |
|
2519 | self.exit_now = True | |
2517 |
|
2520 | |||
2518 | def safe_execfile(self,fname,*where,**kw): |
|
2521 | def safe_execfile(self,fname,*where,**kw): | |
2519 | """A safe version of the builtin execfile(). |
|
2522 | """A safe version of the builtin execfile(). | |
2520 |
|
2523 | |||
2521 | This version will never throw an exception, and knows how to handle |
|
2524 | This version will never throw an exception, and knows how to handle | |
2522 | ipython logs as well. |
|
2525 | ipython logs as well. | |
2523 |
|
2526 | |||
2524 | :Parameters: |
|
2527 | :Parameters: | |
2525 | fname : string |
|
2528 | fname : string | |
2526 | Name of the file to be executed. |
|
2529 | Name of the file to be executed. | |
2527 |
|
2530 | |||
2528 | where : tuple |
|
2531 | where : tuple | |
2529 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2532 | One or two namespaces, passed to execfile() as (globals,locals). | |
2530 | If only one is given, it is passed as both. |
|
2533 | If only one is given, it is passed as both. | |
2531 |
|
2534 | |||
2532 | :Keywords: |
|
2535 | :Keywords: | |
2533 | islog : boolean (False) |
|
2536 | islog : boolean (False) | |
2534 |
|
2537 | |||
2535 | quiet : boolean (True) |
|
2538 | quiet : boolean (True) | |
2536 |
|
2539 | |||
2537 | exit_ignore : boolean (False) |
|
2540 | exit_ignore : boolean (False) | |
2538 | """ |
|
2541 | """ | |
2539 |
|
2542 | |||
2540 | def syspath_cleanup(): |
|
2543 | def syspath_cleanup(): | |
2541 | """Internal cleanup routine for sys.path.""" |
|
2544 | """Internal cleanup routine for sys.path.""" | |
2542 | if add_dname: |
|
2545 | if add_dname: | |
2543 | try: |
|
2546 | try: | |
2544 | sys.path.remove(dname) |
|
2547 | sys.path.remove(dname) | |
2545 | except ValueError: |
|
2548 | except ValueError: | |
2546 | # For some reason the user has already removed it, ignore. |
|
2549 | # For some reason the user has already removed it, ignore. | |
2547 | pass |
|
2550 | pass | |
2548 |
|
2551 | |||
2549 | fname = os.path.expanduser(fname) |
|
2552 | fname = os.path.expanduser(fname) | |
2550 |
|
2553 | |||
2551 | # Find things also in current directory. This is needed to mimic the |
|
2554 | # Find things also in current directory. This is needed to mimic the | |
2552 | # behavior of running a script from the system command line, where |
|
2555 | # behavior of running a script from the system command line, where | |
2553 | # Python inserts the script's directory into sys.path |
|
2556 | # Python inserts the script's directory into sys.path | |
2554 | dname = os.path.dirname(os.path.abspath(fname)) |
|
2557 | dname = os.path.dirname(os.path.abspath(fname)) | |
2555 | add_dname = False |
|
2558 | add_dname = False | |
2556 | if dname not in sys.path: |
|
2559 | if dname not in sys.path: | |
2557 | sys.path.insert(0,dname) |
|
2560 | sys.path.insert(0,dname) | |
2558 | add_dname = True |
|
2561 | add_dname = True | |
2559 |
|
2562 | |||
2560 | try: |
|
2563 | try: | |
2561 | xfile = open(fname) |
|
2564 | xfile = open(fname) | |
2562 | except: |
|
2565 | except: | |
2563 | print >> Term.cerr, \ |
|
2566 | print >> Term.cerr, \ | |
2564 | 'Could not open file <%s> for safe execution.' % fname |
|
2567 | 'Could not open file <%s> for safe execution.' % fname | |
2565 | syspath_cleanup() |
|
2568 | syspath_cleanup() | |
2566 | return None |
|
2569 | return None | |
2567 |
|
2570 | |||
2568 | kw.setdefault('islog',0) |
|
2571 | kw.setdefault('islog',0) | |
2569 | kw.setdefault('quiet',1) |
|
2572 | kw.setdefault('quiet',1) | |
2570 | kw.setdefault('exit_ignore',0) |
|
2573 | kw.setdefault('exit_ignore',0) | |
2571 |
|
2574 | |||
2572 | first = xfile.readline() |
|
2575 | first = xfile.readline() | |
2573 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() |
|
2576 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() | |
2574 | xfile.close() |
|
2577 | xfile.close() | |
2575 | # line by line execution |
|
2578 | # line by line execution | |
2576 | if first.startswith(loghead) or kw['islog']: |
|
2579 | if first.startswith(loghead) or kw['islog']: | |
2577 | print 'Loading log file <%s> one line at a time...' % fname |
|
2580 | print 'Loading log file <%s> one line at a time...' % fname | |
2578 | if kw['quiet']: |
|
2581 | if kw['quiet']: | |
2579 | stdout_save = sys.stdout |
|
2582 | stdout_save = sys.stdout | |
2580 | sys.stdout = StringIO.StringIO() |
|
2583 | sys.stdout = StringIO.StringIO() | |
2581 | try: |
|
2584 | try: | |
2582 | globs,locs = where[0:2] |
|
2585 | globs,locs = where[0:2] | |
2583 | except: |
|
2586 | except: | |
2584 | try: |
|
2587 | try: | |
2585 | globs = locs = where[0] |
|
2588 | globs = locs = where[0] | |
2586 | except: |
|
2589 | except: | |
2587 | globs = locs = globals() |
|
2590 | globs = locs = globals() | |
2588 | badblocks = [] |
|
2591 | badblocks = [] | |
2589 |
|
2592 | |||
2590 | # we also need to identify indented blocks of code when replaying |
|
2593 | # we also need to identify indented blocks of code when replaying | |
2591 | # logs and put them together before passing them to an exec |
|
2594 | # logs and put them together before passing them to an exec | |
2592 | # statement. This takes a bit of regexp and look-ahead work in the |
|
2595 | # statement. This takes a bit of regexp and look-ahead work in the | |
2593 | # file. It's easiest if we swallow the whole thing in memory |
|
2596 | # file. It's easiest if we swallow the whole thing in memory | |
2594 | # first, and manually walk through the lines list moving the |
|
2597 | # first, and manually walk through the lines list moving the | |
2595 | # counter ourselves. |
|
2598 | # counter ourselves. | |
2596 | indent_re = re.compile('\s+\S') |
|
2599 | indent_re = re.compile('\s+\S') | |
2597 | xfile = open(fname) |
|
2600 | xfile = open(fname) | |
2598 | filelines = xfile.readlines() |
|
2601 | filelines = xfile.readlines() | |
2599 | xfile.close() |
|
2602 | xfile.close() | |
2600 | nlines = len(filelines) |
|
2603 | nlines = len(filelines) | |
2601 | lnum = 0 |
|
2604 | lnum = 0 | |
2602 | while lnum < nlines: |
|
2605 | while lnum < nlines: | |
2603 | line = filelines[lnum] |
|
2606 | line = filelines[lnum] | |
2604 | lnum += 1 |
|
2607 | lnum += 1 | |
2605 | # don't re-insert logger status info into cache |
|
2608 | # don't re-insert logger status info into cache | |
2606 | if line.startswith('#log#'): |
|
2609 | if line.startswith('#log#'): | |
2607 | continue |
|
2610 | continue | |
2608 | else: |
|
2611 | else: | |
2609 | # build a block of code (maybe a single line) for execution |
|
2612 | # build a block of code (maybe a single line) for execution | |
2610 | block = line |
|
2613 | block = line | |
2611 | try: |
|
2614 | try: | |
2612 | next = filelines[lnum] # lnum has already incremented |
|
2615 | next = filelines[lnum] # lnum has already incremented | |
2613 | except: |
|
2616 | except: | |
2614 | next = None |
|
2617 | next = None | |
2615 | while next and indent_re.match(next): |
|
2618 | while next and indent_re.match(next): | |
2616 | block += next |
|
2619 | block += next | |
2617 | lnum += 1 |
|
2620 | lnum += 1 | |
2618 | try: |
|
2621 | try: | |
2619 | next = filelines[lnum] |
|
2622 | next = filelines[lnum] | |
2620 | except: |
|
2623 | except: | |
2621 | next = None |
|
2624 | next = None | |
2622 | # now execute the block of one or more lines |
|
2625 | # now execute the block of one or more lines | |
2623 | try: |
|
2626 | try: | |
2624 | exec block in globs,locs |
|
2627 | exec block in globs,locs | |
2625 | except SystemExit: |
|
2628 | except SystemExit: | |
2626 | pass |
|
2629 | pass | |
2627 | except: |
|
2630 | except: | |
2628 | badblocks.append(block.rstrip()) |
|
2631 | badblocks.append(block.rstrip()) | |
2629 | if kw['quiet']: # restore stdout |
|
2632 | if kw['quiet']: # restore stdout | |
2630 | sys.stdout.close() |
|
2633 | sys.stdout.close() | |
2631 | sys.stdout = stdout_save |
|
2634 | sys.stdout = stdout_save | |
2632 | print 'Finished replaying log file <%s>' % fname |
|
2635 | print 'Finished replaying log file <%s>' % fname | |
2633 | if badblocks: |
|
2636 | if badblocks: | |
2634 | print >> sys.stderr, ('\nThe following lines/blocks in file ' |
|
2637 | print >> sys.stderr, ('\nThe following lines/blocks in file ' | |
2635 | '<%s> reported errors:' % fname) |
|
2638 | '<%s> reported errors:' % fname) | |
2636 |
|
2639 | |||
2637 | for badline in badblocks: |
|
2640 | for badline in badblocks: | |
2638 | print >> sys.stderr, badline |
|
2641 | print >> sys.stderr, badline | |
2639 | else: # regular file execution |
|
2642 | else: # regular file execution | |
2640 | try: |
|
2643 | try: | |
2641 | if sys.platform == 'win32' and sys.version_info < (2,5,1): |
|
2644 | if sys.platform == 'win32' and sys.version_info < (2,5,1): | |
2642 | # Work around a bug in Python for Windows. The bug was |
|
2645 | # Work around a bug in Python for Windows. The bug was | |
2643 | # fixed in in Python 2.5 r54159 and 54158, but that's still |
|
2646 | # fixed in in Python 2.5 r54159 and 54158, but that's still | |
2644 | # SVN Python as of March/07. For details, see: |
|
2647 | # SVN Python as of March/07. For details, see: | |
2645 | # http://projects.scipy.org/ipython/ipython/ticket/123 |
|
2648 | # http://projects.scipy.org/ipython/ipython/ticket/123 | |
2646 | try: |
|
2649 | try: | |
2647 | globs,locs = where[0:2] |
|
2650 | globs,locs = where[0:2] | |
2648 | except: |
|
2651 | except: | |
2649 | try: |
|
2652 | try: | |
2650 | globs = locs = where[0] |
|
2653 | globs = locs = where[0] | |
2651 | except: |
|
2654 | except: | |
2652 | globs = locs = globals() |
|
2655 | globs = locs = globals() | |
2653 | exec file(fname) in globs,locs |
|
2656 | exec file(fname) in globs,locs | |
2654 | else: |
|
2657 | else: | |
2655 | execfile(fname,*where) |
|
2658 | execfile(fname,*where) | |
2656 | except SyntaxError: |
|
2659 | except SyntaxError: | |
2657 | self.showsyntaxerror() |
|
2660 | self.showsyntaxerror() | |
2658 | warn('Failure executing file: <%s>' % fname) |
|
2661 | warn('Failure executing file: <%s>' % fname) | |
2659 | except SystemExit,status: |
|
2662 | except SystemExit,status: | |
2660 | # Code that correctly sets the exit status flag to success (0) |
|
2663 | # Code that correctly sets the exit status flag to success (0) | |
2661 | # shouldn't be bothered with a traceback. Note that a plain |
|
2664 | # shouldn't be bothered with a traceback. Note that a plain | |
2662 | # sys.exit() does NOT set the message to 0 (it's empty) so that |
|
2665 | # sys.exit() does NOT set the message to 0 (it's empty) so that | |
2663 | # will still get a traceback. Note that the structure of the |
|
2666 | # will still get a traceback. Note that the structure of the | |
2664 | # SystemExit exception changed between Python 2.4 and 2.5, so |
|
2667 | # SystemExit exception changed between Python 2.4 and 2.5, so | |
2665 | # the checks must be done in a version-dependent way. |
|
2668 | # the checks must be done in a version-dependent way. | |
2666 | show = False |
|
2669 | show = False | |
2667 |
|
2670 | |||
2668 | if sys.version_info[:2] > (2,5): |
|
2671 | if sys.version_info[:2] > (2,5): | |
2669 | if status.message!=0 and not kw['exit_ignore']: |
|
2672 | if status.message!=0 and not kw['exit_ignore']: | |
2670 | show = True |
|
2673 | show = True | |
2671 | else: |
|
2674 | else: | |
2672 | if status.code and not kw['exit_ignore']: |
|
2675 | if status.code and not kw['exit_ignore']: | |
2673 | show = True |
|
2676 | show = True | |
2674 | if show: |
|
2677 | if show: | |
2675 | self.showtraceback() |
|
2678 | self.showtraceback() | |
2676 | warn('Failure executing file: <%s>' % fname) |
|
2679 | warn('Failure executing file: <%s>' % fname) | |
2677 | except: |
|
2680 | except: | |
2678 | self.showtraceback() |
|
2681 | self.showtraceback() | |
2679 | warn('Failure executing file: <%s>' % fname) |
|
2682 | warn('Failure executing file: <%s>' % fname) | |
2680 |
|
2683 | |||
2681 | syspath_cleanup() |
|
2684 | syspath_cleanup() | |
2682 |
|
2685 | |||
2683 | #************************* end of file <iplib.py> ***************************** |
|
2686 | #************************* end of file <iplib.py> ***************************** |
@@ -1,775 +1,778 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | IPython -- An enhanced Interactive Python |
|
3 | IPython -- An enhanced Interactive Python | |
4 |
|
4 | |||
5 | Requires Python 2.1 or better. |
|
5 | Requires Python 2.1 or better. | |
6 |
|
6 | |||
7 | This file contains the main make_IPython() starter function. |
|
7 | This file contains the main make_IPython() starter function. | |
8 |
|
8 | |||
9 | $Id: ipmaker.py 2930 2008-01-11 07:03:11Z vivainio $""" |
|
9 | $Id: ipmaker.py 2930 2008-01-11 07:03:11Z vivainio $""" | |
10 |
|
10 | |||
11 | #***************************************************************************** |
|
11 | #***************************************************************************** | |
12 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
12 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> | |
13 | # |
|
13 | # | |
14 | # Distributed under the terms of the BSD License. The full license is in |
|
14 | # Distributed under the terms of the BSD License. The full license is in | |
15 | # the file COPYING, distributed as part of this software. |
|
15 | # the file COPYING, distributed as part of this software. | |
16 | #***************************************************************************** |
|
16 | #***************************************************************************** | |
17 |
|
17 | |||
18 | from IPython import Release |
|
18 | from IPython import Release | |
19 | __author__ = '%s <%s>' % Release.authors['Fernando'] |
|
19 | __author__ = '%s <%s>' % Release.authors['Fernando'] | |
20 | __license__ = Release.license |
|
20 | __license__ = Release.license | |
21 | __version__ = Release.version |
|
21 | __version__ = Release.version | |
22 |
|
22 | |||
23 | try: |
|
23 | try: | |
24 | credits._Printer__data = """ |
|
24 | credits._Printer__data = """ | |
25 | Python: %s |
|
25 | Python: %s | |
26 |
|
26 | |||
27 | IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users. |
|
27 | IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users. | |
28 | See http://ipython.scipy.org for more information.""" \ |
|
28 | See http://ipython.scipy.org for more information.""" \ | |
29 | % credits._Printer__data |
|
29 | % credits._Printer__data | |
30 |
|
30 | |||
31 | copyright._Printer__data += """ |
|
31 | copyright._Printer__data += """ | |
32 |
|
32 | |||
33 | Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray. |
|
33 | Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray. | |
34 | All Rights Reserved.""" |
|
34 | All Rights Reserved.""" | |
35 | except NameError: |
|
35 | except NameError: | |
36 | # Can happen if ipython was started with 'python -S', so that site.py is |
|
36 | # Can happen if ipython was started with 'python -S', so that site.py is | |
37 | # not loaded |
|
37 | # not loaded | |
38 | pass |
|
38 | pass | |
39 |
|
39 | |||
40 | #**************************************************************************** |
|
40 | #**************************************************************************** | |
41 | # Required modules |
|
41 | # Required modules | |
42 |
|
42 | |||
43 | # From the standard library |
|
43 | # From the standard library | |
44 | import __main__ |
|
44 | import __main__ | |
45 | import __builtin__ |
|
45 | import __builtin__ | |
46 | import os |
|
46 | import os | |
47 | import re |
|
47 | import re | |
48 | import sys |
|
48 | import sys | |
49 | import types |
|
49 | import types | |
50 | from pprint import pprint,pformat |
|
50 | from pprint import pprint,pformat | |
51 |
|
51 | |||
52 | # Our own |
|
52 | # Our own | |
53 | from IPython import DPyGetOpt |
|
53 | from IPython import DPyGetOpt | |
54 | from IPython.ipstruct import Struct |
|
54 | from IPython.ipstruct import Struct | |
55 | from IPython.OutputTrap import OutputTrap |
|
55 | from IPython.OutputTrap import OutputTrap | |
56 | from IPython.ConfigLoader import ConfigLoader |
|
56 | from IPython.ConfigLoader import ConfigLoader | |
57 | from IPython.iplib import InteractiveShell |
|
57 | from IPython.iplib import InteractiveShell | |
58 | from IPython.usage import cmd_line_usage,interactive_usage |
|
58 | from IPython.usage import cmd_line_usage,interactive_usage | |
59 | from IPython.genutils import * |
|
59 | from IPython.genutils import * | |
60 |
|
60 | |||
61 | def force_import(modname): |
|
61 | def force_import(modname): | |
62 | if modname in sys.modules: |
|
62 | if modname in sys.modules: | |
63 | print "reload",modname |
|
63 | print "reload",modname | |
64 | reload(sys.modules[modname]) |
|
64 | reload(sys.modules[modname]) | |
65 | else: |
|
65 | else: | |
66 | __import__(modname) |
|
66 | __import__(modname) | |
67 |
|
67 | |||
68 |
|
68 | |||
69 | #----------------------------------------------------------------------------- |
|
69 | #----------------------------------------------------------------------------- | |
70 | def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1, |
|
70 | def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1, | |
71 | rc_override=None,shell_class=InteractiveShell, |
|
71 | rc_override=None,shell_class=InteractiveShell, | |
72 | embedded=False,**kw): |
|
72 | embedded=False,**kw): | |
73 | """This is a dump of IPython into a single function. |
|
73 | """This is a dump of IPython into a single function. | |
74 |
|
74 | |||
75 | Later it will have to be broken up in a sensible manner. |
|
75 | Later it will have to be broken up in a sensible manner. | |
76 |
|
76 | |||
77 | Arguments: |
|
77 | Arguments: | |
78 |
|
78 | |||
79 | - argv: a list similar to sys.argv[1:]. It should NOT contain the desired |
|
79 | - argv: a list similar to sys.argv[1:]. It should NOT contain the desired | |
80 | script name, b/c DPyGetOpt strips the first argument only for the real |
|
80 | script name, b/c DPyGetOpt strips the first argument only for the real | |
81 | sys.argv. |
|
81 | sys.argv. | |
82 |
|
82 | |||
83 | - user_ns: a dict to be used as the user's namespace.""" |
|
83 | - user_ns: a dict to be used as the user's namespace.""" | |
84 |
|
84 | |||
85 | #---------------------------------------------------------------------- |
|
85 | #---------------------------------------------------------------------- | |
86 | # Defaults and initialization |
|
86 | # Defaults and initialization | |
87 |
|
87 | |||
88 | # For developer debugging, deactivates crash handler and uses pdb. |
|
88 | # For developer debugging, deactivates crash handler and uses pdb. | |
89 | DEVDEBUG = False |
|
89 | DEVDEBUG = False | |
90 |
|
90 | |||
91 | if argv is None: |
|
91 | if argv is None: | |
92 | argv = sys.argv |
|
92 | argv = sys.argv | |
93 |
|
93 | |||
94 | # __IP is the main global that lives throughout and represents the whole |
|
94 | # __IP is the main global that lives throughout and represents the whole | |
95 | # application. If the user redefines it, all bets are off as to what |
|
95 | # application. If the user redefines it, all bets are off as to what | |
96 | # happens. |
|
96 | # happens. | |
97 |
|
97 | |||
98 | # __IP is the name of he global which the caller will have accessible as |
|
98 | # __IP is the name of he global which the caller will have accessible as | |
99 | # __IP.name. We set its name via the first parameter passed to |
|
99 | # __IP.name. We set its name via the first parameter passed to | |
100 | # InteractiveShell: |
|
100 | # InteractiveShell: | |
101 |
|
101 | |||
102 | IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns, |
|
102 | IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns, | |
103 | embedded=embedded,**kw) |
|
103 | embedded=embedded,**kw) | |
104 |
|
104 | |||
105 | # Put 'help' in the user namespace |
|
105 | # Put 'help' in the user namespace | |
106 | from site import _Helper |
|
106 | try: | |
|
107 | from site import _Helper | |||
|
108 | IP.user_ns['help'] = _Helper() | |||
|
109 | except ImportError: | |||
|
110 | warn('help() not available - check site.py') | |||
107 | IP.user_config_ns = {} |
|
111 | IP.user_config_ns = {} | |
108 | IP.user_ns['help'] = _Helper() |
|
|||
109 |
|
112 | |||
110 |
|
113 | |||
111 | if DEVDEBUG: |
|
114 | if DEVDEBUG: | |
112 | # For developer debugging only (global flag) |
|
115 | # For developer debugging only (global flag) | |
113 | from IPython import ultraTB |
|
116 | from IPython import ultraTB | |
114 | sys.excepthook = ultraTB.VerboseTB(call_pdb=1) |
|
117 | sys.excepthook = ultraTB.VerboseTB(call_pdb=1) | |
115 |
|
118 | |||
116 | IP.BANNER_PARTS = ['Python %s\n' |
|
119 | IP.BANNER_PARTS = ['Python %s\n' | |
117 | 'Type "copyright", "credits" or "license" ' |
|
120 | 'Type "copyright", "credits" or "license" ' | |
118 | 'for more information.\n' |
|
121 | 'for more information.\n' | |
119 | % (sys.version.split('\n')[0],), |
|
122 | % (sys.version.split('\n')[0],), | |
120 | "IPython %s -- An enhanced Interactive Python." |
|
123 | "IPython %s -- An enhanced Interactive Python." | |
121 | % (__version__,), |
|
124 | % (__version__,), | |
122 | """\ |
|
125 | """\ | |
123 | ? -> Introduction and overview of IPython's features. |
|
126 | ? -> Introduction and overview of IPython's features. | |
124 | %quickref -> Quick reference. |
|
127 | %quickref -> Quick reference. | |
125 | help -> Python's own help system. |
|
128 | help -> Python's own help system. | |
126 | object? -> Details about 'object'. ?object also works, ?? prints more. |
|
129 | object? -> Details about 'object'. ?object also works, ?? prints more. | |
127 | """ ] |
|
130 | """ ] | |
128 |
|
131 | |||
129 | IP.usage = interactive_usage |
|
132 | IP.usage = interactive_usage | |
130 |
|
133 | |||
131 | # Platform-dependent suffix and directory names. We use _ipython instead |
|
134 | # Platform-dependent suffix and directory names. We use _ipython instead | |
132 | # of .ipython under win32 b/c there's software that breaks with .named |
|
135 | # of .ipython under win32 b/c there's software that breaks with .named | |
133 | # directories on that platform. |
|
136 | # directories on that platform. | |
134 | if os.name == 'posix': |
|
137 | if os.name == 'posix': | |
135 | rc_suffix = '' |
|
138 | rc_suffix = '' | |
136 | ipdir_def = '.ipython' |
|
139 | ipdir_def = '.ipython' | |
137 | else: |
|
140 | else: | |
138 | rc_suffix = '.ini' |
|
141 | rc_suffix = '.ini' | |
139 | ipdir_def = '_ipython' |
|
142 | ipdir_def = '_ipython' | |
140 |
|
143 | |||
141 | # default directory for configuration |
|
144 | # default directory for configuration | |
142 | ipythondir_def = os.path.abspath(os.environ.get('IPYTHONDIR', |
|
145 | ipythondir_def = os.path.abspath(os.environ.get('IPYTHONDIR', | |
143 | os.path.join(IP.home_dir,ipdir_def))) |
|
146 | os.path.join(IP.home_dir,ipdir_def))) | |
144 |
|
147 | |||
145 | sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran |
|
148 | sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran | |
146 |
|
149 | |||
147 | # we need the directory where IPython itself is installed |
|
150 | # we need the directory where IPython itself is installed | |
148 | import IPython |
|
151 | import IPython | |
149 | IPython_dir = os.path.dirname(IPython.__file__) |
|
152 | IPython_dir = os.path.dirname(IPython.__file__) | |
150 | del IPython |
|
153 | del IPython | |
151 |
|
154 | |||
152 | #------------------------------------------------------------------------- |
|
155 | #------------------------------------------------------------------------- | |
153 | # Command line handling |
|
156 | # Command line handling | |
154 |
|
157 | |||
155 | # Valid command line options (uses DPyGetOpt syntax, like Perl's |
|
158 | # Valid command line options (uses DPyGetOpt syntax, like Perl's | |
156 | # GetOpt::Long) |
|
159 | # GetOpt::Long) | |
157 |
|
160 | |||
158 | # Any key not listed here gets deleted even if in the file (like session |
|
161 | # Any key not listed here gets deleted even if in the file (like session | |
159 | # or profile). That's deliberate, to maintain the rc namespace clean. |
|
162 | # or profile). That's deliberate, to maintain the rc namespace clean. | |
160 |
|
163 | |||
161 | # Each set of options appears twice: under _conv only the names are |
|
164 | # Each set of options appears twice: under _conv only the names are | |
162 | # listed, indicating which type they must be converted to when reading the |
|
165 | # listed, indicating which type they must be converted to when reading the | |
163 | # ipythonrc file. And under DPyGetOpt they are listed with the regular |
|
166 | # ipythonrc file. And under DPyGetOpt they are listed with the regular | |
164 | # DPyGetOpt syntax (=s,=i,:f,etc). |
|
167 | # DPyGetOpt syntax (=s,=i,:f,etc). | |
165 |
|
168 | |||
166 | # Make sure there's a space before each end of line (they get auto-joined!) |
|
169 | # Make sure there's a space before each end of line (they get auto-joined!) | |
167 | cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i ' |
|
170 | cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i ' | |
168 | 'c=s classic|cl color_info! colors=s confirm_exit! ' |
|
171 | 'c=s classic|cl color_info! colors=s confirm_exit! ' | |
169 | 'debug! deep_reload! editor=s log|l messages! nosep ' |
|
172 | 'debug! deep_reload! editor=s log|l messages! nosep ' | |
170 | 'object_info_string_level=i pdb! ' |
|
173 | 'object_info_string_level=i pdb! ' | |
171 | 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s ' |
|
174 | 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s ' | |
172 | 'pydb! ' |
|
175 | 'pydb! ' | |
173 | 'pylab_import_all! ' |
|
176 | 'pylab_import_all! ' | |
174 | 'quick screen_length|sl=i prompts_pad_left=i ' |
|
177 | 'quick screen_length|sl=i prompts_pad_left=i ' | |
175 | 'logfile|lf=s logplay|lp=s profile|p=s ' |
|
178 | 'logfile|lf=s logplay|lp=s profile|p=s ' | |
176 | 'readline! readline_merge_completions! ' |
|
179 | 'readline! readline_merge_completions! ' | |
177 | 'readline_omit__names! ' |
|
180 | 'readline_omit__names! ' | |
178 | 'rcfile=s separate_in|si=s separate_out|so=s ' |
|
181 | 'rcfile=s separate_in|si=s separate_out|so=s ' | |
179 | 'separate_out2|so2=s xmode=s wildcards_case_sensitive! ' |
|
182 | 'separate_out2|so2=s xmode=s wildcards_case_sensitive! ' | |
180 | 'magic_docstrings system_verbose! ' |
|
183 | 'magic_docstrings system_verbose! ' | |
181 | 'multi_line_specials! ' |
|
184 | 'multi_line_specials! ' | |
182 | 'term_title! wxversion=s ' |
|
185 | 'term_title! wxversion=s ' | |
183 | 'autoedit_syntax!') |
|
186 | 'autoedit_syntax!') | |
184 |
|
187 | |||
185 | # Options that can *only* appear at the cmd line (not in rcfiles). |
|
188 | # Options that can *only* appear at the cmd line (not in rcfiles). | |
186 |
|
189 | |||
187 | cmdline_only = ('help interact|i ipythondir=s Version upgrade ' |
|
190 | cmdline_only = ('help interact|i ipythondir=s Version upgrade ' | |
188 | 'gthread! qthread! q4thread! wthread! tkthread! pylab! tk! ' |
|
191 | 'gthread! qthread! q4thread! wthread! tkthread! pylab! tk! ' | |
189 | 'twisted!') |
|
192 | 'twisted!') | |
190 |
|
193 | |||
191 | # Build the actual name list to be used by DPyGetOpt |
|
194 | # Build the actual name list to be used by DPyGetOpt | |
192 | opts_names = qw(cmdline_opts) + qw(cmdline_only) |
|
195 | opts_names = qw(cmdline_opts) + qw(cmdline_only) | |
193 |
|
196 | |||
194 | # Set sensible command line defaults. |
|
197 | # Set sensible command line defaults. | |
195 | # This should have everything from cmdline_opts and cmdline_only |
|
198 | # This should have everything from cmdline_opts and cmdline_only | |
196 | opts_def = Struct(autocall = 1, |
|
199 | opts_def = Struct(autocall = 1, | |
197 | autoedit_syntax = 0, |
|
200 | autoedit_syntax = 0, | |
198 | autoindent = 0, |
|
201 | autoindent = 0, | |
199 | automagic = 1, |
|
202 | automagic = 1, | |
200 | autoexec = [], |
|
203 | autoexec = [], | |
201 | banner = 1, |
|
204 | banner = 1, | |
202 | c = '', |
|
205 | c = '', | |
203 | cache_size = 1000, |
|
206 | cache_size = 1000, | |
204 | classic = 0, |
|
207 | classic = 0, | |
205 | color_info = 0, |
|
208 | color_info = 0, | |
206 | colors = 'NoColor', |
|
209 | colors = 'NoColor', | |
207 | confirm_exit = 1, |
|
210 | confirm_exit = 1, | |
208 | debug = 0, |
|
211 | debug = 0, | |
209 | deep_reload = 0, |
|
212 | deep_reload = 0, | |
210 | editor = '0', |
|
213 | editor = '0', | |
211 | gthread = 0, |
|
214 | gthread = 0, | |
212 | help = 0, |
|
215 | help = 0, | |
213 | interact = 0, |
|
216 | interact = 0, | |
214 | ipythondir = ipythondir_def, |
|
217 | ipythondir = ipythondir_def, | |
215 | log = 0, |
|
218 | log = 0, | |
216 | logfile = '', |
|
219 | logfile = '', | |
217 | logplay = '', |
|
220 | logplay = '', | |
218 | messages = 1, |
|
221 | messages = 1, | |
219 | multi_line_specials = 1, |
|
222 | multi_line_specials = 1, | |
220 | nosep = 0, |
|
223 | nosep = 0, | |
221 | object_info_string_level = 0, |
|
224 | object_info_string_level = 0, | |
222 | pdb = 0, |
|
225 | pdb = 0, | |
223 | pprint = 0, |
|
226 | pprint = 0, | |
224 | profile = '', |
|
227 | profile = '', | |
225 | prompt_in1 = 'In [\\#]: ', |
|
228 | prompt_in1 = 'In [\\#]: ', | |
226 | prompt_in2 = ' .\\D.: ', |
|
229 | prompt_in2 = ' .\\D.: ', | |
227 | prompt_out = 'Out[\\#]: ', |
|
230 | prompt_out = 'Out[\\#]: ', | |
228 | prompts_pad_left = 1, |
|
231 | prompts_pad_left = 1, | |
229 | pylab = 0, |
|
232 | pylab = 0, | |
230 | pylab_import_all = 1, |
|
233 | pylab_import_all = 1, | |
231 | q4thread = 0, |
|
234 | q4thread = 0, | |
232 | qthread = 0, |
|
235 | qthread = 0, | |
233 | quick = 0, |
|
236 | quick = 0, | |
234 | quiet = 0, |
|
237 | quiet = 0, | |
235 | rcfile = 'ipythonrc' + rc_suffix, |
|
238 | rcfile = 'ipythonrc' + rc_suffix, | |
236 | readline = 1, |
|
239 | readline = 1, | |
237 | readline_merge_completions = 1, |
|
240 | readline_merge_completions = 1, | |
238 | readline_omit__names = 0, |
|
241 | readline_omit__names = 0, | |
239 | screen_length = 0, |
|
242 | screen_length = 0, | |
240 | separate_in = '\n', |
|
243 | separate_in = '\n', | |
241 | separate_out = '\n', |
|
244 | separate_out = '\n', | |
242 | separate_out2 = '', |
|
245 | separate_out2 = '', | |
243 | system_header = 'IPython system call: ', |
|
246 | system_header = 'IPython system call: ', | |
244 | system_verbose = 0, |
|
247 | system_verbose = 0, | |
245 | term_title = 1, |
|
248 | term_title = 1, | |
246 | tk = 0, |
|
249 | tk = 0, | |
247 | twisted= 0, |
|
250 | twisted= 0, | |
248 | upgrade = 0, |
|
251 | upgrade = 0, | |
249 | Version = 0, |
|
252 | Version = 0, | |
250 | wildcards_case_sensitive = 1, |
|
253 | wildcards_case_sensitive = 1, | |
251 | wthread = 0, |
|
254 | wthread = 0, | |
252 | wxversion = '0', |
|
255 | wxversion = '0', | |
253 | xmode = 'Context', |
|
256 | xmode = 'Context', | |
254 | magic_docstrings = 0, # undocumented, for doc generation |
|
257 | magic_docstrings = 0, # undocumented, for doc generation | |
255 | ) |
|
258 | ) | |
256 |
|
259 | |||
257 | # Things that will *only* appear in rcfiles (not at the command line). |
|
260 | # Things that will *only* appear in rcfiles (not at the command line). | |
258 | # Make sure there's a space before each end of line (they get auto-joined!) |
|
261 | # Make sure there's a space before each end of line (they get auto-joined!) | |
259 | rcfile_opts = { qwflat: 'include import_mod import_all execfile ', |
|
262 | rcfile_opts = { qwflat: 'include import_mod import_all execfile ', | |
260 | qw_lol: 'import_some ', |
|
263 | qw_lol: 'import_some ', | |
261 | # for things with embedded whitespace: |
|
264 | # for things with embedded whitespace: | |
262 | list_strings:'execute alias readline_parse_and_bind ', |
|
265 | list_strings:'execute alias readline_parse_and_bind ', | |
263 | # Regular strings need no conversion: |
|
266 | # Regular strings need no conversion: | |
264 | None:'readline_remove_delims ', |
|
267 | None:'readline_remove_delims ', | |
265 | } |
|
268 | } | |
266 | # Default values for these |
|
269 | # Default values for these | |
267 | rc_def = Struct(include = [], |
|
270 | rc_def = Struct(include = [], | |
268 | import_mod = [], |
|
271 | import_mod = [], | |
269 | import_all = [], |
|
272 | import_all = [], | |
270 | import_some = [[]], |
|
273 | import_some = [[]], | |
271 | execute = [], |
|
274 | execute = [], | |
272 | execfile = [], |
|
275 | execfile = [], | |
273 | alias = [], |
|
276 | alias = [], | |
274 | readline_parse_and_bind = [], |
|
277 | readline_parse_and_bind = [], | |
275 | readline_remove_delims = '', |
|
278 | readline_remove_delims = '', | |
276 | ) |
|
279 | ) | |
277 |
|
280 | |||
278 | # Build the type conversion dictionary from the above tables: |
|
281 | # Build the type conversion dictionary from the above tables: | |
279 | typeconv = rcfile_opts.copy() |
|
282 | typeconv = rcfile_opts.copy() | |
280 | typeconv.update(optstr2types(cmdline_opts)) |
|
283 | typeconv.update(optstr2types(cmdline_opts)) | |
281 |
|
284 | |||
282 | # FIXME: the None key appears in both, put that back together by hand. Ugly! |
|
285 | # FIXME: the None key appears in both, put that back together by hand. Ugly! | |
283 | typeconv[None] += ' ' + rcfile_opts[None] |
|
286 | typeconv[None] += ' ' + rcfile_opts[None] | |
284 |
|
287 | |||
285 | # Remove quotes at ends of all strings (used to protect spaces) |
|
288 | # Remove quotes at ends of all strings (used to protect spaces) | |
286 | typeconv[unquote_ends] = typeconv[None] |
|
289 | typeconv[unquote_ends] = typeconv[None] | |
287 | del typeconv[None] |
|
290 | del typeconv[None] | |
288 |
|
291 | |||
289 | # Build the list we'll use to make all config decisions with defaults: |
|
292 | # Build the list we'll use to make all config decisions with defaults: | |
290 | opts_all = opts_def.copy() |
|
293 | opts_all = opts_def.copy() | |
291 | opts_all.update(rc_def) |
|
294 | opts_all.update(rc_def) | |
292 |
|
295 | |||
293 | # Build conflict resolver for recursive loading of config files: |
|
296 | # Build conflict resolver for recursive loading of config files: | |
294 | # - preserve means the outermost file maintains the value, it is not |
|
297 | # - preserve means the outermost file maintains the value, it is not | |
295 | # overwritten if an included file has the same key. |
|
298 | # overwritten if an included file has the same key. | |
296 | # - add_flip applies + to the two values, so it better make sense to add |
|
299 | # - add_flip applies + to the two values, so it better make sense to add | |
297 | # those types of keys. But it flips them first so that things loaded |
|
300 | # those types of keys. But it flips them first so that things loaded | |
298 | # deeper in the inclusion chain have lower precedence. |
|
301 | # deeper in the inclusion chain have lower precedence. | |
299 | conflict = {'preserve': ' '.join([ typeconv[int], |
|
302 | conflict = {'preserve': ' '.join([ typeconv[int], | |
300 | typeconv[unquote_ends] ]), |
|
303 | typeconv[unquote_ends] ]), | |
301 | 'add_flip': ' '.join([ typeconv[qwflat], |
|
304 | 'add_flip': ' '.join([ typeconv[qwflat], | |
302 | typeconv[qw_lol], |
|
305 | typeconv[qw_lol], | |
303 | typeconv[list_strings] ]) |
|
306 | typeconv[list_strings] ]) | |
304 | } |
|
307 | } | |
305 |
|
308 | |||
306 | # Now actually process the command line |
|
309 | # Now actually process the command line | |
307 | getopt = DPyGetOpt.DPyGetOpt() |
|
310 | getopt = DPyGetOpt.DPyGetOpt() | |
308 | getopt.setIgnoreCase(0) |
|
311 | getopt.setIgnoreCase(0) | |
309 |
|
312 | |||
310 | getopt.parseConfiguration(opts_names) |
|
313 | getopt.parseConfiguration(opts_names) | |
311 |
|
314 | |||
312 | try: |
|
315 | try: | |
313 | getopt.processArguments(argv) |
|
316 | getopt.processArguments(argv) | |
314 | except DPyGetOpt.ArgumentError, exc: |
|
317 | except DPyGetOpt.ArgumentError, exc: | |
315 | print cmd_line_usage |
|
318 | print cmd_line_usage | |
316 | warn('\nError in Arguments: "%s"' % exc) |
|
319 | warn('\nError in Arguments: "%s"' % exc) | |
317 | sys.exit(1) |
|
320 | sys.exit(1) | |
318 |
|
321 | |||
319 | # convert the options dict to a struct for much lighter syntax later |
|
322 | # convert the options dict to a struct for much lighter syntax later | |
320 | opts = Struct(getopt.optionValues) |
|
323 | opts = Struct(getopt.optionValues) | |
321 | args = getopt.freeValues |
|
324 | args = getopt.freeValues | |
322 |
|
325 | |||
323 | # this is the struct (which has default values at this point) with which |
|
326 | # this is the struct (which has default values at this point) with which | |
324 | # we make all decisions: |
|
327 | # we make all decisions: | |
325 | opts_all.update(opts) |
|
328 | opts_all.update(opts) | |
326 |
|
329 | |||
327 | # Options that force an immediate exit |
|
330 | # Options that force an immediate exit | |
328 | if opts_all.help: |
|
331 | if opts_all.help: | |
329 | page(cmd_line_usage) |
|
332 | page(cmd_line_usage) | |
330 | sys.exit() |
|
333 | sys.exit() | |
331 |
|
334 | |||
332 | if opts_all.Version: |
|
335 | if opts_all.Version: | |
333 | print __version__ |
|
336 | print __version__ | |
334 | sys.exit() |
|
337 | sys.exit() | |
335 |
|
338 | |||
336 | if opts_all.magic_docstrings: |
|
339 | if opts_all.magic_docstrings: | |
337 | IP.magic_magic('-latex') |
|
340 | IP.magic_magic('-latex') | |
338 | sys.exit() |
|
341 | sys.exit() | |
339 |
|
342 | |||
340 | # add personal ipythondir to sys.path so that users can put things in |
|
343 | # add personal ipythondir to sys.path so that users can put things in | |
341 | # there for customization |
|
344 | # there for customization | |
342 | sys.path.append(os.path.abspath(opts_all.ipythondir)) |
|
345 | sys.path.append(os.path.abspath(opts_all.ipythondir)) | |
343 |
|
346 | |||
344 | # Create user config directory if it doesn't exist. This must be done |
|
347 | # Create user config directory if it doesn't exist. This must be done | |
345 | # *after* getting the cmd line options. |
|
348 | # *after* getting the cmd line options. | |
346 | if not os.path.isdir(opts_all.ipythondir): |
|
349 | if not os.path.isdir(opts_all.ipythondir): | |
347 | IP.user_setup(opts_all.ipythondir,rc_suffix,'install') |
|
350 | IP.user_setup(opts_all.ipythondir,rc_suffix,'install') | |
348 |
|
351 | |||
349 | # upgrade user config files while preserving a copy of the originals |
|
352 | # upgrade user config files while preserving a copy of the originals | |
350 | if opts_all.upgrade: |
|
353 | if opts_all.upgrade: | |
351 | IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade') |
|
354 | IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade') | |
352 |
|
355 | |||
353 | # check mutually exclusive options in the *original* command line |
|
356 | # check mutually exclusive options in the *original* command line | |
354 | mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'), |
|
357 | mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'), | |
355 | qw('classic profile'),qw('classic rcfile')]) |
|
358 | qw('classic profile'),qw('classic rcfile')]) | |
356 |
|
359 | |||
357 | #--------------------------------------------------------------------------- |
|
360 | #--------------------------------------------------------------------------- | |
358 | # Log replay |
|
361 | # Log replay | |
359 |
|
362 | |||
360 | # if -logplay, we need to 'become' the other session. That basically means |
|
363 | # if -logplay, we need to 'become' the other session. That basically means | |
361 | # replacing the current command line environment with that of the old |
|
364 | # replacing the current command line environment with that of the old | |
362 | # session and moving on. |
|
365 | # session and moving on. | |
363 |
|
366 | |||
364 | # this is needed so that later we know we're in session reload mode, as |
|
367 | # this is needed so that later we know we're in session reload mode, as | |
365 | # opts_all will get overwritten: |
|
368 | # opts_all will get overwritten: | |
366 | load_logplay = 0 |
|
369 | load_logplay = 0 | |
367 |
|
370 | |||
368 | if opts_all.logplay: |
|
371 | if opts_all.logplay: | |
369 | load_logplay = opts_all.logplay |
|
372 | load_logplay = opts_all.logplay | |
370 | opts_debug_save = opts_all.debug |
|
373 | opts_debug_save = opts_all.debug | |
371 | try: |
|
374 | try: | |
372 | logplay = open(opts_all.logplay) |
|
375 | logplay = open(opts_all.logplay) | |
373 | except IOError: |
|
376 | except IOError: | |
374 | if opts_all.debug: IP.InteractiveTB() |
|
377 | if opts_all.debug: IP.InteractiveTB() | |
375 | warn('Could not open logplay file '+`opts_all.logplay`) |
|
378 | warn('Could not open logplay file '+`opts_all.logplay`) | |
376 | # restore state as if nothing had happened and move on, but make |
|
379 | # restore state as if nothing had happened and move on, but make | |
377 | # sure that later we don't try to actually load the session file |
|
380 | # sure that later we don't try to actually load the session file | |
378 | logplay = None |
|
381 | logplay = None | |
379 | load_logplay = 0 |
|
382 | load_logplay = 0 | |
380 | del opts_all.logplay |
|
383 | del opts_all.logplay | |
381 | else: |
|
384 | else: | |
382 | try: |
|
385 | try: | |
383 | logplay.readline() |
|
386 | logplay.readline() | |
384 | logplay.readline(); |
|
387 | logplay.readline(); | |
385 | # this reloads that session's command line |
|
388 | # this reloads that session's command line | |
386 | cmd = logplay.readline()[6:] |
|
389 | cmd = logplay.readline()[6:] | |
387 | exec cmd |
|
390 | exec cmd | |
388 | # restore the true debug flag given so that the process of |
|
391 | # restore the true debug flag given so that the process of | |
389 | # session loading itself can be monitored. |
|
392 | # session loading itself can be monitored. | |
390 | opts.debug = opts_debug_save |
|
393 | opts.debug = opts_debug_save | |
391 | # save the logplay flag so later we don't overwrite the log |
|
394 | # save the logplay flag so later we don't overwrite the log | |
392 | opts.logplay = load_logplay |
|
395 | opts.logplay = load_logplay | |
393 | # now we must update our own structure with defaults |
|
396 | # now we must update our own structure with defaults | |
394 | opts_all.update(opts) |
|
397 | opts_all.update(opts) | |
395 | # now load args |
|
398 | # now load args | |
396 | cmd = logplay.readline()[6:] |
|
399 | cmd = logplay.readline()[6:] | |
397 | exec cmd |
|
400 | exec cmd | |
398 | logplay.close() |
|
401 | logplay.close() | |
399 | except: |
|
402 | except: | |
400 | logplay.close() |
|
403 | logplay.close() | |
401 | if opts_all.debug: IP.InteractiveTB() |
|
404 | if opts_all.debug: IP.InteractiveTB() | |
402 | warn("Logplay file lacking full configuration information.\n" |
|
405 | warn("Logplay file lacking full configuration information.\n" | |
403 | "I'll try to read it, but some things may not work.") |
|
406 | "I'll try to read it, but some things may not work.") | |
404 |
|
407 | |||
405 | #------------------------------------------------------------------------- |
|
408 | #------------------------------------------------------------------------- | |
406 | # set up output traps: catch all output from files, being run, modules |
|
409 | # set up output traps: catch all output from files, being run, modules | |
407 | # loaded, etc. Then give it to the user in a clean form at the end. |
|
410 | # loaded, etc. Then give it to the user in a clean form at the end. | |
408 |
|
411 | |||
409 | msg_out = 'Output messages. ' |
|
412 | msg_out = 'Output messages. ' | |
410 | msg_err = 'Error messages. ' |
|
413 | msg_err = 'Error messages. ' | |
411 | msg_sep = '\n' |
|
414 | msg_sep = '\n' | |
412 | msg = Struct(config = OutputTrap('Configuration Loader',msg_out, |
|
415 | msg = Struct(config = OutputTrap('Configuration Loader',msg_out, | |
413 | msg_err,msg_sep,debug, |
|
416 | msg_err,msg_sep,debug, | |
414 | quiet_out=1), |
|
417 | quiet_out=1), | |
415 | user_exec = OutputTrap('User File Execution',msg_out, |
|
418 | user_exec = OutputTrap('User File Execution',msg_out, | |
416 | msg_err,msg_sep,debug), |
|
419 | msg_err,msg_sep,debug), | |
417 | logplay = OutputTrap('Log Loader',msg_out, |
|
420 | logplay = OutputTrap('Log Loader',msg_out, | |
418 | msg_err,msg_sep,debug), |
|
421 | msg_err,msg_sep,debug), | |
419 | summary = '' |
|
422 | summary = '' | |
420 | ) |
|
423 | ) | |
421 |
|
424 | |||
422 | #------------------------------------------------------------------------- |
|
425 | #------------------------------------------------------------------------- | |
423 | # Process user ipythonrc-type configuration files |
|
426 | # Process user ipythonrc-type configuration files | |
424 |
|
427 | |||
425 | # turn on output trapping and log to msg.config |
|
428 | # turn on output trapping and log to msg.config | |
426 | # remember that with debug on, trapping is actually disabled |
|
429 | # remember that with debug on, trapping is actually disabled | |
427 | msg.config.trap_all() |
|
430 | msg.config.trap_all() | |
428 |
|
431 | |||
429 | # look for rcfile in current or default directory |
|
432 | # look for rcfile in current or default directory | |
430 | try: |
|
433 | try: | |
431 | opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir) |
|
434 | opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir) | |
432 | except IOError: |
|
435 | except IOError: | |
433 | if opts_all.debug: IP.InteractiveTB() |
|
436 | if opts_all.debug: IP.InteractiveTB() | |
434 | warn('Configuration file %s not found. Ignoring request.' |
|
437 | warn('Configuration file %s not found. Ignoring request.' | |
435 | % (opts_all.rcfile) ) |
|
438 | % (opts_all.rcfile) ) | |
436 |
|
439 | |||
437 | # 'profiles' are a shorthand notation for config filenames |
|
440 | # 'profiles' are a shorthand notation for config filenames | |
438 | profile_handled_by_legacy = False |
|
441 | profile_handled_by_legacy = False | |
439 | if opts_all.profile: |
|
442 | if opts_all.profile: | |
440 |
|
443 | |||
441 | try: |
|
444 | try: | |
442 | opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile |
|
445 | opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile | |
443 | + rc_suffix, |
|
446 | + rc_suffix, | |
444 | opts_all.ipythondir) |
|
447 | opts_all.ipythondir) | |
445 | profile_handled_by_legacy = True |
|
448 | profile_handled_by_legacy = True | |
446 | except IOError: |
|
449 | except IOError: | |
447 | if opts_all.debug: IP.InteractiveTB() |
|
450 | if opts_all.debug: IP.InteractiveTB() | |
448 | opts.profile = '' # remove profile from options if invalid |
|
451 | opts.profile = '' # remove profile from options if invalid | |
449 | # We won't warn anymore, primary method is ipy_profile_PROFNAME |
|
452 | # We won't warn anymore, primary method is ipy_profile_PROFNAME | |
450 | # which does trigger a warning. |
|
453 | # which does trigger a warning. | |
451 |
|
454 | |||
452 | # load the config file |
|
455 | # load the config file | |
453 | rcfiledata = None |
|
456 | rcfiledata = None | |
454 | if opts_all.quick: |
|
457 | if opts_all.quick: | |
455 | print 'Launching IPython in quick mode. No config file read.' |
|
458 | print 'Launching IPython in quick mode. No config file read.' | |
456 | elif opts_all.rcfile: |
|
459 | elif opts_all.rcfile: | |
457 | try: |
|
460 | try: | |
458 | cfg_loader = ConfigLoader(conflict) |
|
461 | cfg_loader = ConfigLoader(conflict) | |
459 | rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv, |
|
462 | rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv, | |
460 | 'include',opts_all.ipythondir, |
|
463 | 'include',opts_all.ipythondir, | |
461 | purge = 1, |
|
464 | purge = 1, | |
462 | unique = conflict['preserve']) |
|
465 | unique = conflict['preserve']) | |
463 | except: |
|
466 | except: | |
464 | IP.InteractiveTB() |
|
467 | IP.InteractiveTB() | |
465 | warn('Problems loading configuration file '+ |
|
468 | warn('Problems loading configuration file '+ | |
466 | `opts_all.rcfile`+ |
|
469 | `opts_all.rcfile`+ | |
467 | '\nStarting with default -bare bones- configuration.') |
|
470 | '\nStarting with default -bare bones- configuration.') | |
468 | else: |
|
471 | else: | |
469 | warn('No valid configuration file found in either currrent directory\n'+ |
|
472 | warn('No valid configuration file found in either currrent directory\n'+ | |
470 | 'or in the IPython config. directory: '+`opts_all.ipythondir`+ |
|
473 | 'or in the IPython config. directory: '+`opts_all.ipythondir`+ | |
471 | '\nProceeding with internal defaults.') |
|
474 | '\nProceeding with internal defaults.') | |
472 |
|
475 | |||
473 | #------------------------------------------------------------------------ |
|
476 | #------------------------------------------------------------------------ | |
474 | # Set exception handlers in mode requested by user. |
|
477 | # Set exception handlers in mode requested by user. | |
475 | otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode |
|
478 | otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode | |
476 | IP.magic_xmode(opts_all.xmode) |
|
479 | IP.magic_xmode(opts_all.xmode) | |
477 | otrap.release_out() |
|
480 | otrap.release_out() | |
478 |
|
481 | |||
479 | #------------------------------------------------------------------------ |
|
482 | #------------------------------------------------------------------------ | |
480 | # Execute user config |
|
483 | # Execute user config | |
481 |
|
484 | |||
482 | # Create a valid config structure with the right precedence order: |
|
485 | # Create a valid config structure with the right precedence order: | |
483 | # defaults < rcfile < command line. This needs to be in the instance, so |
|
486 | # defaults < rcfile < command line. This needs to be in the instance, so | |
484 | # that method calls below that rely on it find it. |
|
487 | # that method calls below that rely on it find it. | |
485 | IP.rc = rc_def.copy() |
|
488 | IP.rc = rc_def.copy() | |
486 |
|
489 | |||
487 | # Work with a local alias inside this routine to avoid unnecessary |
|
490 | # Work with a local alias inside this routine to avoid unnecessary | |
488 | # attribute lookups. |
|
491 | # attribute lookups. | |
489 | IP_rc = IP.rc |
|
492 | IP_rc = IP.rc | |
490 |
|
493 | |||
491 | IP_rc.update(opts_def) |
|
494 | IP_rc.update(opts_def) | |
492 | if rcfiledata: |
|
495 | if rcfiledata: | |
493 | # now we can update |
|
496 | # now we can update | |
494 | IP_rc.update(rcfiledata) |
|
497 | IP_rc.update(rcfiledata) | |
495 | IP_rc.update(opts) |
|
498 | IP_rc.update(opts) | |
496 | IP_rc.update(rc_override) |
|
499 | IP_rc.update(rc_override) | |
497 |
|
500 | |||
498 | # Store the original cmd line for reference: |
|
501 | # Store the original cmd line for reference: | |
499 | IP_rc.opts = opts |
|
502 | IP_rc.opts = opts | |
500 | IP_rc.args = args |
|
503 | IP_rc.args = args | |
501 |
|
504 | |||
502 | # create a *runtime* Struct like rc for holding parameters which may be |
|
505 | # create a *runtime* Struct like rc for holding parameters which may be | |
503 | # created and/or modified by runtime user extensions. |
|
506 | # created and/or modified by runtime user extensions. | |
504 | IP.runtime_rc = Struct() |
|
507 | IP.runtime_rc = Struct() | |
505 |
|
508 | |||
506 | # from this point on, all config should be handled through IP_rc, |
|
509 | # from this point on, all config should be handled through IP_rc, | |
507 | # opts* shouldn't be used anymore. |
|
510 | # opts* shouldn't be used anymore. | |
508 |
|
511 | |||
509 |
|
512 | |||
510 | # update IP_rc with some special things that need manual |
|
513 | # update IP_rc with some special things that need manual | |
511 | # tweaks. Basically options which affect other options. I guess this |
|
514 | # tweaks. Basically options which affect other options. I guess this | |
512 | # should just be written so that options are fully orthogonal and we |
|
515 | # should just be written so that options are fully orthogonal and we | |
513 | # wouldn't worry about this stuff! |
|
516 | # wouldn't worry about this stuff! | |
514 |
|
517 | |||
515 | if IP_rc.classic: |
|
518 | if IP_rc.classic: | |
516 | IP_rc.quick = 1 |
|
519 | IP_rc.quick = 1 | |
517 | IP_rc.cache_size = 0 |
|
520 | IP_rc.cache_size = 0 | |
518 | IP_rc.pprint = 0 |
|
521 | IP_rc.pprint = 0 | |
519 | IP_rc.prompt_in1 = '>>> ' |
|
522 | IP_rc.prompt_in1 = '>>> ' | |
520 | IP_rc.prompt_in2 = '... ' |
|
523 | IP_rc.prompt_in2 = '... ' | |
521 | IP_rc.prompt_out = '' |
|
524 | IP_rc.prompt_out = '' | |
522 | IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0' |
|
525 | IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0' | |
523 | IP_rc.colors = 'NoColor' |
|
526 | IP_rc.colors = 'NoColor' | |
524 | IP_rc.xmode = 'Plain' |
|
527 | IP_rc.xmode = 'Plain' | |
525 |
|
528 | |||
526 | IP.pre_config_initialization() |
|
529 | IP.pre_config_initialization() | |
527 | # configure readline |
|
530 | # configure readline | |
528 | # Define the history file for saving commands in between sessions |
|
531 | # Define the history file for saving commands in between sessions | |
529 | if IP_rc.profile: |
|
532 | if IP_rc.profile: | |
530 | histfname = 'history-%s' % IP_rc.profile |
|
533 | histfname = 'history-%s' % IP_rc.profile | |
531 | else: |
|
534 | else: | |
532 | histfname = 'history' |
|
535 | histfname = 'history' | |
533 | IP.histfile = os.path.join(opts_all.ipythondir,histfname) |
|
536 | IP.histfile = os.path.join(opts_all.ipythondir,histfname) | |
534 |
|
537 | |||
535 | # update exception handlers with rc file status |
|
538 | # update exception handlers with rc file status | |
536 | otrap.trap_out() # I don't want these messages ever. |
|
539 | otrap.trap_out() # I don't want these messages ever. | |
537 | IP.magic_xmode(IP_rc.xmode) |
|
540 | IP.magic_xmode(IP_rc.xmode) | |
538 | otrap.release_out() |
|
541 | otrap.release_out() | |
539 |
|
542 | |||
540 | # activate logging if requested and not reloading a log |
|
543 | # activate logging if requested and not reloading a log | |
541 | if IP_rc.logplay: |
|
544 | if IP_rc.logplay: | |
542 | IP.magic_logstart(IP_rc.logplay + ' append') |
|
545 | IP.magic_logstart(IP_rc.logplay + ' append') | |
543 | elif IP_rc.logfile: |
|
546 | elif IP_rc.logfile: | |
544 | IP.magic_logstart(IP_rc.logfile) |
|
547 | IP.magic_logstart(IP_rc.logfile) | |
545 | elif IP_rc.log: |
|
548 | elif IP_rc.log: | |
546 | IP.magic_logstart() |
|
549 | IP.magic_logstart() | |
547 |
|
550 | |||
548 | # find user editor so that it we don't have to look it up constantly |
|
551 | # find user editor so that it we don't have to look it up constantly | |
549 | if IP_rc.editor.strip()=='0': |
|
552 | if IP_rc.editor.strip()=='0': | |
550 | try: |
|
553 | try: | |
551 | ed = os.environ['EDITOR'] |
|
554 | ed = os.environ['EDITOR'] | |
552 | except KeyError: |
|
555 | except KeyError: | |
553 | if os.name == 'posix': |
|
556 | if os.name == 'posix': | |
554 | ed = 'vi' # the only one guaranteed to be there! |
|
557 | ed = 'vi' # the only one guaranteed to be there! | |
555 | else: |
|
558 | else: | |
556 | ed = 'notepad' # same in Windows! |
|
559 | ed = 'notepad' # same in Windows! | |
557 | IP_rc.editor = ed |
|
560 | IP_rc.editor = ed | |
558 |
|
561 | |||
559 | # Keep track of whether this is an embedded instance or not (useful for |
|
562 | # Keep track of whether this is an embedded instance or not (useful for | |
560 | # post-mortems). |
|
563 | # post-mortems). | |
561 | IP_rc.embedded = IP.embedded |
|
564 | IP_rc.embedded = IP.embedded | |
562 |
|
565 | |||
563 | # Recursive reload |
|
566 | # Recursive reload | |
564 | try: |
|
567 | try: | |
565 | from IPython import deep_reload |
|
568 | from IPython import deep_reload | |
566 | if IP_rc.deep_reload: |
|
569 | if IP_rc.deep_reload: | |
567 | __builtin__.reload = deep_reload.reload |
|
570 | __builtin__.reload = deep_reload.reload | |
568 | else: |
|
571 | else: | |
569 | __builtin__.dreload = deep_reload.reload |
|
572 | __builtin__.dreload = deep_reload.reload | |
570 | del deep_reload |
|
573 | del deep_reload | |
571 | except ImportError: |
|
574 | except ImportError: | |
572 | pass |
|
575 | pass | |
573 |
|
576 | |||
574 | # Save the current state of our namespace so that the interactive shell |
|
577 | # Save the current state of our namespace so that the interactive shell | |
575 | # can later know which variables have been created by us from config files |
|
578 | # can later know which variables have been created by us from config files | |
576 | # and loading. This way, loading a file (in any way) is treated just like |
|
579 | # and loading. This way, loading a file (in any way) is treated just like | |
577 | # defining things on the command line, and %who works as expected. |
|
580 | # defining things on the command line, and %who works as expected. | |
578 |
|
581 | |||
579 | # DON'T do anything that affects the namespace beyond this point! |
|
582 | # DON'T do anything that affects the namespace beyond this point! | |
580 | IP.internal_ns.update(__main__.__dict__) |
|
583 | IP.internal_ns.update(__main__.__dict__) | |
581 |
|
584 | |||
582 | #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who |
|
585 | #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who | |
583 |
|
586 | |||
584 | # Now run through the different sections of the users's config |
|
587 | # Now run through the different sections of the users's config | |
585 | if IP_rc.debug: |
|
588 | if IP_rc.debug: | |
586 | print 'Trying to execute the following configuration structure:' |
|
589 | print 'Trying to execute the following configuration structure:' | |
587 | print '(Things listed first are deeper in the inclusion tree and get' |
|
590 | print '(Things listed first are deeper in the inclusion tree and get' | |
588 | print 'loaded first).\n' |
|
591 | print 'loaded first).\n' | |
589 | pprint(IP_rc.__dict__) |
|
592 | pprint(IP_rc.__dict__) | |
590 |
|
593 | |||
591 | for mod in IP_rc.import_mod: |
|
594 | for mod in IP_rc.import_mod: | |
592 | try: |
|
595 | try: | |
593 | exec 'import '+mod in IP.user_ns |
|
596 | exec 'import '+mod in IP.user_ns | |
594 | except : |
|
597 | except : | |
595 | IP.InteractiveTB() |
|
598 | IP.InteractiveTB() | |
596 | import_fail_info(mod) |
|
599 | import_fail_info(mod) | |
597 |
|
600 | |||
598 | for mod_fn in IP_rc.import_some: |
|
601 | for mod_fn in IP_rc.import_some: | |
599 | if not mod_fn == []: |
|
602 | if not mod_fn == []: | |
600 | mod,fn = mod_fn[0],','.join(mod_fn[1:]) |
|
603 | mod,fn = mod_fn[0],','.join(mod_fn[1:]) | |
601 | try: |
|
604 | try: | |
602 | exec 'from '+mod+' import '+fn in IP.user_ns |
|
605 | exec 'from '+mod+' import '+fn in IP.user_ns | |
603 | except : |
|
606 | except : | |
604 | IP.InteractiveTB() |
|
607 | IP.InteractiveTB() | |
605 | import_fail_info(mod,fn) |
|
608 | import_fail_info(mod,fn) | |
606 |
|
609 | |||
607 | for mod in IP_rc.import_all: |
|
610 | for mod in IP_rc.import_all: | |
608 | try: |
|
611 | try: | |
609 | exec 'from '+mod+' import *' in IP.user_ns |
|
612 | exec 'from '+mod+' import *' in IP.user_ns | |
610 | except : |
|
613 | except : | |
611 | IP.InteractiveTB() |
|
614 | IP.InteractiveTB() | |
612 | import_fail_info(mod) |
|
615 | import_fail_info(mod) | |
613 |
|
616 | |||
614 | for code in IP_rc.execute: |
|
617 | for code in IP_rc.execute: | |
615 | try: |
|
618 | try: | |
616 | exec code in IP.user_ns |
|
619 | exec code in IP.user_ns | |
617 | except: |
|
620 | except: | |
618 | IP.InteractiveTB() |
|
621 | IP.InteractiveTB() | |
619 | warn('Failure executing code: ' + `code`) |
|
622 | warn('Failure executing code: ' + `code`) | |
620 |
|
623 | |||
621 | # Execute the files the user wants in ipythonrc |
|
624 | # Execute the files the user wants in ipythonrc | |
622 | for file in IP_rc.execfile: |
|
625 | for file in IP_rc.execfile: | |
623 | try: |
|
626 | try: | |
624 | file = filefind(file,sys.path+[IPython_dir]) |
|
627 | file = filefind(file,sys.path+[IPython_dir]) | |
625 | except IOError: |
|
628 | except IOError: | |
626 | warn(itpl('File $file not found. Skipping it.')) |
|
629 | warn(itpl('File $file not found. Skipping it.')) | |
627 | else: |
|
630 | else: | |
628 | IP.safe_execfile(os.path.expanduser(file),IP.user_ns) |
|
631 | IP.safe_execfile(os.path.expanduser(file),IP.user_ns) | |
629 |
|
632 | |||
630 | # finally, try importing ipy_*_conf for final configuration |
|
633 | # finally, try importing ipy_*_conf for final configuration | |
631 | try: |
|
634 | try: | |
632 | import ipy_system_conf |
|
635 | import ipy_system_conf | |
633 | except ImportError: |
|
636 | except ImportError: | |
634 | if opts_all.debug: IP.InteractiveTB() |
|
637 | if opts_all.debug: IP.InteractiveTB() | |
635 | warn("Could not import 'ipy_system_conf'") |
|
638 | warn("Could not import 'ipy_system_conf'") | |
636 | except: |
|
639 | except: | |
637 | IP.InteractiveTB() |
|
640 | IP.InteractiveTB() | |
638 | import_fail_info('ipy_system_conf') |
|
641 | import_fail_info('ipy_system_conf') | |
639 |
|
642 | |||
640 | # only import prof module if ipythonrc-PROF was not found |
|
643 | # only import prof module if ipythonrc-PROF was not found | |
641 | if opts_all.profile and not profile_handled_by_legacy: |
|
644 | if opts_all.profile and not profile_handled_by_legacy: | |
642 | profmodname = 'ipy_profile_' + opts_all.profile |
|
645 | profmodname = 'ipy_profile_' + opts_all.profile | |
643 | try: |
|
646 | try: | |
644 |
|
647 | |||
645 | force_import(profmodname) |
|
648 | force_import(profmodname) | |
646 | except: |
|
649 | except: | |
647 | IP.InteractiveTB() |
|
650 | IP.InteractiveTB() | |
648 | print "Error importing",profmodname,"- perhaps you should run %upgrade?" |
|
651 | print "Error importing",profmodname,"- perhaps you should run %upgrade?" | |
649 | import_fail_info(profmodname) |
|
652 | import_fail_info(profmodname) | |
650 | else: |
|
653 | else: | |
651 | force_import('ipy_profile_none') |
|
654 | force_import('ipy_profile_none') | |
652 | try: |
|
655 | try: | |
653 |
|
656 | |||
654 | force_import('ipy_user_conf') |
|
657 | force_import('ipy_user_conf') | |
655 |
|
658 | |||
656 | except: |
|
659 | except: | |
657 | conf = opts_all.ipythondir + "/ipy_user_conf.py" |
|
660 | conf = opts_all.ipythondir + "/ipy_user_conf.py" | |
658 | IP.InteractiveTB() |
|
661 | IP.InteractiveTB() | |
659 | if not os.path.isfile(conf): |
|
662 | if not os.path.isfile(conf): | |
660 | warn(conf + ' does not exist, please run %upgrade!') |
|
663 | warn(conf + ' does not exist, please run %upgrade!') | |
661 |
|
664 | |||
662 | import_fail_info("ipy_user_conf") |
|
665 | import_fail_info("ipy_user_conf") | |
663 |
|
666 | |||
664 | # finally, push the argv to options again to ensure highest priority |
|
667 | # finally, push the argv to options again to ensure highest priority | |
665 | IP_rc.update(opts) |
|
668 | IP_rc.update(opts) | |
666 |
|
669 | |||
667 | # release stdout and stderr and save config log into a global summary |
|
670 | # release stdout and stderr and save config log into a global summary | |
668 | msg.config.release_all() |
|
671 | msg.config.release_all() | |
669 | if IP_rc.messages: |
|
672 | if IP_rc.messages: | |
670 | msg.summary += msg.config.summary_all() |
|
673 | msg.summary += msg.config.summary_all() | |
671 |
|
674 | |||
672 | #------------------------------------------------------------------------ |
|
675 | #------------------------------------------------------------------------ | |
673 | # Setup interactive session |
|
676 | # Setup interactive session | |
674 |
|
677 | |||
675 | # Now we should be fully configured. We can then execute files or load |
|
678 | # Now we should be fully configured. We can then execute files or load | |
676 | # things only needed for interactive use. Then we'll open the shell. |
|
679 | # things only needed for interactive use. Then we'll open the shell. | |
677 |
|
680 | |||
678 | # Take a snapshot of the user namespace before opening the shell. That way |
|
681 | # Take a snapshot of the user namespace before opening the shell. That way | |
679 | # we'll be able to identify which things were interactively defined and |
|
682 | # we'll be able to identify which things were interactively defined and | |
680 | # which were defined through config files. |
|
683 | # which were defined through config files. | |
681 | IP.user_config_ns.update(IP.user_ns) |
|
684 | IP.user_config_ns.update(IP.user_ns) | |
682 |
|
685 | |||
683 | # Force reading a file as if it were a session log. Slower but safer. |
|
686 | # Force reading a file as if it were a session log. Slower but safer. | |
684 | if load_logplay: |
|
687 | if load_logplay: | |
685 | print 'Replaying log...' |
|
688 | print 'Replaying log...' | |
686 | try: |
|
689 | try: | |
687 | if IP_rc.debug: |
|
690 | if IP_rc.debug: | |
688 | logplay_quiet = 0 |
|
691 | logplay_quiet = 0 | |
689 | else: |
|
692 | else: | |
690 | logplay_quiet = 1 |
|
693 | logplay_quiet = 1 | |
691 |
|
694 | |||
692 | msg.logplay.trap_all() |
|
695 | msg.logplay.trap_all() | |
693 | IP.safe_execfile(load_logplay,IP.user_ns, |
|
696 | IP.safe_execfile(load_logplay,IP.user_ns, | |
694 | islog = 1, quiet = logplay_quiet) |
|
697 | islog = 1, quiet = logplay_quiet) | |
695 | msg.logplay.release_all() |
|
698 | msg.logplay.release_all() | |
696 | if IP_rc.messages: |
|
699 | if IP_rc.messages: | |
697 | msg.summary += msg.logplay.summary_all() |
|
700 | msg.summary += msg.logplay.summary_all() | |
698 | except: |
|
701 | except: | |
699 | warn('Problems replaying logfile %s.' % load_logplay) |
|
702 | warn('Problems replaying logfile %s.' % load_logplay) | |
700 | IP.InteractiveTB() |
|
703 | IP.InteractiveTB() | |
701 |
|
704 | |||
702 | # Load remaining files in command line |
|
705 | # Load remaining files in command line | |
703 | msg.user_exec.trap_all() |
|
706 | msg.user_exec.trap_all() | |
704 |
|
707 | |||
705 | # Do NOT execute files named in the command line as scripts to be loaded |
|
708 | # Do NOT execute files named in the command line as scripts to be loaded | |
706 | # by embedded instances. Doing so has the potential for an infinite |
|
709 | # by embedded instances. Doing so has the potential for an infinite | |
707 | # recursion if there are exceptions thrown in the process. |
|
710 | # recursion if there are exceptions thrown in the process. | |
708 |
|
711 | |||
709 | # XXX FIXME: the execution of user files should be moved out to after |
|
712 | # XXX FIXME: the execution of user files should be moved out to after | |
710 | # ipython is fully initialized, just as if they were run via %run at the |
|
713 | # ipython is fully initialized, just as if they were run via %run at the | |
711 | # ipython prompt. This would also give them the benefit of ipython's |
|
714 | # ipython prompt. This would also give them the benefit of ipython's | |
712 | # nice tracebacks. |
|
715 | # nice tracebacks. | |
713 |
|
716 | |||
714 | if (not embedded and IP_rc.args and |
|
717 | if (not embedded and IP_rc.args and | |
715 | not IP_rc.args[0].lower().endswith('.ipy')): |
|
718 | not IP_rc.args[0].lower().endswith('.ipy')): | |
716 | name_save = IP.user_ns['__name__'] |
|
719 | name_save = IP.user_ns['__name__'] | |
717 | IP.user_ns['__name__'] = '__main__' |
|
720 | IP.user_ns['__name__'] = '__main__' | |
718 | # Set our own excepthook in case the user code tries to call it |
|
721 | # Set our own excepthook in case the user code tries to call it | |
719 | # directly. This prevents triggering the IPython crash handler. |
|
722 | # directly. This prevents triggering the IPython crash handler. | |
720 | old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook |
|
723 | old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook | |
721 |
|
724 | |||
722 | save_argv = sys.argv[1:] # save it for later restoring |
|
725 | save_argv = sys.argv[1:] # save it for later restoring | |
723 |
|
726 | |||
724 | sys.argv = args |
|
727 | sys.argv = args | |
725 |
|
728 | |||
726 | try: |
|
729 | try: | |
727 | IP.safe_execfile(args[0], IP.user_ns) |
|
730 | IP.safe_execfile(args[0], IP.user_ns) | |
728 | finally: |
|
731 | finally: | |
729 | # Reset our crash handler in place |
|
732 | # Reset our crash handler in place | |
730 | sys.excepthook = old_excepthook |
|
733 | sys.excepthook = old_excepthook | |
731 | sys.argv[:] = save_argv |
|
734 | sys.argv[:] = save_argv | |
732 | IP.user_ns['__name__'] = name_save |
|
735 | IP.user_ns['__name__'] = name_save | |
733 |
|
736 | |||
734 | msg.user_exec.release_all() |
|
737 | msg.user_exec.release_all() | |
735 |
|
738 | |||
736 | if IP_rc.messages: |
|
739 | if IP_rc.messages: | |
737 | msg.summary += msg.user_exec.summary_all() |
|
740 | msg.summary += msg.user_exec.summary_all() | |
738 |
|
741 | |||
739 | # since we can't specify a null string on the cmd line, 0 is the equivalent: |
|
742 | # since we can't specify a null string on the cmd line, 0 is the equivalent: | |
740 | if IP_rc.nosep: |
|
743 | if IP_rc.nosep: | |
741 | IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0' |
|
744 | IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0' | |
742 | if IP_rc.separate_in == '0': IP_rc.separate_in = '' |
|
745 | if IP_rc.separate_in == '0': IP_rc.separate_in = '' | |
743 | if IP_rc.separate_out == '0': IP_rc.separate_out = '' |
|
746 | if IP_rc.separate_out == '0': IP_rc.separate_out = '' | |
744 | if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = '' |
|
747 | if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = '' | |
745 | IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n') |
|
748 | IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n') | |
746 | IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n') |
|
749 | IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n') | |
747 | IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n') |
|
750 | IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n') | |
748 |
|
751 | |||
749 | # Determine how many lines at the bottom of the screen are needed for |
|
752 | # Determine how many lines at the bottom of the screen are needed for | |
750 | # showing prompts, so we can know wheter long strings are to be printed or |
|
753 | # showing prompts, so we can know wheter long strings are to be printed or | |
751 | # paged: |
|
754 | # paged: | |
752 | num_lines_bot = IP_rc.separate_in.count('\n')+1 |
|
755 | num_lines_bot = IP_rc.separate_in.count('\n')+1 | |
753 | IP_rc.screen_length = IP_rc.screen_length - num_lines_bot |
|
756 | IP_rc.screen_length = IP_rc.screen_length - num_lines_bot | |
754 |
|
757 | |||
755 | # configure startup banner |
|
758 | # configure startup banner | |
756 | if IP_rc.c: # regular python doesn't print the banner with -c |
|
759 | if IP_rc.c: # regular python doesn't print the banner with -c | |
757 | IP_rc.banner = 0 |
|
760 | IP_rc.banner = 0 | |
758 | if IP_rc.banner: |
|
761 | if IP_rc.banner: | |
759 | BANN_P = IP.BANNER_PARTS |
|
762 | BANN_P = IP.BANNER_PARTS | |
760 | else: |
|
763 | else: | |
761 | BANN_P = [] |
|
764 | BANN_P = [] | |
762 |
|
765 | |||
763 | if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile) |
|
766 | if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile) | |
764 |
|
767 | |||
765 | # add message log (possibly empty) |
|
768 | # add message log (possibly empty) | |
766 | if msg.summary: BANN_P.append(msg.summary) |
|
769 | if msg.summary: BANN_P.append(msg.summary) | |
767 | # Final banner is a string |
|
770 | # Final banner is a string | |
768 | IP.BANNER = '\n'.join(BANN_P) |
|
771 | IP.BANNER = '\n'.join(BANN_P) | |
769 |
|
772 | |||
770 | # Finalize the IPython instance. This assumes the rc structure is fully |
|
773 | # Finalize the IPython instance. This assumes the rc structure is fully | |
771 | # in place. |
|
774 | # in place. | |
772 | IP.post_config_initialization() |
|
775 | IP.post_config_initialization() | |
773 |
|
776 | |||
774 | return IP |
|
777 | return IP | |
775 | #************************ end of file <ipmaker.py> ************************** |
|
778 | #************************ end of file <ipmaker.py> ************************** |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: file was removed |
|
NO CONTENT: file was removed | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: file was removed |
|
NO CONTENT: file was removed | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: file was removed |
|
NO CONTENT: file was removed | ||
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