Show More
@@ -1,305 +1,311 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """A simple configuration system. |
|
3 | """A simple configuration system. | |
4 |
|
4 | |||
5 | Authors: |
|
5 | Authors: | |
6 |
|
6 | |||
7 | * Brian Granger |
|
7 | * Brian Granger | |
8 | """ |
|
8 | """ | |
9 |
|
9 | |||
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 | # Copyright (C) 2008-2009 The IPython Development Team |
|
11 | # Copyright (C) 2008-2009 The IPython Development Team | |
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 | #----------------------------------------------------------------------------- |
|
17 | #----------------------------------------------------------------------------- | |
18 | # Imports |
|
18 | # Imports | |
19 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
20 |
|
20 | |||
21 | import __builtin__ |
|
21 | import __builtin__ | |
22 | import os |
|
22 | import os | |
23 | import sys |
|
23 | import sys | |
24 |
|
24 | |||
25 | from IPython.external import argparse |
|
25 | from IPython.external import argparse | |
26 | from IPython.utils.genutils import filefind |
|
26 | from IPython.utils.genutils import filefind | |
27 |
|
27 | |||
28 | #----------------------------------------------------------------------------- |
|
28 | #----------------------------------------------------------------------------- | |
29 | # Exceptions |
|
29 | # Exceptions | |
30 | #----------------------------------------------------------------------------- |
|
30 | #----------------------------------------------------------------------------- | |
31 |
|
31 | |||
32 |
|
32 | |||
33 | class ConfigError(Exception): |
|
33 | class ConfigError(Exception): | |
34 | pass |
|
34 | pass | |
35 |
|
35 | |||
36 |
|
36 | |||
37 | class ConfigLoaderError(ConfigError): |
|
37 | class ConfigLoaderError(ConfigError): | |
38 | pass |
|
38 | pass | |
39 |
|
39 | |||
40 |
|
40 | |||
41 | #----------------------------------------------------------------------------- |
|
41 | #----------------------------------------------------------------------------- | |
42 | # Config class for holding config information |
|
42 | # Config class for holding config information | |
43 | #----------------------------------------------------------------------------- |
|
43 | #----------------------------------------------------------------------------- | |
44 |
|
44 | |||
45 |
|
45 | |||
46 | class Config(dict): |
|
46 | class Config(dict): | |
47 | """An attribute based dict that can do smart merges.""" |
|
47 | """An attribute based dict that can do smart merges.""" | |
48 |
|
48 | |||
49 | def __init__(self, *args, **kwds): |
|
49 | def __init__(self, *args, **kwds): | |
50 | dict.__init__(self, *args, **kwds) |
|
50 | dict.__init__(self, *args, **kwds) | |
51 | # This sets self.__dict__ = self, but it has to be done this way |
|
51 | # This sets self.__dict__ = self, but it has to be done this way | |
52 | # because we are also overriding __setattr__. |
|
52 | # because we are also overriding __setattr__. | |
53 | dict.__setattr__(self, '__dict__', self) |
|
53 | dict.__setattr__(self, '__dict__', self) | |
54 |
|
54 | |||
55 | def _merge(self, other): |
|
55 | def _merge(self, other): | |
56 | to_update = {} |
|
56 | to_update = {} | |
57 | for k, v in other.items(): |
|
57 | for k, v in other.items(): | |
58 | if not self.has_key(k): |
|
58 | if not self.has_key(k): | |
59 | to_update[k] = v |
|
59 | to_update[k] = v | |
60 | else: # I have this key |
|
60 | else: # I have this key | |
61 | if isinstance(v, Config): |
|
61 | if isinstance(v, Config): | |
62 | # Recursively merge common sub Configs |
|
62 | # Recursively merge common sub Configs | |
63 | self[k]._merge(v) |
|
63 | self[k]._merge(v) | |
64 | else: |
|
64 | else: | |
65 | # Plain updates for non-Configs |
|
65 | # Plain updates for non-Configs | |
66 | to_update[k] = v |
|
66 | to_update[k] = v | |
67 |
|
67 | |||
68 | self.update(to_update) |
|
68 | self.update(to_update) | |
69 |
|
69 | |||
70 | def _is_section_key(self, key): |
|
70 | def _is_section_key(self, key): | |
71 | if key[0].upper()==key[0] and not key.startswith('_'): |
|
71 | if key[0].upper()==key[0] and not key.startswith('_'): | |
72 | return True |
|
72 | return True | |
73 | else: |
|
73 | else: | |
74 | return False |
|
74 | return False | |
75 |
|
75 | |||
76 | def has_key(self, key): |
|
76 | def has_key(self, key): | |
77 | if self._is_section_key(key): |
|
77 | if self._is_section_key(key): | |
78 | return True |
|
78 | return True | |
79 | else: |
|
79 | else: | |
80 | return dict.has_key(self, key) |
|
80 | return dict.has_key(self, key) | |
81 |
|
81 | |||
82 | def _has_section(self, key): |
|
82 | def _has_section(self, key): | |
83 | if self._is_section_key(key): |
|
83 | if self._is_section_key(key): | |
84 | if dict.has_key(self, key): |
|
84 | if dict.has_key(self, key): | |
85 | return True |
|
85 | return True | |
86 | return False |
|
86 | return False | |
87 |
|
87 | |||
88 | def copy(self): |
|
88 | def copy(self): | |
89 | return type(self)(dict.copy(self)) |
|
89 | return type(self)(dict.copy(self)) | |
90 |
|
90 | |||
91 | def __copy__(self): |
|
91 | def __copy__(self): | |
92 | return self.copy() |
|
92 | return self.copy() | |
93 |
|
93 | |||
94 | def __deepcopy__(self, memo): |
|
94 | def __deepcopy__(self, memo): | |
95 | import copy |
|
95 | import copy | |
96 | return type(self)(copy.deepcopy(self.items())) |
|
96 | return type(self)(copy.deepcopy(self.items())) | |
97 |
|
97 | |||
98 | def __getitem__(self, key): |
|
98 | def __getitem__(self, key): | |
99 | # Because we use this for an exec namespace, we need to delegate |
|
99 | # Because we use this for an exec namespace, we need to delegate | |
100 | # the lookup of names in __builtin__ to itself. This means |
|
100 | # the lookup of names in __builtin__ to itself. This means | |
101 | # that you can't have section or attribute names that are |
|
101 | # that you can't have section or attribute names that are | |
102 | # builtins. |
|
102 | # builtins. | |
103 | try: |
|
103 | try: | |
104 | return getattr(__builtin__, key) |
|
104 | return getattr(__builtin__, key) | |
105 | except AttributeError: |
|
105 | except AttributeError: | |
106 | pass |
|
106 | pass | |
107 | if self._is_section_key(key): |
|
107 | if self._is_section_key(key): | |
108 | try: |
|
108 | try: | |
109 | return dict.__getitem__(self, key) |
|
109 | return dict.__getitem__(self, key) | |
110 | except KeyError: |
|
110 | except KeyError: | |
111 | c = Config() |
|
111 | c = Config() | |
112 | dict.__setitem__(self, key, c) |
|
112 | dict.__setitem__(self, key, c) | |
113 | return c |
|
113 | return c | |
114 | else: |
|
114 | else: | |
115 | return dict.__getitem__(self, key) |
|
115 | return dict.__getitem__(self, key) | |
116 |
|
116 | |||
117 | def __setitem__(self, key, value): |
|
117 | def __setitem__(self, key, value): | |
118 | # Don't allow names in __builtin__ to be modified. |
|
118 | # Don't allow names in __builtin__ to be modified. | |
119 | if hasattr(__builtin__, key): |
|
119 | if hasattr(__builtin__, key): | |
120 | raise ConfigError('Config variable names cannot have the same name ' |
|
120 | raise ConfigError('Config variable names cannot have the same name ' | |
121 | 'as a Python builtin: %s' % key) |
|
121 | 'as a Python builtin: %s' % key) | |
122 | if self._is_section_key(key): |
|
122 | if self._is_section_key(key): | |
123 | if not isinstance(value, Config): |
|
123 | if not isinstance(value, Config): | |
124 | raise ValueError('values whose keys begin with an uppercase ' |
|
124 | raise ValueError('values whose keys begin with an uppercase ' | |
125 | 'char must be Config instances: %r, %r' % (key, value)) |
|
125 | 'char must be Config instances: %r, %r' % (key, value)) | |
126 | else: |
|
126 | else: | |
127 | dict.__setitem__(self, key, value) |
|
127 | dict.__setitem__(self, key, value) | |
128 |
|
128 | |||
129 | def __getattr__(self, key): |
|
129 | def __getattr__(self, key): | |
130 | try: |
|
130 | try: | |
131 | return self.__getitem__(key) |
|
131 | return self.__getitem__(key) | |
132 | except KeyError, e: |
|
132 | except KeyError, e: | |
133 | raise AttributeError(e) |
|
133 | raise AttributeError(e) | |
134 |
|
134 | |||
135 | def __setattr__(self, key, value): |
|
135 | def __setattr__(self, key, value): | |
136 | try: |
|
136 | try: | |
137 | self.__setitem__(key, value) |
|
137 | self.__setitem__(key, value) | |
138 | except KeyError, e: |
|
138 | except KeyError, e: | |
139 | raise AttributeError(e) |
|
139 | raise AttributeError(e) | |
140 |
|
140 | |||
141 | def __delattr__(self, key): |
|
141 | def __delattr__(self, key): | |
142 | try: |
|
142 | try: | |
143 | dict.__delitem__(self, key) |
|
143 | dict.__delitem__(self, key) | |
144 | except KeyError, e: |
|
144 | except KeyError, e: | |
145 | raise AttributeError(e) |
|
145 | raise AttributeError(e) | |
146 |
|
146 | |||
147 |
|
147 | |||
148 | #----------------------------------------------------------------------------- |
|
148 | #----------------------------------------------------------------------------- | |
149 | # Config loading classes |
|
149 | # Config loading classes | |
150 | #----------------------------------------------------------------------------- |
|
150 | #----------------------------------------------------------------------------- | |
151 |
|
151 | |||
152 |
|
152 | |||
153 | class ConfigLoader(object): |
|
153 | class ConfigLoader(object): | |
154 | """A object for loading configurations from just about anywhere. |
|
154 | """A object for loading configurations from just about anywhere. | |
155 |
|
155 | |||
156 | The resulting configuration is packaged as a :class:`Struct`. |
|
156 | The resulting configuration is packaged as a :class:`Struct`. | |
157 |
|
157 | |||
158 | Notes |
|
158 | Notes | |
159 | ----- |
|
159 | ----- | |
160 | A :class:`ConfigLoader` does one thing: load a config from a source |
|
160 | A :class:`ConfigLoader` does one thing: load a config from a source | |
161 | (file, command line arguments) and returns the data as a :class:`Struct`. |
|
161 | (file, command line arguments) and returns the data as a :class:`Struct`. | |
162 | There are lots of things that :class:`ConfigLoader` does not do. It does |
|
162 | There are lots of things that :class:`ConfigLoader` does not do. It does | |
163 | not implement complex logic for finding config files. It does not handle |
|
163 | not implement complex logic for finding config files. It does not handle | |
164 | default values or merge multiple configs. These things need to be |
|
164 | default values or merge multiple configs. These things need to be | |
165 | handled elsewhere. |
|
165 | handled elsewhere. | |
166 | """ |
|
166 | """ | |
167 |
|
167 | |||
168 | def __init__(self): |
|
168 | def __init__(self): | |
169 | """A base class for config loaders. |
|
169 | """A base class for config loaders. | |
170 |
|
170 | |||
171 | Examples |
|
171 | Examples | |
172 | -------- |
|
172 | -------- | |
173 |
|
173 | |||
174 | >>> cl = ConfigLoader() |
|
174 | >>> cl = ConfigLoader() | |
175 | >>> config = cl.load_config() |
|
175 | >>> config = cl.load_config() | |
176 | >>> config |
|
176 | >>> config | |
177 | {} |
|
177 | {} | |
178 | """ |
|
178 | """ | |
179 | self.clear() |
|
179 | self.clear() | |
180 |
|
180 | |||
181 | def clear(self): |
|
181 | def clear(self): | |
182 | self.config = Config() |
|
182 | self.config = Config() | |
183 |
|
183 | |||
184 | def load_config(self): |
|
184 | def load_config(self): | |
185 | """Load a config from somewhere, return a Struct. |
|
185 | """Load a config from somewhere, return a Struct. | |
186 |
|
186 | |||
187 | Usually, this will cause self.config to be set and then returned. |
|
187 | Usually, this will cause self.config to be set and then returned. | |
188 | """ |
|
188 | """ | |
189 | return self.config |
|
189 | return self.config | |
190 |
|
190 | |||
191 |
|
191 | |||
192 | class FileConfigLoader(ConfigLoader): |
|
192 | class FileConfigLoader(ConfigLoader): | |
193 | """A base class for file based configurations. |
|
193 | """A base class for file based configurations. | |
194 |
|
194 | |||
195 | As we add more file based config loaders, the common logic should go |
|
195 | As we add more file based config loaders, the common logic should go | |
196 | here. |
|
196 | here. | |
197 | """ |
|
197 | """ | |
198 | pass |
|
198 | pass | |
199 |
|
199 | |||
200 |
|
200 | |||
201 | class PyFileConfigLoader(FileConfigLoader): |
|
201 | class PyFileConfigLoader(FileConfigLoader): | |
202 | """A config loader for pure python files. |
|
202 | """A config loader for pure python files. | |
203 |
|
203 | |||
204 | This calls execfile on a plain python file and looks for attributes |
|
204 | This calls execfile on a plain python file and looks for attributes | |
205 | that are all caps. These attribute are added to the config Struct. |
|
205 | that are all caps. These attribute are added to the config Struct. | |
206 | """ |
|
206 | """ | |
207 |
|
207 | |||
208 | def __init__(self, filename, path=None): |
|
208 | def __init__(self, filename, path=None): | |
209 | """Build a config loader for a filename and path. |
|
209 | """Build a config loader for a filename and path. | |
210 |
|
210 | |||
211 | Parameters |
|
211 | Parameters | |
212 | ---------- |
|
212 | ---------- | |
213 | filename : str |
|
213 | filename : str | |
214 | The file name of the config file. |
|
214 | The file name of the config file. | |
215 | path : str, list, tuple |
|
215 | path : str, list, tuple | |
216 | The path to search for the config file on, or a sequence of |
|
216 | The path to search for the config file on, or a sequence of | |
217 | paths to try in order. |
|
217 | paths to try in order. | |
218 | """ |
|
218 | """ | |
219 | super(PyFileConfigLoader, self).__init__() |
|
219 | super(PyFileConfigLoader, self).__init__() | |
220 | self.filename = filename |
|
220 | self.filename = filename | |
221 | self.path = path |
|
221 | self.path = path | |
222 | self.full_filename = '' |
|
222 | self.full_filename = '' | |
223 | self.data = None |
|
223 | self.data = None | |
224 |
|
224 | |||
225 | def load_config(self): |
|
225 | def load_config(self): | |
226 | """Load the config from a file and return it as a Struct.""" |
|
226 | """Load the config from a file and return it as a Struct.""" | |
227 | self._find_file() |
|
227 | self._find_file() | |
228 | self._read_file_as_dict() |
|
228 | self._read_file_as_dict() | |
229 | self._convert_to_config() |
|
229 | self._convert_to_config() | |
230 | return self.config |
|
230 | return self.config | |
231 |
|
231 | |||
232 | def _find_file(self): |
|
232 | def _find_file(self): | |
233 | """Try to find the file by searching the paths.""" |
|
233 | """Try to find the file by searching the paths.""" | |
234 | self.full_filename = filefind(self.filename, self.path) |
|
234 | self.full_filename = filefind(self.filename, self.path) | |
235 |
|
235 | |||
236 | def _read_file_as_dict(self): |
|
236 | def _read_file_as_dict(self): | |
237 | execfile(self.full_filename, self.config) |
|
237 | execfile(self.full_filename, self.config) | |
238 |
|
238 | |||
239 | def _convert_to_config(self): |
|
239 | def _convert_to_config(self): | |
240 | if self.data is None: |
|
240 | if self.data is None: | |
241 | ConfigLoaderError('self.data does not exist') |
|
241 | ConfigLoaderError('self.data does not exist') | |
242 | del self.config['__builtins__'] |
|
242 | del self.config['__builtins__'] | |
243 |
|
243 | |||
244 |
|
244 | |||
245 | class CommandLineConfigLoader(ConfigLoader): |
|
245 | class CommandLineConfigLoader(ConfigLoader): | |
246 | """A config loader for command line arguments. |
|
246 | """A config loader for command line arguments. | |
247 |
|
247 | |||
248 | As we add more command line based loaders, the common logic should go |
|
248 | As we add more command line based loaders, the common logic should go | |
249 | here. |
|
249 | here. | |
250 | """ |
|
250 | """ | |
251 |
|
251 | |||
252 |
|
252 | |||
253 | class NoConfigDefault(object): pass |
|
253 | class NoConfigDefault(object): pass | |
254 | NoConfigDefault = NoConfigDefault() |
|
254 | NoConfigDefault = NoConfigDefault() | |
255 |
|
255 | |||
256 | class ArgParseConfigLoader(CommandLineConfigLoader): |
|
256 | class ArgParseConfigLoader(CommandLineConfigLoader): | |
257 |
|
257 | |||
258 | # arguments = [(('-f','--file'),dict(type=str,dest='file'))] |
|
258 | # arguments = [(('-f','--file'),dict(type=str,dest='file'))] | |
259 | arguments = () |
|
259 | arguments = () | |
260 |
|
260 | |||
261 | def __init__(self, *args, **kw): |
|
261 | def __init__(self, *args, **kw): | |
262 | """Create a config loader for use with argparse. |
|
262 | """Create a config loader for use with argparse. | |
263 |
|
263 | |||
264 | The args and kwargs arguments here are passed onto the constructor |
|
264 | The args and kwargs arguments here are passed onto the constructor | |
265 | of :class:`argparse.ArgumentParser`. |
|
265 | of :class:`argparse.ArgumentParser`. | |
266 | """ |
|
266 | """ | |
267 | super(CommandLineConfigLoader, self).__init__() |
|
267 | super(CommandLineConfigLoader, self).__init__() | |
268 | self.args = args |
|
268 | self.args = args | |
269 | self.kw = kw |
|
269 | self.kw = kw | |
270 |
|
270 | |||
271 | def load_config(self, args=None): |
|
271 | def load_config(self, args=None): | |
272 | """Parse command line arguments and return as a Struct.""" |
|
272 | """Parse command line arguments and return as a Struct.""" | |
273 | self._create_parser() |
|
273 | self._create_parser() | |
274 | self._parse_args(args) |
|
274 | self._parse_args(args) | |
275 | self._convert_to_config() |
|
275 | self._convert_to_config() | |
276 | return self.config |
|
276 | return self.config | |
277 |
|
277 | |||
|
278 | def get_extra_args(self): | |||
|
279 | if hasattr(self, 'extra_args'): | |||
|
280 | return self.extra_args | |||
|
281 | else: | |||
|
282 | return [] | |||
|
283 | ||||
278 | def _create_parser(self): |
|
284 | def _create_parser(self): | |
279 | self.parser = argparse.ArgumentParser(*self.args, **self.kw) |
|
285 | self.parser = argparse.ArgumentParser(*self.args, **self.kw) | |
280 | self._add_arguments() |
|
286 | self._add_arguments() | |
281 | self._add_other_arguments() |
|
287 | self._add_other_arguments() | |
282 |
|
288 | |||
283 | def _add_other_arguments(self): |
|
289 | def _add_other_arguments(self): | |
284 | pass |
|
290 | pass | |
285 |
|
291 | |||
286 | def _add_arguments(self): |
|
292 | def _add_arguments(self): | |
287 | for argument in self.arguments: |
|
293 | for argument in self.arguments: | |
288 | if not argument[1].has_key('default'): |
|
294 | if not argument[1].has_key('default'): | |
289 | argument[1]['default'] = NoConfigDefault |
|
295 | argument[1]['default'] = NoConfigDefault | |
290 | self.parser.add_argument(*argument[0],**argument[1]) |
|
296 | self.parser.add_argument(*argument[0],**argument[1]) | |
291 |
|
297 | |||
292 | def _parse_args(self, args=None): |
|
298 | def _parse_args(self, args=None): | |
293 | """self.parser->self.parsed_data""" |
|
299 | """self.parser->self.parsed_data""" | |
294 | if args is None: |
|
300 | if args is None: | |
295 | self.parsed_data = self.parser.parse_args() |
|
301 | self.parsed_data, self.extra_args = self.parser.parse_known_args() | |
296 | else: |
|
302 | else: | |
297 | self.parsed_data = self.parser.parse_args(args) |
|
303 | self.parsed_data, self.extra_args = self.parser.parse_known_args(args) | |
298 |
|
304 | |||
299 | def _convert_to_config(self): |
|
305 | def _convert_to_config(self): | |
300 | """self.parsed_data->self.config""" |
|
306 | """self.parsed_data->self.config""" | |
301 | for k, v in vars(self.parsed_data).items(): |
|
307 | for k, v in vars(self.parsed_data).items(): | |
302 | if v is not NoConfigDefault: |
|
308 | if v is not NoConfigDefault: | |
303 | exec_str = 'self.config.' + k + '= v' |
|
309 | exec_str = 'self.config.' + k + '= v' | |
304 | exec exec_str in locals(), globals() |
|
310 | exec exec_str in locals(), globals() | |
305 |
|
311 |
@@ -1,287 +1,295 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | An application for IPython |
|
4 | An application for IPython | |
5 |
|
5 | |||
6 | Authors: |
|
6 | Authors: | |
7 |
|
7 | |||
8 | * Brian Granger |
|
8 | * Brian Granger | |
9 | * Fernando Perez |
|
9 | * Fernando Perez | |
10 |
|
10 | |||
11 | Notes |
|
11 | Notes | |
12 | ----- |
|
12 | ----- | |
13 | """ |
|
13 | """ | |
14 |
|
14 | |||
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 | # Copyright (C) 2008-2009 The IPython Development Team |
|
16 | # Copyright (C) 2008-2009 The IPython Development Team | |
17 | # |
|
17 | # | |
18 | # Distributed under the terms of the BSD License. The full license is in |
|
18 | # Distributed under the terms of the BSD License. The full license is in | |
19 | # the file COPYING, distributed as part of this software. |
|
19 | # the file COPYING, distributed as part of this software. | |
20 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
21 |
|
21 | |||
22 | #----------------------------------------------------------------------------- |
|
22 | #----------------------------------------------------------------------------- | |
23 | # Imports |
|
23 | # Imports | |
24 | #----------------------------------------------------------------------------- |
|
24 | #----------------------------------------------------------------------------- | |
25 |
|
25 | |||
26 | import logging |
|
26 | import logging | |
27 | import os |
|
27 | import os | |
28 | import sys |
|
28 | import sys | |
29 | import traceback |
|
29 | import traceback | |
30 | from copy import deepcopy |
|
30 | from copy import deepcopy | |
31 |
|
31 | |||
32 | from IPython.utils.genutils import get_ipython_dir, filefind |
|
32 | from IPython.utils.genutils import get_ipython_dir, filefind | |
33 | from IPython.config.loader import ( |
|
33 | from IPython.config.loader import ( | |
34 | PyFileConfigLoader, |
|
34 | PyFileConfigLoader, | |
35 | ArgParseConfigLoader, |
|
35 | ArgParseConfigLoader, | |
36 | Config, |
|
36 | Config, | |
37 | NoConfigDefault |
|
37 | NoConfigDefault | |
38 | ) |
|
38 | ) | |
39 |
|
39 | |||
40 | #----------------------------------------------------------------------------- |
|
40 | #----------------------------------------------------------------------------- | |
41 | # Classes and functions |
|
41 | # Classes and functions | |
42 | #----------------------------------------------------------------------------- |
|
42 | #----------------------------------------------------------------------------- | |
43 |
|
43 | |||
44 |
|
44 | |||
45 | class IPythonArgParseConfigLoader(ArgParseConfigLoader): |
|
45 | class IPythonArgParseConfigLoader(ArgParseConfigLoader): | |
46 | """Default command line options for IPython based applications.""" |
|
46 | """Default command line options for IPython based applications.""" | |
47 |
|
47 | |||
48 | def _add_other_arguments(self): |
|
48 | def _add_other_arguments(self): | |
49 | self.parser.add_argument('-ipythondir',dest='Global.ipythondir',type=str, |
|
49 | self.parser.add_argument('-ipythondir',dest='Global.ipythondir',type=str, | |
50 | help='Set to override default location of Global.ipythondir.', |
|
50 | help='Set to override default location of Global.ipythondir.', | |
51 | default=NoConfigDefault, |
|
51 | default=NoConfigDefault, | |
52 | metavar='Global.ipythondir') |
|
52 | metavar='Global.ipythondir') | |
53 | self.parser.add_argument('-p','-profile',dest='Global.profile',type=str, |
|
53 | self.parser.add_argument('-p','-profile',dest='Global.profile',type=str, | |
54 | help='The string name of the ipython profile to be used.', |
|
54 | help='The string name of the ipython profile to be used.', | |
55 | default=NoConfigDefault, |
|
55 | default=NoConfigDefault, | |
56 | metavar='Global.profile') |
|
56 | metavar='Global.profile') | |
57 | self.parser.add_argument('-log_level',dest="Global.log_level",type=int, |
|
57 | self.parser.add_argument('-log_level',dest="Global.log_level",type=int, | |
58 | help='Set the log level (0,10,20,30,40,50). Default is 30.', |
|
58 | help='Set the log level (0,10,20,30,40,50). Default is 30.', | |
59 | default=NoConfigDefault) |
|
59 | default=NoConfigDefault) | |
60 | self.parser.add_argument('-config_file',dest='Global.config_file',type=str, |
|
60 | self.parser.add_argument('-config_file',dest='Global.config_file',type=str, | |
61 | help='Set the config file name to override default.', |
|
61 | help='Set the config file name to override default.', | |
62 | default=NoConfigDefault, |
|
62 | default=NoConfigDefault, | |
63 | metavar='Global.config_file') |
|
63 | metavar='Global.config_file') | |
64 |
|
64 | |||
65 |
|
65 | |||
66 | class ApplicationError(Exception): |
|
66 | class ApplicationError(Exception): | |
67 | pass |
|
67 | pass | |
68 |
|
68 | |||
69 |
|
69 | |||
70 | class Application(object): |
|
70 | class Application(object): | |
71 | """Load a config, construct an app and run it. |
|
71 | """Load a config, construct an app and run it. | |
72 | """ |
|
72 | """ | |
73 |
|
73 | |||
74 | config_file_name = 'ipython_config.py' |
|
74 | config_file_name = 'ipython_config.py' | |
75 | name = 'ipython' |
|
75 | name = 'ipython' | |
76 |
|
76 | |||
77 | def __init__(self): |
|
77 | def __init__(self): | |
78 | self.init_logger() |
|
78 | self.init_logger() | |
79 |
|
79 | |||
80 | def init_logger(self): |
|
80 | def init_logger(self): | |
81 | self.log = logging.getLogger(self.__class__.__name__) |
|
81 | self.log = logging.getLogger(self.__class__.__name__) | |
82 | # This is used as the default until the command line arguments are read. |
|
82 | # This is used as the default until the command line arguments are read. | |
83 | self.log.setLevel(logging.WARN) |
|
83 | self.log.setLevel(logging.WARN) | |
84 | self._log_handler = logging.StreamHandler() |
|
84 | self._log_handler = logging.StreamHandler() | |
85 | self._log_formatter = logging.Formatter("[%(name)s] %(message)s") |
|
85 | self._log_formatter = logging.Formatter("[%(name)s] %(message)s") | |
86 | self._log_handler.setFormatter(self._log_formatter) |
|
86 | self._log_handler.setFormatter(self._log_formatter) | |
87 | self.log.addHandler(self._log_handler) |
|
87 | self.log.addHandler(self._log_handler) | |
88 |
|
88 | |||
89 | def _set_log_level(self, level): |
|
89 | def _set_log_level(self, level): | |
90 | self.log.setLevel(level) |
|
90 | self.log.setLevel(level) | |
91 |
|
91 | |||
92 | def _get_log_level(self): |
|
92 | def _get_log_level(self): | |
93 | return self.log.level |
|
93 | return self.log.level | |
94 |
|
94 | |||
95 | log_level = property(_get_log_level, _set_log_level) |
|
95 | log_level = property(_get_log_level, _set_log_level) | |
96 |
|
96 | |||
97 | def start(self): |
|
97 | def start(self): | |
98 | """Start the application.""" |
|
98 | """Start the application.""" | |
99 | self.attempt(self.create_default_config) |
|
99 | self.attempt(self.create_default_config) | |
100 | self.attempt(self.pre_load_command_line_config) |
|
100 | self.attempt(self.pre_load_command_line_config) | |
101 | self.attempt(self.load_command_line_config, action='abort') |
|
101 | self.attempt(self.load_command_line_config, action='abort') | |
102 | self.attempt(self.post_load_command_line_config) |
|
102 | self.attempt(self.post_load_command_line_config) | |
103 | self.attempt(self.find_ipythondir) |
|
103 | self.attempt(self.find_ipythondir) | |
104 | self.attempt(self.find_config_file_name) |
|
104 | self.attempt(self.find_config_file_name) | |
105 | self.attempt(self.find_config_file_paths) |
|
105 | self.attempt(self.find_config_file_paths) | |
106 | self.attempt(self.pre_load_file_config) |
|
106 | self.attempt(self.pre_load_file_config) | |
107 | self.attempt(self.load_file_config) |
|
107 | self.attempt(self.load_file_config) | |
108 | self.attempt(self.post_load_file_config) |
|
108 | self.attempt(self.post_load_file_config) | |
109 | self.attempt(self.merge_configs) |
|
109 | self.attempt(self.merge_configs) | |
110 | self.attempt(self.pre_construct) |
|
110 | self.attempt(self.pre_construct) | |
111 | self.attempt(self.construct) |
|
111 | self.attempt(self.construct) | |
112 | self.attempt(self.post_construct) |
|
112 | self.attempt(self.post_construct) | |
113 | self.attempt(self.start_app) |
|
113 | self.attempt(self.start_app) | |
114 |
|
114 | |||
115 | #------------------------------------------------------------------------- |
|
115 | #------------------------------------------------------------------------- | |
116 | # Various stages of Application creation |
|
116 | # Various stages of Application creation | |
117 | #------------------------------------------------------------------------- |
|
117 | #------------------------------------------------------------------------- | |
118 |
|
118 | |||
119 | def create_default_config(self): |
|
119 | def create_default_config(self): | |
120 |
"""Create defaults that can't be set elsewhere. |
|
120 | """Create defaults that can't be set elsewhere. | |
|
121 | ||||
|
122 | For the most part, we try to set default in the class attributes | |||
|
123 | of Components. But, defaults the top-level Application (which is | |||
|
124 | not a HasTraitlets or Component) are not set in this way. Instead | |||
|
125 | we set them here. The Global section is for variables like this that | |||
|
126 | don't belong to a particular component. | |||
|
127 | """ | |||
121 | self.default_config = Config() |
|
128 | self.default_config = Config() | |
122 | self.default_config.Global.ipythondir = get_ipython_dir() |
|
129 | self.default_config.Global.ipythondir = get_ipython_dir() | |
123 | self.log.debug('Default config loaded:') |
|
130 | self.log.debug('Default config loaded:') | |
124 | self.log.debug(repr(self.default_config)) |
|
131 | self.log.debug(repr(self.default_config)) | |
125 |
|
132 | |||
126 | def create_command_line_config(self): |
|
133 | def create_command_line_config(self): | |
127 | """Create and return a command line config loader.""" |
|
134 | """Create and return a command line config loader.""" | |
128 | return IPythonArgParseConfigLoader(description=self.name) |
|
135 | return IPythonArgParseConfigLoader(description=self.name) | |
129 |
|
136 | |||
130 | def pre_load_command_line_config(self): |
|
137 | def pre_load_command_line_config(self): | |
131 | """Do actions just before loading the command line config.""" |
|
138 | """Do actions just before loading the command line config.""" | |
132 | pass |
|
139 | pass | |
133 |
|
140 | |||
134 | def load_command_line_config(self): |
|
141 | def load_command_line_config(self): | |
135 | """Load the command line config. |
|
142 | """Load the command line config. | |
136 |
|
143 | |||
137 | This method also sets ``self.debug``. |
|
144 | This method also sets ``self.debug``. | |
138 | """ |
|
145 | """ | |
139 |
|
146 | |||
140 | loader = self.create_command_line_config() |
|
147 | loader = self.create_command_line_config() | |
141 | self.command_line_config = loader.load_config() |
|
148 | self.command_line_config = loader.load_config() | |
|
149 | self.extra_args = loader.get_extra_args() | |||
142 |
|
150 | |||
143 | try: |
|
151 | try: | |
144 | self.log_level = self.command_line_config.Global.log_level |
|
152 | self.log_level = self.command_line_config.Global.log_level | |
145 | except AttributeError: |
|
153 | except AttributeError: | |
146 | pass # Use existing value which is set in Application.init_logger. |
|
154 | pass # Use existing value which is set in Application.init_logger. | |
147 |
|
155 | |||
148 | self.log.debug("Command line config loaded:") |
|
156 | self.log.debug("Command line config loaded:") | |
149 | self.log.debug(repr(self.command_line_config)) |
|
157 | self.log.debug(repr(self.command_line_config)) | |
150 |
|
158 | |||
151 | def post_load_command_line_config(self): |
|
159 | def post_load_command_line_config(self): | |
152 | """Do actions just after loading the command line config.""" |
|
160 | """Do actions just after loading the command line config.""" | |
153 | pass |
|
161 | pass | |
154 |
|
162 | |||
155 | def find_ipythondir(self): |
|
163 | def find_ipythondir(self): | |
156 | """Set the IPython directory. |
|
164 | """Set the IPython directory. | |
157 |
|
165 | |||
158 | This sets ``self.ipythondir``, but the actual value that is passed |
|
166 | This sets ``self.ipythondir``, but the actual value that is passed | |
159 | to the application is kept in either ``self.default_config`` or |
|
167 | to the application is kept in either ``self.default_config`` or | |
160 | ``self.command_line_config``. This also added ``self.ipythondir`` to |
|
168 | ``self.command_line_config``. This also added ``self.ipythondir`` to | |
161 | ``sys.path`` so config files there can be references by other config |
|
169 | ``sys.path`` so config files there can be references by other config | |
162 | files. |
|
170 | files. | |
163 | """ |
|
171 | """ | |
164 |
|
172 | |||
165 | try: |
|
173 | try: | |
166 | self.ipythondir = self.command_line_config.Global.ipythondir |
|
174 | self.ipythondir = self.command_line_config.Global.ipythondir | |
167 | except AttributeError: |
|
175 | except AttributeError: | |
168 | self.ipythondir = self.default_config.Global.ipythondir |
|
176 | self.ipythondir = self.default_config.Global.ipythondir | |
169 | sys.path.append(os.path.abspath(self.ipythondir)) |
|
177 | sys.path.append(os.path.abspath(self.ipythondir)) | |
170 | if not os.path.isdir(self.ipythondir): |
|
178 | if not os.path.isdir(self.ipythondir): | |
171 | os.makedirs(self.ipythondir, mode = 0777) |
|
179 | os.makedirs(self.ipythondir, mode = 0777) | |
172 | self.log.debug("IPYTHONDIR set to: %s" % self.ipythondir) |
|
180 | self.log.debug("IPYTHONDIR set to: %s" % self.ipythondir) | |
173 |
|
181 | |||
174 | def find_config_file_name(self): |
|
182 | def find_config_file_name(self): | |
175 | """Find the config file name for this application. |
|
183 | """Find the config file name for this application. | |
176 |
|
184 | |||
177 | If a profile has been set at the command line, this will resolve |
|
185 | If a profile has been set at the command line, this will resolve | |
178 | it. The search paths for the config file are set in |
|
186 | it. The search paths for the config file are set in | |
179 | :meth:`find_config_file_paths` and then passed to the config file |
|
187 | :meth:`find_config_file_paths` and then passed to the config file | |
180 | loader where they are resolved to an absolute path. |
|
188 | loader where they are resolved to an absolute path. | |
181 | """ |
|
189 | """ | |
182 |
|
190 | |||
183 | try: |
|
191 | try: | |
184 | self.config_file_name = self.command_line_config.Global.config_file |
|
192 | self.config_file_name = self.command_line_config.Global.config_file | |
185 | except AttributeError: |
|
193 | except AttributeError: | |
186 | pass |
|
194 | pass | |
187 |
|
195 | |||
188 | try: |
|
196 | try: | |
189 | self.profile_name = self.command_line_config.Global.profile |
|
197 | self.profile_name = self.command_line_config.Global.profile | |
190 | name_parts = self.config_file_name.split('.') |
|
198 | name_parts = self.config_file_name.split('.') | |
191 | name_parts.insert(1, '_' + self.profile_name + '.') |
|
199 | name_parts.insert(1, '_' + self.profile_name + '.') | |
192 | self.config_file_name = ''.join(name_parts) |
|
200 | self.config_file_name = ''.join(name_parts) | |
193 | except AttributeError: |
|
201 | except AttributeError: | |
194 | pass |
|
202 | pass | |
195 |
|
203 | |||
196 | def find_config_file_paths(self): |
|
204 | def find_config_file_paths(self): | |
197 | """Set the search paths for resolving the config file.""" |
|
205 | """Set the search paths for resolving the config file.""" | |
198 | self.config_file_paths = (os.getcwd(), self.ipythondir) |
|
206 | self.config_file_paths = (os.getcwd(), self.ipythondir) | |
199 |
|
207 | |||
200 | def pre_load_file_config(self): |
|
208 | def pre_load_file_config(self): | |
201 | """Do actions before the config file is loaded.""" |
|
209 | """Do actions before the config file is loaded.""" | |
202 | pass |
|
210 | pass | |
203 |
|
211 | |||
204 | def load_file_config(self): |
|
212 | def load_file_config(self): | |
205 | """Load the config file. |
|
213 | """Load the config file. | |
206 |
|
214 | |||
207 | This tries to load the config file from disk. If successful, the |
|
215 | This tries to load the config file from disk. If successful, the | |
208 | ``CONFIG_FILE`` config variable is set to the resolved config file |
|
216 | ``CONFIG_FILE`` config variable is set to the resolved config file | |
209 | location. If not successful, an empty config is used. |
|
217 | location. If not successful, an empty config is used. | |
210 | """ |
|
218 | """ | |
211 | self.log.debug("Attempting to load config file: <%s>" % self.config_file_name) |
|
219 | self.log.debug("Attempting to load config file: <%s>" % self.config_file_name) | |
212 | loader = PyFileConfigLoader(self.config_file_name, |
|
220 | loader = PyFileConfigLoader(self.config_file_name, | |
213 | path=self.config_file_paths) |
|
221 | path=self.config_file_paths) | |
214 | try: |
|
222 | try: | |
215 | self.file_config = loader.load_config() |
|
223 | self.file_config = loader.load_config() | |
216 | self.file_config.Global.config_file = loader.full_filename |
|
224 | self.file_config.Global.config_file = loader.full_filename | |
217 | except IOError: |
|
225 | except IOError: | |
218 | self.log.warn("Config file not found, skipping: <%s>" % \ |
|
226 | self.log.warn("Config file not found, skipping: <%s>" % \ | |
219 | self.config_file_name, exc_info=True) |
|
227 | self.config_file_name, exc_info=True) | |
220 | self.file_config = Config() |
|
228 | self.file_config = Config() | |
221 | except: |
|
229 | except: | |
222 | self.log.warn("Error loading config file: <%s>" % \ |
|
230 | self.log.warn("Error loading config file: <%s>" % \ | |
223 | self.config_file_name, exc_info=True) |
|
231 | self.config_file_name, exc_info=True) | |
224 | self.file_config = Config() |
|
232 | self.file_config = Config() | |
225 | else: |
|
233 | else: | |
226 | self.log.debug("Config file loaded: <%s>" % loader.full_filename) |
|
234 | self.log.debug("Config file loaded: <%s>" % loader.full_filename) | |
227 | self.log.debug(repr(self.file_config)) |
|
235 | self.log.debug(repr(self.file_config)) | |
228 | # We need to keeep self.log_level updated. |
|
236 | # We need to keeep self.log_level updated. | |
229 | try: |
|
237 | try: | |
230 | self.log_level = self.file_config.Global.log_level |
|
238 | self.log_level = self.file_config.Global.log_level | |
231 | except AttributeError: |
|
239 | except AttributeError: | |
232 | pass # Use existing value |
|
240 | pass # Use existing value | |
233 |
|
241 | |||
234 | def post_load_file_config(self): |
|
242 | def post_load_file_config(self): | |
235 | """Do actions after the config file is loaded.""" |
|
243 | """Do actions after the config file is loaded.""" | |
236 | pass |
|
244 | pass | |
237 |
|
245 | |||
238 | def merge_configs(self): |
|
246 | def merge_configs(self): | |
239 | """Merge the default, command line and file config objects.""" |
|
247 | """Merge the default, command line and file config objects.""" | |
240 | config = Config() |
|
248 | config = Config() | |
241 | config._merge(self.default_config) |
|
249 | config._merge(self.default_config) | |
242 | config._merge(self.file_config) |
|
250 | config._merge(self.file_config) | |
243 | config._merge(self.command_line_config) |
|
251 | config._merge(self.command_line_config) | |
244 | self.master_config = config |
|
252 | self.master_config = config | |
245 | self.log.debug("Master config created:") |
|
253 | self.log.debug("Master config created:") | |
246 | self.log.debug(repr(self.master_config)) |
|
254 | self.log.debug(repr(self.master_config)) | |
247 |
|
255 | |||
248 | def pre_construct(self): |
|
256 | def pre_construct(self): | |
249 | """Do actions after the config has been built, but before construct.""" |
|
257 | """Do actions after the config has been built, but before construct.""" | |
250 | pass |
|
258 | pass | |
251 |
|
259 | |||
252 | def construct(self): |
|
260 | def construct(self): | |
253 | """Construct the main components that make up this app.""" |
|
261 | """Construct the main components that make up this app.""" | |
254 | self.log.debug("Constructing components for application") |
|
262 | self.log.debug("Constructing components for application") | |
255 |
|
263 | |||
256 | def post_construct(self): |
|
264 | def post_construct(self): | |
257 | """Do actions after construct, but before starting the app.""" |
|
265 | """Do actions after construct, but before starting the app.""" | |
258 | pass |
|
266 | pass | |
259 |
|
267 | |||
260 | def start_app(self): |
|
268 | def start_app(self): | |
261 | """Actually start the app.""" |
|
269 | """Actually start the app.""" | |
262 | self.log.debug("Starting application") |
|
270 | self.log.debug("Starting application") | |
263 |
|
271 | |||
264 | #------------------------------------------------------------------------- |
|
272 | #------------------------------------------------------------------------- | |
265 | # Utility methods |
|
273 | # Utility methods | |
266 | #------------------------------------------------------------------------- |
|
274 | #------------------------------------------------------------------------- | |
267 |
|
275 | |||
268 | def abort(self): |
|
276 | def abort(self): | |
269 | """Abort the starting of the application.""" |
|
277 | """Abort the starting of the application.""" | |
270 | self.log.critical("Aborting application: %s" % self.name, exc_info=True) |
|
278 | self.log.critical("Aborting application: %s" % self.name, exc_info=True) | |
271 | sys.exit(1) |
|
279 | sys.exit(1) | |
272 |
|
280 | |||
273 | def exit(self): |
|
281 | def exit(self): | |
274 | self.log.critical("Aborting application: %s" % self.name) |
|
282 | self.log.critical("Aborting application: %s" % self.name) | |
275 | sys.exit(1) |
|
283 | sys.exit(1) | |
276 |
|
284 | |||
277 | def attempt(self, func, action='abort'): |
|
285 | def attempt(self, func, action='abort'): | |
278 | try: |
|
286 | try: | |
279 | func() |
|
287 | func() | |
280 | except SystemExit: |
|
288 | except SystemExit: | |
281 | self.exit() |
|
289 | self.exit() | |
282 | except: |
|
290 | except: | |
283 | if action == 'abort': |
|
291 | if action == 'abort': | |
284 | self.abort() |
|
292 | self.abort() | |
285 | elif action == 'exit': |
|
293 | elif action == 'exit': | |
286 | self.exit() |
|
294 | self.exit() | |
287 | No newline at end of file |
|
295 |
@@ -1,442 +1,490 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | The main IPython application object |
|
4 | The main IPython application object | |
5 |
|
5 | |||
6 | Authors: |
|
6 | Authors: | |
7 |
|
7 | |||
8 | * Brian Granger |
|
8 | * Brian Granger | |
9 | * Fernando Perez |
|
9 | * Fernando Perez | |
10 |
|
10 | |||
11 | Notes |
|
11 | Notes | |
12 | ----- |
|
12 | ----- | |
13 | """ |
|
13 | """ | |
14 |
|
14 | |||
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 | # Copyright (C) 2008-2009 The IPython Development Team |
|
16 | # Copyright (C) 2008-2009 The IPython Development Team | |
17 | # |
|
17 | # | |
18 | # Distributed under the terms of the BSD License. The full license is in |
|
18 | # Distributed under the terms of the BSD License. The full license is in | |
19 | # the file COPYING, distributed as part of this software. |
|
19 | # the file COPYING, distributed as part of this software. | |
20 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
21 |
|
21 | |||
22 | #----------------------------------------------------------------------------- |
|
22 | #----------------------------------------------------------------------------- | |
23 | # Imports |
|
23 | # Imports | |
24 | #----------------------------------------------------------------------------- |
|
24 | #----------------------------------------------------------------------------- | |
25 |
|
25 | |||
26 | import logging |
|
26 | import logging | |
27 | import os |
|
27 | import os | |
28 | import sys |
|
28 | import sys | |
29 | import warnings |
|
29 | import warnings | |
30 |
|
30 | |||
31 | from IPython.core.application import Application, IPythonArgParseConfigLoader |
|
31 | from IPython.core.application import Application, IPythonArgParseConfigLoader | |
32 | from IPython.core import release |
|
32 | from IPython.core import release | |
33 | from IPython.core.iplib import InteractiveShell |
|
33 | from IPython.core.iplib import InteractiveShell | |
34 | from IPython.config.loader import ( |
|
34 | from IPython.config.loader import ( | |
35 | NoConfigDefault, |
|
35 | NoConfigDefault, | |
36 | Config, |
|
36 | Config, | |
37 | ConfigError, |
|
37 | ConfigError, | |
38 | PyFileConfigLoader |
|
38 | PyFileConfigLoader | |
39 | ) |
|
39 | ) | |
40 |
|
40 | |||
41 | from IPython.utils.ipstruct import Struct |
|
41 | from IPython.utils.ipstruct import Struct | |
42 | from IPython.utils.genutils import filefind, get_ipython_dir |
|
42 | from IPython.utils.genutils import filefind, get_ipython_dir | |
43 |
|
43 | |||
44 | #----------------------------------------------------------------------------- |
|
44 | #----------------------------------------------------------------------------- | |
45 | # Utilities and helpers |
|
45 | # Utilities and helpers | |
46 | #----------------------------------------------------------------------------- |
|
46 | #----------------------------------------------------------------------------- | |
47 |
|
47 | |||
48 |
|
48 | |||
49 | ipython_desc = """ |
|
49 | ipython_desc = """ | |
50 | A Python shell with automatic history (input and output), dynamic object |
|
50 | A Python shell with automatic history (input and output), dynamic object | |
51 | introspection, easier configuration, command completion, access to the system |
|
51 | introspection, easier configuration, command completion, access to the system | |
52 | shell and more. |
|
52 | shell and more. | |
53 | """ |
|
53 | """ | |
54 |
|
54 | |||
55 | def threaded_shell_warning(): |
|
55 | def threaded_shell_warning(): | |
56 | msg = """ |
|
56 | msg = """ | |
57 |
|
57 | |||
58 | The IPython threaded shells and their associated command line |
|
58 | The IPython threaded shells and their associated command line | |
59 | arguments (pylab/wthread/gthread/qthread/q4thread) have been |
|
59 | arguments (pylab/wthread/gthread/qthread/q4thread) have been | |
60 | deprecated. See the %gui magic for information on the new interface. |
|
60 | deprecated. See the %gui magic for information on the new interface. | |
61 | """ |
|
61 | """ | |
62 | warnings.warn(msg, category=DeprecationWarning, stacklevel=1) |
|
62 | warnings.warn(msg, category=DeprecationWarning, stacklevel=1) | |
63 |
|
63 | |||
64 |
|
64 | |||
65 | #----------------------------------------------------------------------------- |
|
65 | #----------------------------------------------------------------------------- | |
66 | # Main classes and functions |
|
66 | # Main classes and functions | |
67 | #----------------------------------------------------------------------------- |
|
67 | #----------------------------------------------------------------------------- | |
68 |
|
68 | |||
69 | cl_args = ( |
|
69 | cl_args = ( | |
70 | (('-autocall',), dict( |
|
70 | (('-autocall',), dict( | |
71 | type=int, dest='InteractiveShell.autocall', default=NoConfigDefault, |
|
71 | type=int, dest='InteractiveShell.autocall', default=NoConfigDefault, | |
72 | help='Set the autocall value (0,1,2).', |
|
72 | help='Set the autocall value (0,1,2).', | |
73 | metavar='InteractiveShell.autocall') |
|
73 | metavar='InteractiveShell.autocall') | |
74 | ), |
|
74 | ), | |
75 | (('-autoindent',), dict( |
|
75 | (('-autoindent',), dict( | |
76 | action='store_true', dest='InteractiveShell.autoindent', default=NoConfigDefault, |
|
76 | action='store_true', dest='InteractiveShell.autoindent', default=NoConfigDefault, | |
77 | help='Turn on autoindenting.') |
|
77 | help='Turn on autoindenting.') | |
78 | ), |
|
78 | ), | |
79 | (('-noautoindent',), dict( |
|
79 | (('-noautoindent',), dict( | |
80 | action='store_false', dest='InteractiveShell.autoindent', default=NoConfigDefault, |
|
80 | action='store_false', dest='InteractiveShell.autoindent', default=NoConfigDefault, | |
81 | help='Turn off autoindenting.') |
|
81 | help='Turn off autoindenting.') | |
82 | ), |
|
82 | ), | |
83 | (('-automagic',), dict( |
|
83 | (('-automagic',), dict( | |
84 | action='store_true', dest='InteractiveShell.automagic', default=NoConfigDefault, |
|
84 | action='store_true', dest='InteractiveShell.automagic', default=NoConfigDefault, | |
85 | help='Turn on the auto calling of magic commands.') |
|
85 | help='Turn on the auto calling of magic commands.') | |
86 | ), |
|
86 | ), | |
87 | (('-noautomagic',), dict( |
|
87 | (('-noautomagic',), dict( | |
88 | action='store_false', dest='InteractiveShell.automagic', default=NoConfigDefault, |
|
88 | action='store_false', dest='InteractiveShell.automagic', default=NoConfigDefault, | |
89 | help='Turn off the auto calling of magic commands.') |
|
89 | help='Turn off the auto calling of magic commands.') | |
90 | ), |
|
90 | ), | |
91 | (('-autoedit_syntax',), dict( |
|
91 | (('-autoedit_syntax',), dict( | |
92 | action='store_true', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault, |
|
92 | action='store_true', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault, | |
93 | help='Turn on auto editing of files with syntax errors.') |
|
93 | help='Turn on auto editing of files with syntax errors.') | |
94 | ), |
|
94 | ), | |
95 | (('-noautoedit_syntax',), dict( |
|
95 | (('-noautoedit_syntax',), dict( | |
96 | action='store_false', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault, |
|
96 | action='store_false', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault, | |
97 | help='Turn off auto editing of files with syntax errors.') |
|
97 | help='Turn off auto editing of files with syntax errors.') | |
98 | ), |
|
98 | ), | |
99 | (('-banner',), dict( |
|
99 | (('-banner',), dict( | |
100 | action='store_true', dest='Global.display_banner', default=NoConfigDefault, |
|
100 | action='store_true', dest='Global.display_banner', default=NoConfigDefault, | |
101 | help='Display a banner upon starting IPython.') |
|
101 | help='Display a banner upon starting IPython.') | |
102 | ), |
|
102 | ), | |
103 | (('-nobanner',), dict( |
|
103 | (('-nobanner',), dict( | |
104 | action='store_false', dest='Global.display_banner', default=NoConfigDefault, |
|
104 | action='store_false', dest='Global.display_banner', default=NoConfigDefault, | |
105 | help="Don't display a banner upon starting IPython.") |
|
105 | help="Don't display a banner upon starting IPython.") | |
106 | ), |
|
106 | ), | |
107 | (('-c',), dict( |
|
|||
108 | type=str, dest='InteractiveShell.c', default=NoConfigDefault, |
|
|||
109 | help="Execute the given command string.", |
|
|||
110 | metavar='InteractiveShell.c') |
|
|||
111 | ), |
|
|||
112 | (('-cache_size',), dict( |
|
107 | (('-cache_size',), dict( | |
113 | type=int, dest='InteractiveShell.cache_size', default=NoConfigDefault, |
|
108 | type=int, dest='InteractiveShell.cache_size', default=NoConfigDefault, | |
114 | help="Set the size of the output cache.", |
|
109 | help="Set the size of the output cache.", | |
115 | metavar='InteractiveShell.cache_size') |
|
110 | metavar='InteractiveShell.cache_size') | |
116 | ), |
|
111 | ), | |
117 | (('-classic',), dict( |
|
112 | (('-classic',), dict( | |
118 | action='store_true', dest='Global.classic', default=NoConfigDefault, |
|
113 | action='store_true', dest='Global.classic', default=NoConfigDefault, | |
119 | help="Gives IPython a similar feel to the classic Python prompt.") |
|
114 | help="Gives IPython a similar feel to the classic Python prompt.") | |
120 | ), |
|
115 | ), | |
121 | (('-colors',), dict( |
|
116 | (('-colors',), dict( | |
122 | type=str, dest='InteractiveShell.colors', default=NoConfigDefault, |
|
117 | type=str, dest='InteractiveShell.colors', default=NoConfigDefault, | |
123 | help="Set the color scheme (NoColor, Linux, and LightBG).", |
|
118 | help="Set the color scheme (NoColor, Linux, and LightBG).", | |
124 | metavar='InteractiveShell.colors') |
|
119 | metavar='InteractiveShell.colors') | |
125 | ), |
|
120 | ), | |
126 | (('-color_info',), dict( |
|
121 | (('-color_info',), dict( | |
127 | action='store_true', dest='InteractiveShell.color_info', default=NoConfigDefault, |
|
122 | action='store_true', dest='InteractiveShell.color_info', default=NoConfigDefault, | |
128 | help="Enable using colors for info related things.") |
|
123 | help="Enable using colors for info related things.") | |
129 | ), |
|
124 | ), | |
130 | (('-nocolor_info',), dict( |
|
125 | (('-nocolor_info',), dict( | |
131 | action='store_false', dest='InteractiveShell.color_info', default=NoConfigDefault, |
|
126 | action='store_false', dest='InteractiveShell.color_info', default=NoConfigDefault, | |
132 | help="Disable using colors for info related things.") |
|
127 | help="Disable using colors for info related things.") | |
133 | ), |
|
128 | ), | |
134 | (('-confirm_exit',), dict( |
|
129 | (('-confirm_exit',), dict( | |
135 | action='store_true', dest='InteractiveShell.confirm_exit', default=NoConfigDefault, |
|
130 | action='store_true', dest='InteractiveShell.confirm_exit', default=NoConfigDefault, | |
136 | help="Prompt the user when existing.") |
|
131 | help="Prompt the user when existing.") | |
137 | ), |
|
132 | ), | |
138 | (('-noconfirm_exit',), dict( |
|
133 | (('-noconfirm_exit',), dict( | |
139 | action='store_false', dest='InteractiveShell.confirm_exit', default=NoConfigDefault, |
|
134 | action='store_false', dest='InteractiveShell.confirm_exit', default=NoConfigDefault, | |
140 | help="Don't prompt the user when existing.") |
|
135 | help="Don't prompt the user when existing.") | |
141 | ), |
|
136 | ), | |
142 | (('-deep_reload',), dict( |
|
137 | (('-deep_reload',), dict( | |
143 | action='store_true', dest='InteractiveShell.deep_reload', default=NoConfigDefault, |
|
138 | action='store_true', dest='InteractiveShell.deep_reload', default=NoConfigDefault, | |
144 | help="Enable deep (recursive) reloading by default.") |
|
139 | help="Enable deep (recursive) reloading by default.") | |
145 | ), |
|
140 | ), | |
146 | (('-nodeep_reload',), dict( |
|
141 | (('-nodeep_reload',), dict( | |
147 | action='store_false', dest='InteractiveShell.deep_reload', default=NoConfigDefault, |
|
142 | action='store_false', dest='InteractiveShell.deep_reload', default=NoConfigDefault, | |
148 | help="Disable deep (recursive) reloading by default.") |
|
143 | help="Disable deep (recursive) reloading by default.") | |
149 | ), |
|
144 | ), | |
150 | (('-editor',), dict( |
|
145 | (('-editor',), dict( | |
151 | type=str, dest='InteractiveShell.editor', default=NoConfigDefault, |
|
146 | type=str, dest='InteractiveShell.editor', default=NoConfigDefault, | |
152 | help="Set the editor used by IPython (default to $EDITOR/vi/notepad).", |
|
147 | help="Set the editor used by IPython (default to $EDITOR/vi/notepad).", | |
153 | metavar='InteractiveShell.editor') |
|
148 | metavar='InteractiveShell.editor') | |
154 | ), |
|
149 | ), | |
155 | (('-log','-l'), dict( |
|
150 | (('-log','-l'), dict( | |
156 | action='store_true', dest='InteractiveShell.logstart', default=NoConfigDefault, |
|
151 | action='store_true', dest='InteractiveShell.logstart', default=NoConfigDefault, | |
157 | help="Start logging to the default file (./ipython_log.py).") |
|
152 | help="Start logging to the default file (./ipython_log.py).") | |
158 | ), |
|
153 | ), | |
159 | (('-logfile','-lf'), dict( |
|
154 | (('-logfile','-lf'), dict( | |
160 | type=str, dest='InteractiveShell.logfile', default=NoConfigDefault, |
|
155 | type=str, dest='InteractiveShell.logfile', default=NoConfigDefault, | |
161 | help="Specify the name of your logfile.", |
|
156 | help="Specify the name of your logfile.", | |
162 | metavar='InteractiveShell.logfile') |
|
157 | metavar='InteractiveShell.logfile') | |
163 | ), |
|
158 | ), | |
164 | (('-logplay','-lp'), dict( |
|
159 | (('-logplay','-lp'), dict( | |
165 | type=str, dest='InteractiveShell.logplay', default=NoConfigDefault, |
|
160 | type=str, dest='InteractiveShell.logplay', default=NoConfigDefault, | |
166 | help="Re-play a log file and then append to it.", |
|
161 | help="Re-play a log file and then append to it.", | |
167 | metavar='InteractiveShell.logplay') |
|
162 | metavar='InteractiveShell.logplay') | |
168 | ), |
|
163 | ), | |
169 | (('-pdb',), dict( |
|
164 | (('-pdb',), dict( | |
170 | action='store_true', dest='InteractiveShell.pdb', default=NoConfigDefault, |
|
165 | action='store_true', dest='InteractiveShell.pdb', default=NoConfigDefault, | |
171 | help="Enable auto calling the pdb debugger after every exception.") |
|
166 | help="Enable auto calling the pdb debugger after every exception.") | |
172 | ), |
|
167 | ), | |
173 | (('-nopdb',), dict( |
|
168 | (('-nopdb',), dict( | |
174 | action='store_false', dest='InteractiveShell.pdb', default=NoConfigDefault, |
|
169 | action='store_false', dest='InteractiveShell.pdb', default=NoConfigDefault, | |
175 | help="Disable auto calling the pdb debugger after every exception.") |
|
170 | help="Disable auto calling the pdb debugger after every exception.") | |
176 | ), |
|
171 | ), | |
177 | (('-pprint',), dict( |
|
172 | (('-pprint',), dict( | |
178 | action='store_true', dest='InteractiveShell.pprint', default=NoConfigDefault, |
|
173 | action='store_true', dest='InteractiveShell.pprint', default=NoConfigDefault, | |
179 | help="Enable auto pretty printing of results.") |
|
174 | help="Enable auto pretty printing of results.") | |
180 | ), |
|
175 | ), | |
181 | (('-nopprint',), dict( |
|
176 | (('-nopprint',), dict( | |
182 | action='store_false', dest='InteractiveShell.pprint', default=NoConfigDefault, |
|
177 | action='store_false', dest='InteractiveShell.pprint', default=NoConfigDefault, | |
183 | help="Disable auto auto pretty printing of results.") |
|
178 | help="Disable auto auto pretty printing of results.") | |
184 | ), |
|
179 | ), | |
185 | (('-prompt_in1','-pi1'), dict( |
|
180 | (('-prompt_in1','-pi1'), dict( | |
186 | type=str, dest='InteractiveShell.prompt_in1', default=NoConfigDefault, |
|
181 | type=str, dest='InteractiveShell.prompt_in1', default=NoConfigDefault, | |
187 | help="Set the main input prompt ('In [\#]: ')", |
|
182 | help="Set the main input prompt ('In [\#]: ')", | |
188 | metavar='InteractiveShell.prompt_in1') |
|
183 | metavar='InteractiveShell.prompt_in1') | |
189 | ), |
|
184 | ), | |
190 | (('-prompt_in2','-pi2'), dict( |
|
185 | (('-prompt_in2','-pi2'), dict( | |
191 | type=str, dest='InteractiveShell.prompt_in2', default=NoConfigDefault, |
|
186 | type=str, dest='InteractiveShell.prompt_in2', default=NoConfigDefault, | |
192 | help="Set the secondary input prompt (' .\D.: ')", |
|
187 | help="Set the secondary input prompt (' .\D.: ')", | |
193 | metavar='InteractiveShell.prompt_in2') |
|
188 | metavar='InteractiveShell.prompt_in2') | |
194 | ), |
|
189 | ), | |
195 | (('-prompt_out','-po'), dict( |
|
190 | (('-prompt_out','-po'), dict( | |
196 | type=str, dest='InteractiveShell.prompt_out', default=NoConfigDefault, |
|
191 | type=str, dest='InteractiveShell.prompt_out', default=NoConfigDefault, | |
197 | help="Set the output prompt ('Out[\#]:')", |
|
192 | help="Set the output prompt ('Out[\#]:')", | |
198 | metavar='InteractiveShell.prompt_out') |
|
193 | metavar='InteractiveShell.prompt_out') | |
199 | ), |
|
194 | ), | |
200 | (('-quick',), dict( |
|
195 | (('-quick',), dict( | |
201 | action='store_true', dest='Global.quick', default=NoConfigDefault, |
|
196 | action='store_true', dest='Global.quick', default=NoConfigDefault, | |
202 | help="Enable quick startup with no config files.") |
|
197 | help="Enable quick startup with no config files.") | |
203 | ), |
|
198 | ), | |
204 | (('-readline',), dict( |
|
199 | (('-readline',), dict( | |
205 | action='store_true', dest='InteractiveShell.readline_use', default=NoConfigDefault, |
|
200 | action='store_true', dest='InteractiveShell.readline_use', default=NoConfigDefault, | |
206 | help="Enable readline for command line usage.") |
|
201 | help="Enable readline for command line usage.") | |
207 | ), |
|
202 | ), | |
208 | (('-noreadline',), dict( |
|
203 | (('-noreadline',), dict( | |
209 | action='store_false', dest='InteractiveShell.readline_use', default=NoConfigDefault, |
|
204 | action='store_false', dest='InteractiveShell.readline_use', default=NoConfigDefault, | |
210 | help="Disable readline for command line usage.") |
|
205 | help="Disable readline for command line usage.") | |
211 | ), |
|
206 | ), | |
212 | (('-screen_length','-sl'), dict( |
|
207 | (('-screen_length','-sl'), dict( | |
213 | type=int, dest='InteractiveShell.screen_length', default=NoConfigDefault, |
|
208 | type=int, dest='InteractiveShell.screen_length', default=NoConfigDefault, | |
214 | help='Number of lines on screen, used to control printing of long strings.', |
|
209 | help='Number of lines on screen, used to control printing of long strings.', | |
215 | metavar='InteractiveShell.screen_length') |
|
210 | metavar='InteractiveShell.screen_length') | |
216 | ), |
|
211 | ), | |
217 | (('-separate_in','-si'), dict( |
|
212 | (('-separate_in','-si'), dict( | |
218 | type=str, dest='InteractiveShell.separate_in', default=NoConfigDefault, |
|
213 | type=str, dest='InteractiveShell.separate_in', default=NoConfigDefault, | |
219 | help="Separator before input prompts. Default '\n'.", |
|
214 | help="Separator before input prompts. Default '\n'.", | |
220 | metavar='InteractiveShell.separate_in') |
|
215 | metavar='InteractiveShell.separate_in') | |
221 | ), |
|
216 | ), | |
222 | (('-separate_out','-so'), dict( |
|
217 | (('-separate_out','-so'), dict( | |
223 | type=str, dest='InteractiveShell.separate_out', default=NoConfigDefault, |
|
218 | type=str, dest='InteractiveShell.separate_out', default=NoConfigDefault, | |
224 | help="Separator before output prompts. Default 0 (nothing).", |
|
219 | help="Separator before output prompts. Default 0 (nothing).", | |
225 | metavar='InteractiveShell.separate_out') |
|
220 | metavar='InteractiveShell.separate_out') | |
226 | ), |
|
221 | ), | |
227 | (('-separate_out2','-so2'), dict( |
|
222 | (('-separate_out2','-so2'), dict( | |
228 | type=str, dest='InteractiveShell.separate_out2', default=NoConfigDefault, |
|
223 | type=str, dest='InteractiveShell.separate_out2', default=NoConfigDefault, | |
229 | help="Separator after output prompts. Default 0 (nonight).", |
|
224 | help="Separator after output prompts. Default 0 (nonight).", | |
230 | metavar='InteractiveShell.separate_out2') |
|
225 | metavar='InteractiveShell.separate_out2') | |
231 | ), |
|
226 | ), | |
232 | (('-nosep',), dict( |
|
227 | (('-nosep',), dict( | |
233 | action='store_true', dest='Global.nosep', default=NoConfigDefault, |
|
228 | action='store_true', dest='Global.nosep', default=NoConfigDefault, | |
234 | help="Eliminate all spacing between prompts.") |
|
229 | help="Eliminate all spacing between prompts.") | |
235 | ), |
|
230 | ), | |
236 | (('-term_title',), dict( |
|
231 | (('-term_title',), dict( | |
237 | action='store_true', dest='InteractiveShell.term_title', default=NoConfigDefault, |
|
232 | action='store_true', dest='InteractiveShell.term_title', default=NoConfigDefault, | |
238 | help="Enable auto setting the terminal title.") |
|
233 | help="Enable auto setting the terminal title.") | |
239 | ), |
|
234 | ), | |
240 | (('-noterm_title',), dict( |
|
235 | (('-noterm_title',), dict( | |
241 | action='store_false', dest='InteractiveShell.term_title', default=NoConfigDefault, |
|
236 | action='store_false', dest='InteractiveShell.term_title', default=NoConfigDefault, | |
242 | help="Disable auto setting the terminal title.") |
|
237 | help="Disable auto setting the terminal title.") | |
243 | ), |
|
238 | ), | |
244 | (('-xmode',), dict( |
|
239 | (('-xmode',), dict( | |
245 | type=str, dest='InteractiveShell.xmode', default=NoConfigDefault, |
|
240 | type=str, dest='InteractiveShell.xmode', default=NoConfigDefault, | |
246 | help="Exception mode ('Plain','Context','Verbose')", |
|
241 | help="Exception mode ('Plain','Context','Verbose')", | |
247 | metavar='InteractiveShell.xmode') |
|
242 | metavar='InteractiveShell.xmode') | |
248 | ), |
|
243 | ), | |
249 | (('-ext',), dict( |
|
244 | (('-ext',), dict( | |
250 | type=str, dest='Global.extra_extension', default=NoConfigDefault, |
|
245 | type=str, dest='Global.extra_extension', default=NoConfigDefault, | |
251 | help="The dotted module name of an IPython extension to load.", |
|
246 | help="The dotted module name of an IPython extension to load.", | |
252 | metavar='Global.extra_extension') |
|
247 | metavar='Global.extra_extension') | |
253 | ), |
|
248 | ), | |
|
249 | (('-c',), dict( | |||
|
250 | type=str, dest='Global.code_to_run', default=NoConfigDefault, | |||
|
251 | help="Execute the given command string.", | |||
|
252 | metavar='Global.code_to_run') | |||
|
253 | ), | |||
|
254 | (('-i',), dict( | |||
|
255 | action='store_true', dest='Global.force_interact', default=NoConfigDefault, | |||
|
256 | help="If running code from the command line, become interactive afterwards.") | |||
|
257 | ), | |||
254 | # These are only here to get the proper deprecation warnings |
|
258 | # These are only here to get the proper deprecation warnings | |
255 | (('-pylab','-wthread','-qthread','-q4thread','-gthread'), dict( |
|
259 | (('-pylab','-wthread','-qthread','-q4thread','-gthread'), dict( | |
256 | action='store_true', dest='Global.threaded_shell', default=NoConfigDefault, |
|
260 | action='store_true', dest='Global.threaded_shell', default=NoConfigDefault, | |
257 | help="These command line flags are deprecated, see the 'gui' magic.") |
|
261 | help="These command line flags are deprecated, see the 'gui' magic.") | |
258 | ), |
|
262 | ), | |
259 | ) |
|
263 | ) | |
260 |
|
264 | |||
261 |
|
265 | |||
262 | class IPythonAppCLConfigLoader(IPythonArgParseConfigLoader): |
|
266 | class IPythonAppCLConfigLoader(IPythonArgParseConfigLoader): | |
263 |
|
267 | |||
264 | arguments = cl_args |
|
268 | arguments = cl_args | |
265 |
|
269 | |||
266 |
|
270 | |||
267 | _default_config_file_name = 'ipython_config.py' |
|
271 | _default_config_file_name = 'ipython_config.py' | |
268 |
|
272 | |||
269 | class IPythonApp(Application): |
|
273 | class IPythonApp(Application): | |
270 | name = 'ipython' |
|
274 | name = 'ipython' | |
271 | config_file_name = _default_config_file_name |
|
275 | config_file_name = _default_config_file_name | |
272 |
|
276 | |||
273 | def create_default_config(self): |
|
277 | def create_default_config(self): | |
274 | super(IPythonApp, self).create_default_config() |
|
278 | super(IPythonApp, self).create_default_config() | |
275 | self.default_config.Global.display_banner=True |
|
279 | self.default_config.Global.display_banner = True | |
|
280 | ||||
|
281 | # If the -c flag is given or a file is given to run at the cmd line | |||
|
282 | # like "ipython foo.py", normally we exit without starting the main | |||
|
283 | # loop. The force_interact config variable allows a user to override | |||
|
284 | # this and interact. It is also set by the -i cmd line flag, just | |||
|
285 | # like Python. | |||
|
286 | self.default_config.Global.force_interact = False | |||
|
287 | # By default always interact by starting the IPython mainloop. | |||
|
288 | self.default_config.Global.interact = True | |||
276 | # Let the parent class set the default, but each time log_level |
|
289 | # Let the parent class set the default, but each time log_level | |
277 | # changes from config, we need to update self.log_level as that is |
|
290 | # changes from config, we need to update self.log_level as that is | |
278 | # what updates the actual log level in self.log. |
|
291 | # what updates the actual log level in self.log. | |
279 | self.default_config.Global.log_level = self.log_level |
|
292 | self.default_config.Global.log_level = self.log_level | |
280 |
|
293 | |||
281 | def create_command_line_config(self): |
|
294 | def create_command_line_config(self): | |
282 | """Create and return a command line config loader.""" |
|
295 | """Create and return a command line config loader.""" | |
283 | return IPythonAppCLConfigLoader( |
|
296 | return IPythonAppCLConfigLoader( | |
284 | description=ipython_desc, |
|
297 | description=ipython_desc, | |
285 | version=release.version) |
|
298 | version=release.version) | |
286 |
|
299 | |||
287 | def post_load_command_line_config(self): |
|
300 | def post_load_command_line_config(self): | |
288 | """Do actions after loading cl config.""" |
|
301 | """Do actions after loading cl config.""" | |
289 | clc = self.command_line_config |
|
302 | clc = self.command_line_config | |
290 |
|
303 | |||
291 | # Display the deprecation warnings about threaded shells |
|
304 | # Display the deprecation warnings about threaded shells | |
292 | if hasattr(clc.Global, 'threaded_shell'): |
|
305 | if hasattr(clc.Global, 'threaded_shell'): | |
293 | threaded_shell_warning() |
|
306 | threaded_shell_warning() | |
294 | del clc.Global['threaded_shell'] |
|
307 | del clc.Global['threaded_shell'] | |
295 |
|
308 | |||
296 | def load_file_config(self): |
|
309 | def load_file_config(self): | |
297 | if hasattr(self.command_line_config.Global, 'quick'): |
|
310 | if hasattr(self.command_line_config.Global, 'quick'): | |
298 | if self.command_line_config.Global.quick: |
|
311 | if self.command_line_config.Global.quick: | |
299 | self.file_config = Config() |
|
312 | self.file_config = Config() | |
300 | return |
|
313 | return | |
301 | super(IPythonApp, self).load_file_config() |
|
314 | super(IPythonApp, self).load_file_config() | |
302 |
|
315 | |||
303 | def post_load_file_config(self): |
|
316 | def post_load_file_config(self): | |
304 | if hasattr(self.command_line_config.Global, 'extra_extension'): |
|
317 | if hasattr(self.command_line_config.Global, 'extra_extension'): | |
305 | if not hasattr(self.file_config.Global, 'extensions'): |
|
318 | if not hasattr(self.file_config.Global, 'extensions'): | |
306 | self.file_config.Global.extensions = [] |
|
319 | self.file_config.Global.extensions = [] | |
307 | self.file_config.Global.extensions.append( |
|
320 | self.file_config.Global.extensions.append( | |
308 | self.command_line_config.Global.extra_extension) |
|
321 | self.command_line_config.Global.extra_extension) | |
309 | del self.command_line_config.Global.extra_extension |
|
322 | del self.command_line_config.Global.extra_extension | |
310 |
|
323 | |||
311 | def pre_construct(self): |
|
324 | def pre_construct(self): | |
312 | config = self.master_config |
|
325 | config = self.master_config | |
313 |
|
326 | |||
314 | if hasattr(config.Global, 'classic'): |
|
327 | if hasattr(config.Global, 'classic'): | |
315 | if config.Global.classic: |
|
328 | if config.Global.classic: | |
316 | config.InteractiveShell.cache_size = 0 |
|
329 | config.InteractiveShell.cache_size = 0 | |
317 | config.InteractiveShell.pprint = 0 |
|
330 | config.InteractiveShell.pprint = 0 | |
318 | config.InteractiveShell.prompt_in1 = '>>> ' |
|
331 | config.InteractiveShell.prompt_in1 = '>>> ' | |
319 | config.InteractiveShell.prompt_in2 = '... ' |
|
332 | config.InteractiveShell.prompt_in2 = '... ' | |
320 | config.InteractiveShell.prompt_out = '' |
|
333 | config.InteractiveShell.prompt_out = '' | |
321 | config.InteractiveShell.separate_in = \ |
|
334 | config.InteractiveShell.separate_in = \ | |
322 | config.InteractiveShell.separate_out = \ |
|
335 | config.InteractiveShell.separate_out = \ | |
323 | config.InteractiveShell.separate_out2 = '' |
|
336 | config.InteractiveShell.separate_out2 = '' | |
324 | config.InteractiveShell.colors = 'NoColor' |
|
337 | config.InteractiveShell.colors = 'NoColor' | |
325 | config.InteractiveShell.xmode = 'Plain' |
|
338 | config.InteractiveShell.xmode = 'Plain' | |
326 |
|
339 | |||
327 | # All this should be moved to traitlet handlers in InteractiveShell |
|
|||
328 | # But, currently InteractiveShell doesn't have support for changing |
|
|||
329 | # these values at runtime. Once we support that, this should |
|
|||
330 | # be moved there!!! |
|
|||
331 | if hasattr(config.Global, 'nosep'): |
|
340 | if hasattr(config.Global, 'nosep'): | |
332 | if config.Global.nosep: |
|
341 | if config.Global.nosep: | |
333 | config.InteractiveShell.separate_in = \ |
|
342 | config.InteractiveShell.separate_in = \ | |
334 | config.InteractiveShell.separate_out = \ |
|
343 | config.InteractiveShell.separate_out = \ | |
335 |
config.InteractiveShell.separate_out2 = ' |
|
344 | config.InteractiveShell.separate_out2 = '' | |
|
345 | ||||
|
346 | # if there is code of files to run from the cmd line, don't interact | |||
|
347 | # unless the -i flag (Global.force_interact) is true. | |||
|
348 | code_to_run = config.Global.get('code_to_run','') | |||
|
349 | file_to_run = False | |||
|
350 | if len(self.extra_args)>=1: | |||
|
351 | if self.extra_args[0]: | |||
|
352 | file_to_run = True | |||
|
353 | if file_to_run or code_to_run: | |||
|
354 | if not config.Global.force_interact: | |||
|
355 | config.Global.interact = False | |||
336 |
|
356 | |||
337 | def construct(self): |
|
357 | def construct(self): | |
338 | # I am a little hesitant to put these into InteractiveShell itself. |
|
358 | # I am a little hesitant to put these into InteractiveShell itself. | |
339 | # But that might be the place for them |
|
359 | # But that might be the place for them | |
340 | sys.path.insert(0, '') |
|
360 | sys.path.insert(0, '') | |
341 |
|
361 | |||
342 | # Create an InteractiveShell instance |
|
362 | # Create an InteractiveShell instance | |
343 | self.shell = InteractiveShell( |
|
363 | self.shell = InteractiveShell( | |
344 | parent=None, |
|
364 | parent=None, | |
345 | config=self.master_config |
|
365 | config=self.master_config | |
346 | ) |
|
366 | ) | |
347 |
|
367 | |||
348 | def post_construct(self): |
|
368 | def post_construct(self): | |
349 | """Do actions after construct, but before starting the app.""" |
|
369 | """Do actions after construct, but before starting the app.""" | |
350 | # shell.display_banner should always be False for the terminal |
|
370 | # shell.display_banner should always be False for the terminal | |
351 | # based app, because we call shell.show_banner() by hand below |
|
371 | # based app, because we call shell.show_banner() by hand below | |
352 | # so the banner shows *before* all extension loading stuff. |
|
372 | # so the banner shows *before* all extension loading stuff. | |
353 | self.shell.display_banner = False |
|
373 | self.shell.display_banner = False | |
354 |
|
374 | |||
355 |
if self.master_config.Global.display_banner |
|
375 | if self.master_config.Global.display_banner and \ | |
|
376 | self.master_config.Global.interact: | |||
356 | self.shell.show_banner() |
|
377 | self.shell.show_banner() | |
357 |
|
378 | |||
358 | # Make sure there is a space below the banner. |
|
379 | # Make sure there is a space below the banner. | |
359 | if self.log_level <= logging.INFO: print |
|
380 | if self.log_level <= logging.INFO: print | |
360 |
|
381 | |||
361 | self._load_extensions() |
|
382 | self._load_extensions() | |
362 | self._run_exec_lines() |
|
383 | self._run_exec_lines() | |
363 | self._run_exec_files() |
|
384 | self._run_exec_files() | |
|
385 | self._run_cmd_line_code() | |||
364 |
|
386 | |||
365 | def _load_extensions(self): |
|
387 | def _load_extensions(self): | |
366 | """Load all IPython extensions in Global.extensions. |
|
388 | """Load all IPython extensions in Global.extensions. | |
367 |
|
389 | |||
368 | This uses the :meth:`InteractiveShell.load_extensions` to load all |
|
390 | This uses the :meth:`InteractiveShell.load_extensions` to load all | |
369 | the extensions listed in ``self.master_config.Global.extensions``. |
|
391 | the extensions listed in ``self.master_config.Global.extensions``. | |
370 | """ |
|
392 | """ | |
371 | try: |
|
393 | try: | |
372 | if hasattr(self.master_config.Global, 'extensions'): |
|
394 | if hasattr(self.master_config.Global, 'extensions'): | |
373 | self.log.debug("Loading IPython extensions...") |
|
395 | self.log.debug("Loading IPython extensions...") | |
374 | extensions = self.master_config.Global.extensions |
|
396 | extensions = self.master_config.Global.extensions | |
375 | for ext in extensions: |
|
397 | for ext in extensions: | |
376 | try: |
|
398 | try: | |
377 | self.log.info("Loading IPython extension: %s" % ext) |
|
399 | self.log.info("Loading IPython extension: %s" % ext) | |
378 | self.shell.load_extension(ext) |
|
400 | self.shell.load_extension(ext) | |
379 | except: |
|
401 | except: | |
380 | self.log.warn("Error in loading extension: %s" % ext) |
|
402 | self.log.warn("Error in loading extension: %s" % ext) | |
381 | self.shell.showtraceback() |
|
403 | self.shell.showtraceback() | |
382 | except: |
|
404 | except: | |
383 | self.log.warn("Unknown error in loading extensions:") |
|
405 | self.log.warn("Unknown error in loading extensions:") | |
384 | self.shell.showtraceback() |
|
406 | self.shell.showtraceback() | |
385 |
|
407 | |||
386 | def _run_exec_lines(self): |
|
408 | def _run_exec_lines(self): | |
387 | """Run lines of code in Global.exec_lines in the user's namespace.""" |
|
409 | """Run lines of code in Global.exec_lines in the user's namespace.""" | |
388 | try: |
|
410 | try: | |
389 | if hasattr(self.master_config.Global, 'exec_lines'): |
|
411 | if hasattr(self.master_config.Global, 'exec_lines'): | |
390 | self.log.debug("Running code from Global.exec_lines...") |
|
412 | self.log.debug("Running code from Global.exec_lines...") | |
391 | exec_lines = self.master_config.Global.exec_lines |
|
413 | exec_lines = self.master_config.Global.exec_lines | |
392 | for line in exec_lines: |
|
414 | for line in exec_lines: | |
393 | try: |
|
415 | try: | |
394 | self.log.info("Running code in user namespace: %s" % line) |
|
416 | self.log.info("Running code in user namespace: %s" % line) | |
395 | self.shell.runlines(line) |
|
417 | self.shell.runlines(line) | |
396 | except: |
|
418 | except: | |
397 | self.log.warn("Error in executing line in user namespace: %s" % line) |
|
419 | self.log.warn("Error in executing line in user namespace: %s" % line) | |
398 | self.shell.showtraceback() |
|
420 | self.shell.showtraceback() | |
399 | except: |
|
421 | except: | |
400 | self.log.warn("Unknown error in handling Global.exec_lines:") |
|
422 | self.log.warn("Unknown error in handling Global.exec_lines:") | |
401 | self.shell.showtraceback() |
|
423 | self.shell.showtraceback() | |
402 |
|
424 | |||
|
425 | def _exec_file(self, fname): | |||
|
426 | full_filename = filefind(fname, ['.', self.ipythondir]) | |||
|
427 | if os.path.isfile(full_filename): | |||
|
428 | if full_filename.endswith('.py'): | |||
|
429 | self.log.info("Running file in user namespace: %s" % full_filename) | |||
|
430 | self.shell.safe_execfile(full_filename, self.shell.user_ns) | |||
|
431 | elif full_filename.endswith('.ipy'): | |||
|
432 | self.log.info("Running file in user namespace: %s" % full_filename) | |||
|
433 | self.shell.safe_execfile_ipy(full_filename) | |||
|
434 | else: | |||
|
435 | self.log.warn("File does not have a .py or .ipy extension: <%s>" % full_filename) | |||
|
436 | ||||
403 | def _run_exec_files(self): |
|
437 | def _run_exec_files(self): | |
404 | try: |
|
438 | try: | |
405 | if hasattr(self.master_config.Global, 'exec_files'): |
|
439 | if hasattr(self.master_config.Global, 'exec_files'): | |
406 | self.log.debug("Running files in Global.exec_files...") |
|
440 | self.log.debug("Running files in Global.exec_files...") | |
407 | exec_files = self.master_config.Global.exec_files |
|
441 | exec_files = self.master_config.Global.exec_files | |
408 | for fname in exec_files: |
|
442 | for fname in exec_files: | |
409 | full_filename = filefind(fname, ['.', self.ipythondir]) |
|
443 | self._exec_file(fname) | |
410 | if os.path.isfile(full_filename): |
|
|||
411 | if full_filename.endswith('.py'): |
|
|||
412 | self.log.info("Running file in user namespace: %s" % full_filename) |
|
|||
413 | self.shell.safe_execfile(full_filename, self.shell.user_ns) |
|
|||
414 | elif full_filename.endswith('.ipy'): |
|
|||
415 | self.log.info("Running file in user namespace: %s" % full_filename) |
|
|||
416 | self.shell.safe_execfile_ipy(full_filename) |
|
|||
417 | else: |
|
|||
418 | self.log.warn("File does not have a .py or .ipy extension: <%s>" % full_filename) |
|
|||
419 | except: |
|
444 | except: | |
420 | self.log.warn("Unknown error in handling Global.exec_files:") |
|
445 | self.log.warn("Unknown error in handling Global.exec_files:") | |
421 | self.shell.showtraceback() |
|
446 | self.shell.showtraceback() | |
422 |
|
447 | |||
|
448 | def _run_cmd_line_code(self): | |||
|
449 | if hasattr(self.master_config.Global, 'code_to_run'): | |||
|
450 | line = self.master_config.Global.code_to_run | |||
|
451 | try: | |||
|
452 | self.log.info("Running code given at command line (-c): %s" % line) | |||
|
453 | self.shell.runlines(line) | |||
|
454 | except: | |||
|
455 | self.log.warn("Error in executing line in user namespace: %s" % line) | |||
|
456 | self.shell.showtraceback() | |||
|
457 | return | |||
|
458 | # Like Python itself, ignore the second if the first of these is present | |||
|
459 | try: | |||
|
460 | fname = self.extra_args[0] | |||
|
461 | except: | |||
|
462 | pass | |||
|
463 | else: | |||
|
464 | try: | |||
|
465 | self._exec_file(fname) | |||
|
466 | except: | |||
|
467 | self.log.warn("Error in executing file in user namespace: %s" % fname) | |||
|
468 | self.shell.showtraceback() | |||
|
469 | ||||
423 | def start_app(self): |
|
470 | def start_app(self): | |
424 | self.log.debug("Starting IPython's mainloop...") |
|
471 | if self.master_config.Global.interact: | |
425 | self.shell.mainloop() |
|
472 | self.log.debug("Starting IPython's mainloop...") | |
|
473 | self.shell.mainloop() | |||
426 |
|
474 | |||
427 |
|
475 | |||
428 | def load_default_config(ipythondir=None): |
|
476 | def load_default_config(ipythondir=None): | |
429 | """Load the default config file from the default ipythondir. |
|
477 | """Load the default config file from the default ipythondir. | |
430 |
|
478 | |||
431 | This is useful for embedded shells. |
|
479 | This is useful for embedded shells. | |
432 | """ |
|
480 | """ | |
433 | if ipythondir is None: |
|
481 | if ipythondir is None: | |
434 | ipythondir = get_ipython_dir() |
|
482 | ipythondir = get_ipython_dir() | |
435 | cl = PyFileConfigLoader(_default_config_file_name, ipythondir) |
|
483 | cl = PyFileConfigLoader(_default_config_file_name, ipythondir) | |
436 | config = cl.load_config() |
|
484 | config = cl.load_config() | |
437 | return config |
|
485 | return config | |
438 |
|
486 | |||
439 |
|
487 | |||
440 | if __name__ == '__main__': |
|
488 | if __name__ == '__main__': | |
441 | app = IPythonApp() |
|
489 | app = IPythonApp() | |
442 | app.start() No newline at end of file |
|
490 | app.start() |
@@ -1,2480 +1,2448 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | Main IPython Component |
|
3 | Main IPython Component | |
4 | """ |
|
4 | """ | |
5 |
|
5 | |||
6 | #----------------------------------------------------------------------------- |
|
6 | #----------------------------------------------------------------------------- | |
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> | |
8 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
8 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
9 | # Copyright (C) 2008-2009 The IPython Development Team |
|
9 | # Copyright (C) 2008-2009 The IPython Development Team | |
10 | # |
|
10 | # | |
11 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | # Distributed under the terms of the BSD License. The full license is in | |
12 | # the file COPYING, distributed as part of this software. |
|
12 | # the file COPYING, distributed as part of this software. | |
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 |
|
14 | |||
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 | # Imports |
|
16 | # Imports | |
17 | #----------------------------------------------------------------------------- |
|
17 | #----------------------------------------------------------------------------- | |
18 |
|
18 | |||
19 | from __future__ import with_statement |
|
19 | from __future__ import with_statement | |
20 |
|
20 | |||
21 | import __builtin__ |
|
21 | import __builtin__ | |
22 | import StringIO |
|
22 | import StringIO | |
23 | import bdb |
|
23 | import bdb | |
24 | import codeop |
|
24 | import codeop | |
25 | import exceptions |
|
25 | import exceptions | |
26 | import new |
|
26 | import new | |
27 | import os |
|
27 | import os | |
28 | import re |
|
28 | import re | |
29 | import string |
|
29 | import string | |
30 | import sys |
|
30 | import sys | |
31 | import tempfile |
|
31 | import tempfile | |
32 | from contextlib import nested |
|
32 | from contextlib import nested | |
33 |
|
33 | |||
34 | from IPython.core import ultratb |
|
34 | from IPython.core import ultratb | |
35 | from IPython.core import debugger, oinspect |
|
35 | from IPython.core import debugger, oinspect | |
36 | from IPython.core import shadowns |
|
36 | from IPython.core import shadowns | |
37 | from IPython.core import history as ipcorehist |
|
37 | from IPython.core import history as ipcorehist | |
38 | from IPython.core import prefilter |
|
38 | from IPython.core import prefilter | |
39 | from IPython.core.alias import AliasManager |
|
39 | from IPython.core.alias import AliasManager | |
40 | from IPython.core.builtin_trap import BuiltinTrap |
|
40 | from IPython.core.builtin_trap import BuiltinTrap | |
41 | from IPython.core.display_trap import DisplayTrap |
|
41 | from IPython.core.display_trap import DisplayTrap | |
42 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
42 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict | |
43 | from IPython.core.logger import Logger |
|
43 | from IPython.core.logger import Logger | |
44 | from IPython.core.magic import Magic |
|
44 | from IPython.core.magic import Magic | |
45 | from IPython.core.prompts import CachedOutput |
|
45 | from IPython.core.prompts import CachedOutput | |
46 | from IPython.core.prefilter import PrefilterManager |
|
46 | from IPython.core.prefilter import PrefilterManager | |
47 | from IPython.core.component import Component |
|
47 | from IPython.core.component import Component | |
48 | from IPython.core.usage import interactive_usage, default_banner |
|
48 | from IPython.core.usage import interactive_usage, default_banner | |
49 | from IPython.core.error import TryNext, UsageError |
|
49 | from IPython.core.error import TryNext, UsageError | |
50 |
|
50 | |||
51 | from IPython.extensions import pickleshare |
|
51 | from IPython.extensions import pickleshare | |
52 | from IPython.external.Itpl import ItplNS |
|
52 | from IPython.external.Itpl import ItplNS | |
53 | from IPython.lib.backgroundjobs import BackgroundJobManager |
|
53 | from IPython.lib.backgroundjobs import BackgroundJobManager | |
54 | from IPython.utils.ipstruct import Struct |
|
54 | from IPython.utils.ipstruct import Struct | |
55 | from IPython.utils import PyColorize |
|
55 | from IPython.utils import PyColorize | |
56 | from IPython.utils.genutils import * |
|
56 | from IPython.utils.genutils import * | |
57 | from IPython.utils.genutils import get_ipython_dir |
|
57 | from IPython.utils.genutils import get_ipython_dir | |
58 | from IPython.utils.platutils import toggle_set_term_title, set_term_title |
|
58 | from IPython.utils.platutils import toggle_set_term_title, set_term_title | |
59 | from IPython.utils.strdispatch import StrDispatch |
|
59 | from IPython.utils.strdispatch import StrDispatch | |
60 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
60 | from IPython.utils.syspathcontext import prepended_to_syspath | |
61 |
|
61 | |||
62 | # from IPython.utils import growl |
|
62 | # from IPython.utils import growl | |
63 | # growl.start("IPython") |
|
63 | # growl.start("IPython") | |
64 |
|
64 | |||
65 | from IPython.utils.traitlets import ( |
|
65 | from IPython.utils.traitlets import ( | |
66 | Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode |
|
66 | Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode | |
67 | ) |
|
67 | ) | |
68 |
|
68 | |||
69 | #----------------------------------------------------------------------------- |
|
69 | #----------------------------------------------------------------------------- | |
70 | # Globals |
|
70 | # Globals | |
71 | #----------------------------------------------------------------------------- |
|
71 | #----------------------------------------------------------------------------- | |
72 |
|
72 | |||
73 |
|
73 | |||
74 | # store the builtin raw_input globally, and use this always, in case user code |
|
74 | # store the builtin raw_input globally, and use this always, in case user code | |
75 | # overwrites it (like wx.py.PyShell does) |
|
75 | # overwrites it (like wx.py.PyShell does) | |
76 | raw_input_original = raw_input |
|
76 | raw_input_original = raw_input | |
77 |
|
77 | |||
78 | # compiled regexps for autoindent management |
|
78 | # compiled regexps for autoindent management | |
79 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
79 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
80 |
|
80 | |||
81 |
|
81 | |||
82 | #----------------------------------------------------------------------------- |
|
82 | #----------------------------------------------------------------------------- | |
83 | # Utilities |
|
83 | # Utilities | |
84 | #----------------------------------------------------------------------------- |
|
84 | #----------------------------------------------------------------------------- | |
85 |
|
85 | |||
86 |
|
86 | |||
87 | ini_spaces_re = re.compile(r'^(\s+)') |
|
87 | ini_spaces_re = re.compile(r'^(\s+)') | |
88 |
|
88 | |||
89 |
|
89 | |||
90 | def num_ini_spaces(strng): |
|
90 | def num_ini_spaces(strng): | |
91 | """Return the number of initial spaces in a string""" |
|
91 | """Return the number of initial spaces in a string""" | |
92 |
|
92 | |||
93 | ini_spaces = ini_spaces_re.match(strng) |
|
93 | ini_spaces = ini_spaces_re.match(strng) | |
94 | if ini_spaces: |
|
94 | if ini_spaces: | |
95 | return ini_spaces.end() |
|
95 | return ini_spaces.end() | |
96 | else: |
|
96 | else: | |
97 | return 0 |
|
97 | return 0 | |
98 |
|
98 | |||
99 |
|
99 | |||
100 | def softspace(file, newvalue): |
|
100 | def softspace(file, newvalue): | |
101 | """Copied from code.py, to remove the dependency""" |
|
101 | """Copied from code.py, to remove the dependency""" | |
102 |
|
102 | |||
103 | oldvalue = 0 |
|
103 | oldvalue = 0 | |
104 | try: |
|
104 | try: | |
105 | oldvalue = file.softspace |
|
105 | oldvalue = file.softspace | |
106 | except AttributeError: |
|
106 | except AttributeError: | |
107 | pass |
|
107 | pass | |
108 | try: |
|
108 | try: | |
109 | file.softspace = newvalue |
|
109 | file.softspace = newvalue | |
110 | except (AttributeError, TypeError): |
|
110 | except (AttributeError, TypeError): | |
111 | # "attribute-less object" or "read-only attributes" |
|
111 | # "attribute-less object" or "read-only attributes" | |
112 | pass |
|
112 | pass | |
113 | return oldvalue |
|
113 | return oldvalue | |
114 |
|
114 | |||
115 |
|
115 | |||
116 | class SpaceInInput(exceptions.Exception): pass |
|
116 | class SpaceInInput(exceptions.Exception): pass | |
117 |
|
117 | |||
118 | class Bunch: pass |
|
118 | class Bunch: pass | |
119 |
|
119 | |||
120 | class InputList(list): |
|
120 | class InputList(list): | |
121 | """Class to store user input. |
|
121 | """Class to store user input. | |
122 |
|
122 | |||
123 | It's basically a list, but slices return a string instead of a list, thus |
|
123 | It's basically a list, but slices return a string instead of a list, thus | |
124 | allowing things like (assuming 'In' is an instance): |
|
124 | allowing things like (assuming 'In' is an instance): | |
125 |
|
125 | |||
126 | exec In[4:7] |
|
126 | exec In[4:7] | |
127 |
|
127 | |||
128 | or |
|
128 | or | |
129 |
|
129 | |||
130 | exec In[5:9] + In[14] + In[21:25]""" |
|
130 | exec In[5:9] + In[14] + In[21:25]""" | |
131 |
|
131 | |||
132 | def __getslice__(self,i,j): |
|
132 | def __getslice__(self,i,j): | |
133 | return ''.join(list.__getslice__(self,i,j)) |
|
133 | return ''.join(list.__getslice__(self,i,j)) | |
134 |
|
134 | |||
135 |
|
135 | |||
136 | class SyntaxTB(ultratb.ListTB): |
|
136 | class SyntaxTB(ultratb.ListTB): | |
137 | """Extension which holds some state: the last exception value""" |
|
137 | """Extension which holds some state: the last exception value""" | |
138 |
|
138 | |||
139 | def __init__(self,color_scheme = 'NoColor'): |
|
139 | def __init__(self,color_scheme = 'NoColor'): | |
140 | ultratb.ListTB.__init__(self,color_scheme) |
|
140 | ultratb.ListTB.__init__(self,color_scheme) | |
141 | self.last_syntax_error = None |
|
141 | self.last_syntax_error = None | |
142 |
|
142 | |||
143 | def __call__(self, etype, value, elist): |
|
143 | def __call__(self, etype, value, elist): | |
144 | self.last_syntax_error = value |
|
144 | self.last_syntax_error = value | |
145 | ultratb.ListTB.__call__(self,etype,value,elist) |
|
145 | ultratb.ListTB.__call__(self,etype,value,elist) | |
146 |
|
146 | |||
147 | def clear_err_state(self): |
|
147 | def clear_err_state(self): | |
148 | """Return the current error state and clear it""" |
|
148 | """Return the current error state and clear it""" | |
149 | e = self.last_syntax_error |
|
149 | e = self.last_syntax_error | |
150 | self.last_syntax_error = None |
|
150 | self.last_syntax_error = None | |
151 | return e |
|
151 | return e | |
152 |
|
152 | |||
153 |
|
153 | |||
154 | def get_default_editor(): |
|
154 | def get_default_editor(): | |
155 | try: |
|
155 | try: | |
156 | ed = os.environ['EDITOR'] |
|
156 | ed = os.environ['EDITOR'] | |
157 | except KeyError: |
|
157 | except KeyError: | |
158 | if os.name == 'posix': |
|
158 | if os.name == 'posix': | |
159 | ed = 'vi' # the only one guaranteed to be there! |
|
159 | ed = 'vi' # the only one guaranteed to be there! | |
160 | else: |
|
160 | else: | |
161 | ed = 'notepad' # same in Windows! |
|
161 | ed = 'notepad' # same in Windows! | |
162 | return ed |
|
162 | return ed | |
163 |
|
163 | |||
164 |
|
164 | |||
165 | class SeparateStr(Str): |
|
165 | class SeparateStr(Str): | |
166 | """A Str subclass to validate separate_in, separate_out, etc. |
|
166 | """A Str subclass to validate separate_in, separate_out, etc. | |
167 |
|
167 | |||
168 | This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'. |
|
168 | This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'. | |
169 | """ |
|
169 | """ | |
170 |
|
170 | |||
171 | def validate(self, obj, value): |
|
171 | def validate(self, obj, value): | |
172 | if value == '0': value = '' |
|
172 | if value == '0': value = '' | |
173 | value = value.replace('\\n','\n') |
|
173 | value = value.replace('\\n','\n') | |
174 | return super(SeparateStr, self).validate(obj, value) |
|
174 | return super(SeparateStr, self).validate(obj, value) | |
175 |
|
175 | |||
176 |
|
176 | |||
177 | #----------------------------------------------------------------------------- |
|
177 | #----------------------------------------------------------------------------- | |
178 | # Main IPython class |
|
178 | # Main IPython class | |
179 | #----------------------------------------------------------------------------- |
|
179 | #----------------------------------------------------------------------------- | |
180 |
|
180 | |||
181 |
|
181 | |||
182 | class InteractiveShell(Component, Magic): |
|
182 | class InteractiveShell(Component, Magic): | |
183 | """An enhanced, interactive shell for Python.""" |
|
183 | """An enhanced, interactive shell for Python.""" | |
184 |
|
184 | |||
185 | autocall = Enum((0,1,2), config=True) |
|
185 | autocall = Enum((0,1,2), config=True) | |
186 | autoedit_syntax = CBool(False, config=True) |
|
186 | autoedit_syntax = CBool(False, config=True) | |
187 | autoindent = CBool(True, config=True) |
|
187 | autoindent = CBool(True, config=True) | |
188 | automagic = CBool(True, config=True) |
|
188 | automagic = CBool(True, config=True) | |
189 | banner = Str('') |
|
189 | banner = Str('') | |
190 | banner1 = Str(default_banner, config=True) |
|
190 | banner1 = Str(default_banner, config=True) | |
191 | banner2 = Str('', config=True) |
|
191 | banner2 = Str('', config=True) | |
192 | c = Str('', config=True) |
|
|||
193 | cache_size = Int(1000, config=True) |
|
192 | cache_size = Int(1000, config=True) | |
194 | color_info = CBool(True, config=True) |
|
193 | color_info = CBool(True, config=True) | |
195 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
194 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), | |
196 | default_value='LightBG', config=True) |
|
195 | default_value='LightBG', config=True) | |
197 | confirm_exit = CBool(True, config=True) |
|
196 | confirm_exit = CBool(True, config=True) | |
198 | debug = CBool(False, config=True) |
|
197 | debug = CBool(False, config=True) | |
199 | deep_reload = CBool(False, config=True) |
|
198 | deep_reload = CBool(False, config=True) | |
200 | # This display_banner only controls whether or not self.show_banner() |
|
199 | # This display_banner only controls whether or not self.show_banner() | |
201 | # is called when mainloop/interact are called. The default is False |
|
200 | # is called when mainloop/interact are called. The default is False | |
202 | # because for the terminal based application, the banner behavior |
|
201 | # because for the terminal based application, the banner behavior | |
203 | # is controlled by Global.display_banner, which IPythonApp looks at |
|
202 | # is controlled by Global.display_banner, which IPythonApp looks at | |
204 | # to determine if *it* should call show_banner() by hand or not. |
|
203 | # to determine if *it* should call show_banner() by hand or not. | |
205 | display_banner = CBool(False) # This isn't configurable! |
|
204 | display_banner = CBool(False) # This isn't configurable! | |
206 | embedded = CBool(False) |
|
205 | embedded = CBool(False) | |
207 | embedded_active = CBool(False) |
|
206 | embedded_active = CBool(False) | |
208 | editor = Str(get_default_editor(), config=True) |
|
207 | editor = Str(get_default_editor(), config=True) | |
209 | filename = Str("<ipython console>") |
|
208 | filename = Str("<ipython console>") | |
210 | interactive = CBool(False, config=True) |
|
|||
211 | ipythondir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ |
|
209 | ipythondir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ | |
212 | logstart = CBool(False, config=True) |
|
210 | logstart = CBool(False, config=True) | |
213 | logfile = Str('', config=True) |
|
211 | logfile = Str('', config=True) | |
214 | logplay = Str('', config=True) |
|
212 | logplay = Str('', config=True) | |
215 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
213 | object_info_string_level = Enum((0,1,2), default_value=0, | |
216 | config=True) |
|
214 | config=True) | |
217 | pager = Str('less', config=True) |
|
215 | pager = Str('less', config=True) | |
218 | pdb = CBool(False, config=True) |
|
216 | pdb = CBool(False, config=True) | |
219 | pprint = CBool(True, config=True) |
|
217 | pprint = CBool(True, config=True) | |
220 | profile = Str('', config=True) |
|
218 | profile = Str('', config=True) | |
221 | prompt_in1 = Str('In [\\#]: ', config=True) |
|
219 | prompt_in1 = Str('In [\\#]: ', config=True) | |
222 | prompt_in2 = Str(' .\\D.: ', config=True) |
|
220 | prompt_in2 = Str(' .\\D.: ', config=True) | |
223 | prompt_out = Str('Out[\\#]: ', config=True) |
|
221 | prompt_out = Str('Out[\\#]: ', config=True) | |
224 | prompts_pad_left = CBool(True, config=True) |
|
222 | prompts_pad_left = CBool(True, config=True) | |
225 | quiet = CBool(False, config=True) |
|
223 | quiet = CBool(False, config=True) | |
226 |
|
224 | |||
227 | readline_use = CBool(True, config=True) |
|
225 | readline_use = CBool(True, config=True) | |
228 | readline_merge_completions = CBool(True, config=True) |
|
226 | readline_merge_completions = CBool(True, config=True) | |
229 | readline_omit__names = Enum((0,1,2), default_value=0, config=True) |
|
227 | readline_omit__names = Enum((0,1,2), default_value=0, config=True) | |
230 | readline_remove_delims = Str('-/~', config=True) |
|
228 | readline_remove_delims = Str('-/~', config=True) | |
231 | readline_parse_and_bind = List([ |
|
229 | readline_parse_and_bind = List([ | |
232 | 'tab: complete', |
|
230 | 'tab: complete', | |
233 | '"\C-l": possible-completions', |
|
231 | '"\C-l": possible-completions', | |
234 | 'set show-all-if-ambiguous on', |
|
232 | 'set show-all-if-ambiguous on', | |
235 | '"\C-o": tab-insert', |
|
233 | '"\C-o": tab-insert', | |
236 | '"\M-i": " "', |
|
234 | '"\M-i": " "', | |
237 | '"\M-o": "\d\d\d\d"', |
|
235 | '"\M-o": "\d\d\d\d"', | |
238 | '"\M-I": "\d\d\d\d"', |
|
236 | '"\M-I": "\d\d\d\d"', | |
239 | '"\C-r": reverse-search-history', |
|
237 | '"\C-r": reverse-search-history', | |
240 | '"\C-s": forward-search-history', |
|
238 | '"\C-s": forward-search-history', | |
241 | '"\C-p": history-search-backward', |
|
239 | '"\C-p": history-search-backward', | |
242 | '"\C-n": history-search-forward', |
|
240 | '"\C-n": history-search-forward', | |
243 | '"\e[A": history-search-backward', |
|
241 | '"\e[A": history-search-backward', | |
244 | '"\e[B": history-search-forward', |
|
242 | '"\e[B": history-search-forward', | |
245 | '"\C-k": kill-line', |
|
243 | '"\C-k": kill-line', | |
246 | '"\C-u": unix-line-discard', |
|
244 | '"\C-u": unix-line-discard', | |
247 | ], allow_none=False, config=True) |
|
245 | ], allow_none=False, config=True) | |
248 |
|
246 | |||
249 | screen_length = Int(0, config=True) |
|
247 | screen_length = Int(0, config=True) | |
250 |
|
248 | |||
251 | # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n' |
|
249 | # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n' | |
252 | separate_in = SeparateStr('\n', config=True) |
|
250 | separate_in = SeparateStr('\n', config=True) | |
253 | separate_out = SeparateStr('', config=True) |
|
251 | separate_out = SeparateStr('', config=True) | |
254 | separate_out2 = SeparateStr('', config=True) |
|
252 | separate_out2 = SeparateStr('', config=True) | |
255 |
|
253 | |||
256 | system_header = Str('IPython system call: ', config=True) |
|
254 | system_header = Str('IPython system call: ', config=True) | |
257 | system_verbose = CBool(False, config=True) |
|
255 | system_verbose = CBool(False, config=True) | |
258 | term_title = CBool(False, config=True) |
|
256 | term_title = CBool(False, config=True) | |
259 | wildcards_case_sensitive = CBool(True, config=True) |
|
257 | wildcards_case_sensitive = CBool(True, config=True) | |
260 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
258 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), | |
261 | default_value='Context', config=True) |
|
259 | default_value='Context', config=True) | |
262 |
|
260 | |||
263 | autoexec = List(allow_none=False) |
|
261 | autoexec = List(allow_none=False) | |
264 |
|
262 | |||
265 | # class attribute to indicate whether the class supports threads or not. |
|
263 | # class attribute to indicate whether the class supports threads or not. | |
266 | # Subclasses with thread support should override this as needed. |
|
264 | # Subclasses with thread support should override this as needed. | |
267 | isthreaded = False |
|
265 | isthreaded = False | |
268 |
|
266 | |||
269 | def __init__(self, parent=None, config=None, ipythondir=None, usage=None, |
|
267 | def __init__(self, parent=None, config=None, ipythondir=None, usage=None, | |
270 | user_ns=None, user_global_ns=None, |
|
268 | user_ns=None, user_global_ns=None, | |
271 | banner1=None, banner2=None, display_banner=None, |
|
269 | banner1=None, banner2=None, display_banner=None, | |
272 | custom_exceptions=((),None)): |
|
270 | custom_exceptions=((),None)): | |
273 |
|
271 | |||
274 | # This is where traitlets with a config_key argument are updated |
|
272 | # This is where traitlets with a config_key argument are updated | |
275 | # from the values on config. |
|
273 | # from the values on config. | |
276 | super(InteractiveShell, self).__init__(parent, config=config) |
|
274 | super(InteractiveShell, self).__init__(parent, config=config) | |
277 |
|
275 | |||
278 | # These are relatively independent and stateless |
|
276 | # These are relatively independent and stateless | |
279 | self.init_ipythondir(ipythondir) |
|
277 | self.init_ipythondir(ipythondir) | |
280 | self.init_instance_attrs() |
|
278 | self.init_instance_attrs() | |
281 | self.init_term_title() |
|
279 | self.init_term_title() | |
282 | self.init_usage(usage) |
|
280 | self.init_usage(usage) | |
283 | self.init_banner(banner1, banner2, display_banner) |
|
281 | self.init_banner(banner1, banner2, display_banner) | |
284 |
|
282 | |||
285 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
283 | # Create namespaces (user_ns, user_global_ns, etc.) | |
286 | self.init_create_namespaces(user_ns, user_global_ns) |
|
284 | self.init_create_namespaces(user_ns, user_global_ns) | |
287 | # This has to be done after init_create_namespaces because it uses |
|
285 | # This has to be done after init_create_namespaces because it uses | |
288 | # something in self.user_ns, but before init_sys_modules, which |
|
286 | # something in self.user_ns, but before init_sys_modules, which | |
289 | # is the first thing to modify sys. |
|
287 | # is the first thing to modify sys. | |
290 | self.save_sys_module_state() |
|
288 | self.save_sys_module_state() | |
291 | self.init_sys_modules() |
|
289 | self.init_sys_modules() | |
292 |
|
290 | |||
293 | self.init_history() |
|
291 | self.init_history() | |
294 | self.init_encoding() |
|
292 | self.init_encoding() | |
295 | self.init_prefilter() |
|
293 | self.init_prefilter() | |
296 |
|
294 | |||
297 | Magic.__init__(self, self) |
|
295 | Magic.__init__(self, self) | |
298 |
|
296 | |||
299 | self.init_syntax_highlighting() |
|
297 | self.init_syntax_highlighting() | |
300 | self.init_hooks() |
|
298 | self.init_hooks() | |
301 | self.init_pushd_popd_magic() |
|
299 | self.init_pushd_popd_magic() | |
302 | self.init_traceback_handlers(custom_exceptions) |
|
300 | self.init_traceback_handlers(custom_exceptions) | |
303 | self.init_user_ns() |
|
301 | self.init_user_ns() | |
304 | self.init_logger() |
|
302 | self.init_logger() | |
305 | self.init_alias() |
|
303 | self.init_alias() | |
306 | self.init_builtins() |
|
304 | self.init_builtins() | |
307 |
|
305 | |||
308 | # pre_config_initialization |
|
306 | # pre_config_initialization | |
309 | self.init_shadow_hist() |
|
307 | self.init_shadow_hist() | |
310 |
|
308 | |||
311 | # The next section should contain averything that was in ipmaker. |
|
309 | # The next section should contain averything that was in ipmaker. | |
312 | self.init_logstart() |
|
310 | self.init_logstart() | |
313 |
|
311 | |||
314 | # The following was in post_config_initialization |
|
312 | # The following was in post_config_initialization | |
315 | self.init_inspector() |
|
313 | self.init_inspector() | |
316 | self.init_readline() |
|
314 | self.init_readline() | |
317 | self.init_prompts() |
|
315 | self.init_prompts() | |
318 | self.init_displayhook() |
|
316 | self.init_displayhook() | |
319 | self.init_reload_doctest() |
|
317 | self.init_reload_doctest() | |
320 | self.init_magics() |
|
318 | self.init_magics() | |
321 | self.init_pdb() |
|
319 | self.init_pdb() | |
322 | self.hooks.late_startup_hook() |
|
320 | self.hooks.late_startup_hook() | |
323 |
|
321 | |||
324 | def get_ipython(self): |
|
322 | def get_ipython(self): | |
325 | return self |
|
323 | return self | |
326 |
|
324 | |||
327 | #------------------------------------------------------------------------- |
|
325 | #------------------------------------------------------------------------- | |
328 | # Traitlet changed handlers |
|
326 | # Traitlet changed handlers | |
329 | #------------------------------------------------------------------------- |
|
327 | #------------------------------------------------------------------------- | |
330 |
|
328 | |||
331 | def _banner1_changed(self): |
|
329 | def _banner1_changed(self): | |
332 | self.compute_banner() |
|
330 | self.compute_banner() | |
333 |
|
331 | |||
334 | def _banner2_changed(self): |
|
332 | def _banner2_changed(self): | |
335 | self.compute_banner() |
|
333 | self.compute_banner() | |
336 |
|
334 | |||
337 | def _ipythondir_changed(self, name, new): |
|
335 | def _ipythondir_changed(self, name, new): | |
338 | if not os.path.isdir(new): |
|
336 | if not os.path.isdir(new): | |
339 | os.makedirs(new, mode = 0777) |
|
337 | os.makedirs(new, mode = 0777) | |
340 | if not os.path.isdir(self.ipython_extension_dir): |
|
338 | if not os.path.isdir(self.ipython_extension_dir): | |
341 | os.makedirs(self.ipython_extension_dir, mode = 0777) |
|
339 | os.makedirs(self.ipython_extension_dir, mode = 0777) | |
342 |
|
340 | |||
343 | @property |
|
341 | @property | |
344 | def ipython_extension_dir(self): |
|
342 | def ipython_extension_dir(self): | |
345 | return os.path.join(self.ipythondir, 'extensions') |
|
343 | return os.path.join(self.ipythondir, 'extensions') | |
346 |
|
344 | |||
347 | @property |
|
345 | @property | |
348 | def usable_screen_length(self): |
|
346 | def usable_screen_length(self): | |
349 | if self.screen_length == 0: |
|
347 | if self.screen_length == 0: | |
350 | return 0 |
|
348 | return 0 | |
351 | else: |
|
349 | else: | |
352 | num_lines_bot = self.separate_in.count('\n')+1 |
|
350 | num_lines_bot = self.separate_in.count('\n')+1 | |
353 | return self.screen_length - num_lines_bot |
|
351 | return self.screen_length - num_lines_bot | |
354 |
|
352 | |||
355 | def _term_title_changed(self, name, new_value): |
|
353 | def _term_title_changed(self, name, new_value): | |
356 | self.init_term_title() |
|
354 | self.init_term_title() | |
357 |
|
355 | |||
358 | def set_autoindent(self,value=None): |
|
356 | def set_autoindent(self,value=None): | |
359 | """Set the autoindent flag, checking for readline support. |
|
357 | """Set the autoindent flag, checking for readline support. | |
360 |
|
358 | |||
361 | If called with no arguments, it acts as a toggle.""" |
|
359 | If called with no arguments, it acts as a toggle.""" | |
362 |
|
360 | |||
363 | if not self.has_readline: |
|
361 | if not self.has_readline: | |
364 | if os.name == 'posix': |
|
362 | if os.name == 'posix': | |
365 | warn("The auto-indent feature requires the readline library") |
|
363 | warn("The auto-indent feature requires the readline library") | |
366 | self.autoindent = 0 |
|
364 | self.autoindent = 0 | |
367 | return |
|
365 | return | |
368 | if value is None: |
|
366 | if value is None: | |
369 | self.autoindent = not self.autoindent |
|
367 | self.autoindent = not self.autoindent | |
370 | else: |
|
368 | else: | |
371 | self.autoindent = value |
|
369 | self.autoindent = value | |
372 |
|
370 | |||
373 | #------------------------------------------------------------------------- |
|
371 | #------------------------------------------------------------------------- | |
374 | # init_* methods called by __init__ |
|
372 | # init_* methods called by __init__ | |
375 | #------------------------------------------------------------------------- |
|
373 | #------------------------------------------------------------------------- | |
376 |
|
374 | |||
377 | def init_ipythondir(self, ipythondir): |
|
375 | def init_ipythondir(self, ipythondir): | |
378 | if ipythondir is not None: |
|
376 | if ipythondir is not None: | |
379 | self.ipythondir = ipythondir |
|
377 | self.ipythondir = ipythondir | |
380 | self.config.Global.ipythondir = self.ipythondir |
|
378 | self.config.Global.ipythondir = self.ipythondir | |
381 | return |
|
379 | return | |
382 |
|
380 | |||
383 | if hasattr(self.config.Global, 'ipythondir'): |
|
381 | if hasattr(self.config.Global, 'ipythondir'): | |
384 | self.ipythondir = self.config.Global.ipythondir |
|
382 | self.ipythondir = self.config.Global.ipythondir | |
385 | else: |
|
383 | else: | |
386 | self.ipythondir = get_ipython_dir() |
|
384 | self.ipythondir = get_ipython_dir() | |
387 |
|
385 | |||
388 | # All children can just read this |
|
386 | # All children can just read this | |
389 | self.config.Global.ipythondir = self.ipythondir |
|
387 | self.config.Global.ipythondir = self.ipythondir | |
390 |
|
388 | |||
391 | def init_instance_attrs(self): |
|
389 | def init_instance_attrs(self): | |
392 | self.jobs = BackgroundJobManager() |
|
390 | self.jobs = BackgroundJobManager() | |
393 | self.more = False |
|
391 | self.more = False | |
394 |
|
392 | |||
395 | # command compiler |
|
393 | # command compiler | |
396 | self.compile = codeop.CommandCompiler() |
|
394 | self.compile = codeop.CommandCompiler() | |
397 |
|
395 | |||
398 | # User input buffer |
|
396 | # User input buffer | |
399 | self.buffer = [] |
|
397 | self.buffer = [] | |
400 |
|
398 | |||
401 | # Make an empty namespace, which extension writers can rely on both |
|
399 | # Make an empty namespace, which extension writers can rely on both | |
402 | # existing and NEVER being used by ipython itself. This gives them a |
|
400 | # existing and NEVER being used by ipython itself. This gives them a | |
403 | # convenient location for storing additional information and state |
|
401 | # convenient location for storing additional information and state | |
404 | # their extensions may require, without fear of collisions with other |
|
402 | # their extensions may require, without fear of collisions with other | |
405 | # ipython names that may develop later. |
|
403 | # ipython names that may develop later. | |
406 | self.meta = Struct() |
|
404 | self.meta = Struct() | |
407 |
|
405 | |||
408 | # Object variable to store code object waiting execution. This is |
|
406 | # Object variable to store code object waiting execution. This is | |
409 | # used mainly by the multithreaded shells, but it can come in handy in |
|
407 | # used mainly by the multithreaded shells, but it can come in handy in | |
410 | # other situations. No need to use a Queue here, since it's a single |
|
408 | # other situations. No need to use a Queue here, since it's a single | |
411 | # item which gets cleared once run. |
|
409 | # item which gets cleared once run. | |
412 | self.code_to_run = None |
|
410 | self.code_to_run = None | |
413 |
|
411 | |||
414 | # Flag to mark unconditional exit |
|
412 | # Flag to mark unconditional exit | |
415 | self.exit_now = False |
|
413 | self.exit_now = False | |
416 |
|
414 | |||
417 | # Temporary files used for various purposes. Deleted at exit. |
|
415 | # Temporary files used for various purposes. Deleted at exit. | |
418 | self.tempfiles = [] |
|
416 | self.tempfiles = [] | |
419 |
|
417 | |||
420 | # Keep track of readline usage (later set by init_readline) |
|
418 | # Keep track of readline usage (later set by init_readline) | |
421 | self.has_readline = False |
|
419 | self.has_readline = False | |
422 |
|
420 | |||
423 | # keep track of where we started running (mainly for crash post-mortem) |
|
421 | # keep track of where we started running (mainly for crash post-mortem) | |
424 | # This is not being used anywhere currently. |
|
422 | # This is not being used anywhere currently. | |
425 | self.starting_dir = os.getcwd() |
|
423 | self.starting_dir = os.getcwd() | |
426 |
|
424 | |||
427 | # Indentation management |
|
425 | # Indentation management | |
428 | self.indent_current_nsp = 0 |
|
426 | self.indent_current_nsp = 0 | |
429 |
|
427 | |||
430 | def init_term_title(self): |
|
428 | def init_term_title(self): | |
431 | # Enable or disable the terminal title. |
|
429 | # Enable or disable the terminal title. | |
432 | if self.term_title: |
|
430 | if self.term_title: | |
433 | toggle_set_term_title(True) |
|
431 | toggle_set_term_title(True) | |
434 | set_term_title('IPython: ' + abbrev_cwd()) |
|
432 | set_term_title('IPython: ' + abbrev_cwd()) | |
435 | else: |
|
433 | else: | |
436 | toggle_set_term_title(False) |
|
434 | toggle_set_term_title(False) | |
437 |
|
435 | |||
438 | def init_usage(self, usage=None): |
|
436 | def init_usage(self, usage=None): | |
439 | if usage is None: |
|
437 | if usage is None: | |
440 | self.usage = interactive_usage |
|
438 | self.usage = interactive_usage | |
441 | else: |
|
439 | else: | |
442 | self.usage = usage |
|
440 | self.usage = usage | |
443 |
|
441 | |||
444 | def init_encoding(self): |
|
442 | def init_encoding(self): | |
445 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
443 | # Get system encoding at startup time. Certain terminals (like Emacs | |
446 | # under Win32 have it set to None, and we need to have a known valid |
|
444 | # under Win32 have it set to None, and we need to have a known valid | |
447 | # encoding to use in the raw_input() method |
|
445 | # encoding to use in the raw_input() method | |
448 | try: |
|
446 | try: | |
449 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
447 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
450 | except AttributeError: |
|
448 | except AttributeError: | |
451 | self.stdin_encoding = 'ascii' |
|
449 | self.stdin_encoding = 'ascii' | |
452 |
|
450 | |||
453 | def init_syntax_highlighting(self): |
|
451 | def init_syntax_highlighting(self): | |
454 | # Python source parser/formatter for syntax highlighting |
|
452 | # Python source parser/formatter for syntax highlighting | |
455 | pyformat = PyColorize.Parser().format |
|
453 | pyformat = PyColorize.Parser().format | |
456 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
454 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) | |
457 |
|
455 | |||
458 | def init_pushd_popd_magic(self): |
|
456 | def init_pushd_popd_magic(self): | |
459 | # for pushd/popd management |
|
457 | # for pushd/popd management | |
460 | try: |
|
458 | try: | |
461 | self.home_dir = get_home_dir() |
|
459 | self.home_dir = get_home_dir() | |
462 | except HomeDirError, msg: |
|
460 | except HomeDirError, msg: | |
463 | fatal(msg) |
|
461 | fatal(msg) | |
464 |
|
462 | |||
465 | self.dir_stack = [] |
|
463 | self.dir_stack = [] | |
466 |
|
464 | |||
467 | def init_logger(self): |
|
465 | def init_logger(self): | |
468 | self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate') |
|
466 | self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate') | |
469 | # local shortcut, this is used a LOT |
|
467 | # local shortcut, this is used a LOT | |
470 | self.log = self.logger.log |
|
468 | self.log = self.logger.log | |
471 | # template for logfile headers. It gets resolved at runtime by the |
|
469 | # template for logfile headers. It gets resolved at runtime by the | |
472 | # logstart method. |
|
470 | # logstart method. | |
473 | self.loghead_tpl = \ |
|
471 | self.loghead_tpl = \ | |
474 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** |
|
472 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** | |
475 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW |
|
473 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW | |
476 | #log# opts = %s |
|
474 | #log# opts = %s | |
477 | #log# args = %s |
|
475 | #log# args = %s | |
478 | #log# It is safe to make manual edits below here. |
|
476 | #log# It is safe to make manual edits below here. | |
479 | #log#----------------------------------------------------------------------- |
|
477 | #log#----------------------------------------------------------------------- | |
480 | """ |
|
478 | """ | |
481 |
|
479 | |||
482 | def init_logstart(self): |
|
480 | def init_logstart(self): | |
483 | if self.logplay: |
|
481 | if self.logplay: | |
484 | self.magic_logstart(self.logplay + ' append') |
|
482 | self.magic_logstart(self.logplay + ' append') | |
485 | elif self.logfile: |
|
483 | elif self.logfile: | |
486 | self.magic_logstart(self.logfile) |
|
484 | self.magic_logstart(self.logfile) | |
487 | elif self.logstart: |
|
485 | elif self.logstart: | |
488 | self.magic_logstart() |
|
486 | self.magic_logstart() | |
489 |
|
487 | |||
490 | def init_builtins(self): |
|
488 | def init_builtins(self): | |
491 | self.builtin_trap = BuiltinTrap(self) |
|
489 | self.builtin_trap = BuiltinTrap(self) | |
492 |
|
490 | |||
493 | def init_inspector(self): |
|
491 | def init_inspector(self): | |
494 | # Object inspector |
|
492 | # Object inspector | |
495 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
493 | self.inspector = oinspect.Inspector(oinspect.InspectColors, | |
496 | PyColorize.ANSICodeColors, |
|
494 | PyColorize.ANSICodeColors, | |
497 | 'NoColor', |
|
495 | 'NoColor', | |
498 | self.object_info_string_level) |
|
496 | self.object_info_string_level) | |
499 |
|
497 | |||
500 | def init_prompts(self): |
|
498 | def init_prompts(self): | |
501 | # Initialize cache, set in/out prompts and printing system |
|
499 | # Initialize cache, set in/out prompts and printing system | |
502 | self.outputcache = CachedOutput(self, |
|
500 | self.outputcache = CachedOutput(self, | |
503 | self.cache_size, |
|
501 | self.cache_size, | |
504 | self.pprint, |
|
502 | self.pprint, | |
505 | input_sep = self.separate_in, |
|
503 | input_sep = self.separate_in, | |
506 | output_sep = self.separate_out, |
|
504 | output_sep = self.separate_out, | |
507 | output_sep2 = self.separate_out2, |
|
505 | output_sep2 = self.separate_out2, | |
508 | ps1 = self.prompt_in1, |
|
506 | ps1 = self.prompt_in1, | |
509 | ps2 = self.prompt_in2, |
|
507 | ps2 = self.prompt_in2, | |
510 | ps_out = self.prompt_out, |
|
508 | ps_out = self.prompt_out, | |
511 | pad_left = self.prompts_pad_left) |
|
509 | pad_left = self.prompts_pad_left) | |
512 |
|
510 | |||
513 | # user may have over-ridden the default print hook: |
|
511 | # user may have over-ridden the default print hook: | |
514 | try: |
|
512 | try: | |
515 | self.outputcache.__class__.display = self.hooks.display |
|
513 | self.outputcache.__class__.display = self.hooks.display | |
516 | except AttributeError: |
|
514 | except AttributeError: | |
517 | pass |
|
515 | pass | |
518 |
|
516 | |||
519 | def init_displayhook(self): |
|
517 | def init_displayhook(self): | |
520 | self.display_trap = DisplayTrap(self, self.outputcache) |
|
518 | self.display_trap = DisplayTrap(self, self.outputcache) | |
521 |
|
519 | |||
522 | def init_reload_doctest(self): |
|
520 | def init_reload_doctest(self): | |
523 | # Do a proper resetting of doctest, including the necessary displayhook |
|
521 | # Do a proper resetting of doctest, including the necessary displayhook | |
524 | # monkeypatching |
|
522 | # monkeypatching | |
525 | try: |
|
523 | try: | |
526 | doctest_reload() |
|
524 | doctest_reload() | |
527 | except ImportError: |
|
525 | except ImportError: | |
528 | warn("doctest module does not exist.") |
|
526 | warn("doctest module does not exist.") | |
529 |
|
527 | |||
530 | #------------------------------------------------------------------------- |
|
528 | #------------------------------------------------------------------------- | |
531 | # Things related to the banner |
|
529 | # Things related to the banner | |
532 | #------------------------------------------------------------------------- |
|
530 | #------------------------------------------------------------------------- | |
533 |
|
531 | |||
534 | def init_banner(self, banner1, banner2, display_banner): |
|
532 | def init_banner(self, banner1, banner2, display_banner): | |
535 | if banner1 is not None: |
|
533 | if banner1 is not None: | |
536 | self.banner1 = banner1 |
|
534 | self.banner1 = banner1 | |
537 | if banner2 is not None: |
|
535 | if banner2 is not None: | |
538 | self.banner2 = banner2 |
|
536 | self.banner2 = banner2 | |
539 | if display_banner is not None: |
|
537 | if display_banner is not None: | |
540 | self.display_banner = display_banner |
|
538 | self.display_banner = display_banner | |
541 | self.compute_banner() |
|
539 | self.compute_banner() | |
542 |
|
540 | |||
543 | def show_banner(self, banner=None): |
|
541 | def show_banner(self, banner=None): | |
544 | if banner is None: |
|
542 | if banner is None: | |
545 | banner = self.banner |
|
543 | banner = self.banner | |
546 | self.write(banner) |
|
544 | self.write(banner) | |
547 |
|
545 | |||
548 | def compute_banner(self): |
|
546 | def compute_banner(self): | |
549 | self.banner = self.banner1 + '\n' |
|
547 | self.banner = self.banner1 + '\n' | |
550 | if self.profile: |
|
548 | if self.profile: | |
551 | self.banner += '\nIPython profile: %s\n' % self.profile |
|
549 | self.banner += '\nIPython profile: %s\n' % self.profile | |
552 | if self.banner2: |
|
550 | if self.banner2: | |
553 | self.banner += '\n' + self.banner2 + '\n' |
|
551 | self.banner += '\n' + self.banner2 + '\n' | |
554 |
|
552 | |||
555 | #------------------------------------------------------------------------- |
|
553 | #------------------------------------------------------------------------- | |
556 | # Things related to injections into the sys module |
|
554 | # Things related to injections into the sys module | |
557 | #------------------------------------------------------------------------- |
|
555 | #------------------------------------------------------------------------- | |
558 |
|
556 | |||
559 | def save_sys_module_state(self): |
|
557 | def save_sys_module_state(self): | |
560 | """Save the state of hooks in the sys module. |
|
558 | """Save the state of hooks in the sys module. | |
561 |
|
559 | |||
562 | This has to be called after self.user_ns is created. |
|
560 | This has to be called after self.user_ns is created. | |
563 | """ |
|
561 | """ | |
564 | self._orig_sys_module_state = {} |
|
562 | self._orig_sys_module_state = {} | |
565 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
563 | self._orig_sys_module_state['stdin'] = sys.stdin | |
566 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
564 | self._orig_sys_module_state['stdout'] = sys.stdout | |
567 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
565 | self._orig_sys_module_state['stderr'] = sys.stderr | |
568 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
566 | self._orig_sys_module_state['excepthook'] = sys.excepthook | |
569 | try: |
|
567 | try: | |
570 | self._orig_sys_modules_main_name = self.user_ns['__name__'] |
|
568 | self._orig_sys_modules_main_name = self.user_ns['__name__'] | |
571 | except KeyError: |
|
569 | except KeyError: | |
572 | pass |
|
570 | pass | |
573 |
|
571 | |||
574 | def restore_sys_module_state(self): |
|
572 | def restore_sys_module_state(self): | |
575 | """Restore the state of the sys module.""" |
|
573 | """Restore the state of the sys module.""" | |
576 | try: |
|
574 | try: | |
577 | for k, v in self._orig_sys_module_state.items(): |
|
575 | for k, v in self._orig_sys_module_state.items(): | |
578 | setattr(sys, k, v) |
|
576 | setattr(sys, k, v) | |
579 | except AttributeError: |
|
577 | except AttributeError: | |
580 | pass |
|
578 | pass | |
581 | try: |
|
579 | try: | |
582 | delattr(sys, 'ipcompleter') |
|
580 | delattr(sys, 'ipcompleter') | |
583 | except AttributeError: |
|
581 | except AttributeError: | |
584 | pass |
|
582 | pass | |
585 | # Reset what what done in self.init_sys_modules |
|
583 | # Reset what what done in self.init_sys_modules | |
586 | try: |
|
584 | try: | |
587 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name |
|
585 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name | |
588 | except (AttributeError, KeyError): |
|
586 | except (AttributeError, KeyError): | |
589 | pass |
|
587 | pass | |
590 |
|
588 | |||
591 | #------------------------------------------------------------------------- |
|
589 | #------------------------------------------------------------------------- | |
592 | # Things related to hooks |
|
590 | # Things related to hooks | |
593 | #------------------------------------------------------------------------- |
|
591 | #------------------------------------------------------------------------- | |
594 |
|
592 | |||
595 | def init_hooks(self): |
|
593 | def init_hooks(self): | |
596 | # hooks holds pointers used for user-side customizations |
|
594 | # hooks holds pointers used for user-side customizations | |
597 | self.hooks = Struct() |
|
595 | self.hooks = Struct() | |
598 |
|
596 | |||
599 | self.strdispatchers = {} |
|
597 | self.strdispatchers = {} | |
600 |
|
598 | |||
601 | # Set all default hooks, defined in the IPython.hooks module. |
|
599 | # Set all default hooks, defined in the IPython.hooks module. | |
602 | import IPython.core.hooks |
|
600 | import IPython.core.hooks | |
603 | hooks = IPython.core.hooks |
|
601 | hooks = IPython.core.hooks | |
604 | for hook_name in hooks.__all__: |
|
602 | for hook_name in hooks.__all__: | |
605 | # default hooks have priority 100, i.e. low; user hooks should have |
|
603 | # default hooks have priority 100, i.e. low; user hooks should have | |
606 | # 0-100 priority |
|
604 | # 0-100 priority | |
607 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
605 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
608 |
|
606 | |||
609 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
607 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
610 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
608 | """set_hook(name,hook) -> sets an internal IPython hook. | |
611 |
|
609 | |||
612 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
610 | IPython exposes some of its internal API as user-modifiable hooks. By | |
613 | adding your function to one of these hooks, you can modify IPython's |
|
611 | adding your function to one of these hooks, you can modify IPython's | |
614 | behavior to call at runtime your own routines.""" |
|
612 | behavior to call at runtime your own routines.""" | |
615 |
|
613 | |||
616 | # At some point in the future, this should validate the hook before it |
|
614 | # At some point in the future, this should validate the hook before it | |
617 | # accepts it. Probably at least check that the hook takes the number |
|
615 | # accepts it. Probably at least check that the hook takes the number | |
618 | # of args it's supposed to. |
|
616 | # of args it's supposed to. | |
619 |
|
617 | |||
620 | f = new.instancemethod(hook,self,self.__class__) |
|
618 | f = new.instancemethod(hook,self,self.__class__) | |
621 |
|
619 | |||
622 | # check if the hook is for strdispatcher first |
|
620 | # check if the hook is for strdispatcher first | |
623 | if str_key is not None: |
|
621 | if str_key is not None: | |
624 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
622 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
625 | sdp.add_s(str_key, f, priority ) |
|
623 | sdp.add_s(str_key, f, priority ) | |
626 | self.strdispatchers[name] = sdp |
|
624 | self.strdispatchers[name] = sdp | |
627 | return |
|
625 | return | |
628 | if re_key is not None: |
|
626 | if re_key is not None: | |
629 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
627 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
630 | sdp.add_re(re.compile(re_key), f, priority ) |
|
628 | sdp.add_re(re.compile(re_key), f, priority ) | |
631 | self.strdispatchers[name] = sdp |
|
629 | self.strdispatchers[name] = sdp | |
632 | return |
|
630 | return | |
633 |
|
631 | |||
634 | dp = getattr(self.hooks, name, None) |
|
632 | dp = getattr(self.hooks, name, None) | |
635 | if name not in IPython.core.hooks.__all__: |
|
633 | if name not in IPython.core.hooks.__all__: | |
636 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ ) |
|
634 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ ) | |
637 | if not dp: |
|
635 | if not dp: | |
638 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
636 | dp = IPython.core.hooks.CommandChainDispatcher() | |
639 |
|
637 | |||
640 | try: |
|
638 | try: | |
641 | dp.add(f,priority) |
|
639 | dp.add(f,priority) | |
642 | except AttributeError: |
|
640 | except AttributeError: | |
643 | # it was not commandchain, plain old func - replace |
|
641 | # it was not commandchain, plain old func - replace | |
644 | dp = f |
|
642 | dp = f | |
645 |
|
643 | |||
646 | setattr(self.hooks,name, dp) |
|
644 | setattr(self.hooks,name, dp) | |
647 |
|
645 | |||
648 | #------------------------------------------------------------------------- |
|
646 | #------------------------------------------------------------------------- | |
649 | # Things related to the "main" module |
|
647 | # Things related to the "main" module | |
650 | #------------------------------------------------------------------------- |
|
648 | #------------------------------------------------------------------------- | |
651 |
|
649 | |||
652 | def new_main_mod(self,ns=None): |
|
650 | def new_main_mod(self,ns=None): | |
653 | """Return a new 'main' module object for user code execution. |
|
651 | """Return a new 'main' module object for user code execution. | |
654 | """ |
|
652 | """ | |
655 | main_mod = self._user_main_module |
|
653 | main_mod = self._user_main_module | |
656 | init_fakemod_dict(main_mod,ns) |
|
654 | init_fakemod_dict(main_mod,ns) | |
657 | return main_mod |
|
655 | return main_mod | |
658 |
|
656 | |||
659 | def cache_main_mod(self,ns,fname): |
|
657 | def cache_main_mod(self,ns,fname): | |
660 | """Cache a main module's namespace. |
|
658 | """Cache a main module's namespace. | |
661 |
|
659 | |||
662 | When scripts are executed via %run, we must keep a reference to the |
|
660 | When scripts are executed via %run, we must keep a reference to the | |
663 | namespace of their __main__ module (a FakeModule instance) around so |
|
661 | namespace of their __main__ module (a FakeModule instance) around so | |
664 | that Python doesn't clear it, rendering objects defined therein |
|
662 | that Python doesn't clear it, rendering objects defined therein | |
665 | useless. |
|
663 | useless. | |
666 |
|
664 | |||
667 | This method keeps said reference in a private dict, keyed by the |
|
665 | This method keeps said reference in a private dict, keyed by the | |
668 | absolute path of the module object (which corresponds to the script |
|
666 | absolute path of the module object (which corresponds to the script | |
669 | path). This way, for multiple executions of the same script we only |
|
667 | path). This way, for multiple executions of the same script we only | |
670 | keep one copy of the namespace (the last one), thus preventing memory |
|
668 | keep one copy of the namespace (the last one), thus preventing memory | |
671 | leaks from old references while allowing the objects from the last |
|
669 | leaks from old references while allowing the objects from the last | |
672 | execution to be accessible. |
|
670 | execution to be accessible. | |
673 |
|
671 | |||
674 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
672 | Note: we can not allow the actual FakeModule instances to be deleted, | |
675 | because of how Python tears down modules (it hard-sets all their |
|
673 | because of how Python tears down modules (it hard-sets all their | |
676 | references to None without regard for reference counts). This method |
|
674 | references to None without regard for reference counts). This method | |
677 | must therefore make a *copy* of the given namespace, to allow the |
|
675 | must therefore make a *copy* of the given namespace, to allow the | |
678 | original module's __dict__ to be cleared and reused. |
|
676 | original module's __dict__ to be cleared and reused. | |
679 |
|
677 | |||
680 |
|
678 | |||
681 | Parameters |
|
679 | Parameters | |
682 | ---------- |
|
680 | ---------- | |
683 | ns : a namespace (a dict, typically) |
|
681 | ns : a namespace (a dict, typically) | |
684 |
|
682 | |||
685 | fname : str |
|
683 | fname : str | |
686 | Filename associated with the namespace. |
|
684 | Filename associated with the namespace. | |
687 |
|
685 | |||
688 | Examples |
|
686 | Examples | |
689 | -------- |
|
687 | -------- | |
690 |
|
688 | |||
691 | In [10]: import IPython |
|
689 | In [10]: import IPython | |
692 |
|
690 | |||
693 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
691 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
694 |
|
692 | |||
695 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
693 | In [12]: IPython.__file__ in _ip._main_ns_cache | |
696 | Out[12]: True |
|
694 | Out[12]: True | |
697 | """ |
|
695 | """ | |
698 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
696 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() | |
699 |
|
697 | |||
700 | def clear_main_mod_cache(self): |
|
698 | def clear_main_mod_cache(self): | |
701 | """Clear the cache of main modules. |
|
699 | """Clear the cache of main modules. | |
702 |
|
700 | |||
703 | Mainly for use by utilities like %reset. |
|
701 | Mainly for use by utilities like %reset. | |
704 |
|
702 | |||
705 | Examples |
|
703 | Examples | |
706 | -------- |
|
704 | -------- | |
707 |
|
705 | |||
708 | In [15]: import IPython |
|
706 | In [15]: import IPython | |
709 |
|
707 | |||
710 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
708 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
711 |
|
709 | |||
712 | In [17]: len(_ip._main_ns_cache) > 0 |
|
710 | In [17]: len(_ip._main_ns_cache) > 0 | |
713 | Out[17]: True |
|
711 | Out[17]: True | |
714 |
|
712 | |||
715 | In [18]: _ip.clear_main_mod_cache() |
|
713 | In [18]: _ip.clear_main_mod_cache() | |
716 |
|
714 | |||
717 | In [19]: len(_ip._main_ns_cache) == 0 |
|
715 | In [19]: len(_ip._main_ns_cache) == 0 | |
718 | Out[19]: True |
|
716 | Out[19]: True | |
719 | """ |
|
717 | """ | |
720 | self._main_ns_cache.clear() |
|
718 | self._main_ns_cache.clear() | |
721 |
|
719 | |||
722 | #------------------------------------------------------------------------- |
|
720 | #------------------------------------------------------------------------- | |
723 | # Things related to debugging |
|
721 | # Things related to debugging | |
724 | #------------------------------------------------------------------------- |
|
722 | #------------------------------------------------------------------------- | |
725 |
|
723 | |||
726 | def init_pdb(self): |
|
724 | def init_pdb(self): | |
727 | # Set calling of pdb on exceptions |
|
725 | # Set calling of pdb on exceptions | |
728 | # self.call_pdb is a property |
|
726 | # self.call_pdb is a property | |
729 | self.call_pdb = self.pdb |
|
727 | self.call_pdb = self.pdb | |
730 |
|
728 | |||
731 | def _get_call_pdb(self): |
|
729 | def _get_call_pdb(self): | |
732 | return self._call_pdb |
|
730 | return self._call_pdb | |
733 |
|
731 | |||
734 | def _set_call_pdb(self,val): |
|
732 | def _set_call_pdb(self,val): | |
735 |
|
733 | |||
736 | if val not in (0,1,False,True): |
|
734 | if val not in (0,1,False,True): | |
737 | raise ValueError,'new call_pdb value must be boolean' |
|
735 | raise ValueError,'new call_pdb value must be boolean' | |
738 |
|
736 | |||
739 | # store value in instance |
|
737 | # store value in instance | |
740 | self._call_pdb = val |
|
738 | self._call_pdb = val | |
741 |
|
739 | |||
742 | # notify the actual exception handlers |
|
740 | # notify the actual exception handlers | |
743 | self.InteractiveTB.call_pdb = val |
|
741 | self.InteractiveTB.call_pdb = val | |
744 | if self.isthreaded: |
|
742 | if self.isthreaded: | |
745 | try: |
|
743 | try: | |
746 | self.sys_excepthook.call_pdb = val |
|
744 | self.sys_excepthook.call_pdb = val | |
747 | except: |
|
745 | except: | |
748 | warn('Failed to activate pdb for threaded exception handler') |
|
746 | warn('Failed to activate pdb for threaded exception handler') | |
749 |
|
747 | |||
750 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
748 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
751 | 'Control auto-activation of pdb at exceptions') |
|
749 | 'Control auto-activation of pdb at exceptions') | |
752 |
|
750 | |||
753 | def debugger(self,force=False): |
|
751 | def debugger(self,force=False): | |
754 | """Call the pydb/pdb debugger. |
|
752 | """Call the pydb/pdb debugger. | |
755 |
|
753 | |||
756 | Keywords: |
|
754 | Keywords: | |
757 |
|
755 | |||
758 | - force(False): by default, this routine checks the instance call_pdb |
|
756 | - force(False): by default, this routine checks the instance call_pdb | |
759 | flag and does not actually invoke the debugger if the flag is false. |
|
757 | flag and does not actually invoke the debugger if the flag is false. | |
760 | The 'force' option forces the debugger to activate even if the flag |
|
758 | The 'force' option forces the debugger to activate even if the flag | |
761 | is false. |
|
759 | is false. | |
762 | """ |
|
760 | """ | |
763 |
|
761 | |||
764 | if not (force or self.call_pdb): |
|
762 | if not (force or self.call_pdb): | |
765 | return |
|
763 | return | |
766 |
|
764 | |||
767 | if not hasattr(sys,'last_traceback'): |
|
765 | if not hasattr(sys,'last_traceback'): | |
768 | error('No traceback has been produced, nothing to debug.') |
|
766 | error('No traceback has been produced, nothing to debug.') | |
769 | return |
|
767 | return | |
770 |
|
768 | |||
771 | # use pydb if available |
|
769 | # use pydb if available | |
772 | if debugger.has_pydb: |
|
770 | if debugger.has_pydb: | |
773 | from pydb import pm |
|
771 | from pydb import pm | |
774 | else: |
|
772 | else: | |
775 | # fallback to our internal debugger |
|
773 | # fallback to our internal debugger | |
776 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
774 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
777 | self.history_saving_wrapper(pm)() |
|
775 | self.history_saving_wrapper(pm)() | |
778 |
|
776 | |||
779 | #------------------------------------------------------------------------- |
|
777 | #------------------------------------------------------------------------- | |
780 | # Things related to IPython's various namespaces |
|
778 | # Things related to IPython's various namespaces | |
781 | #------------------------------------------------------------------------- |
|
779 | #------------------------------------------------------------------------- | |
782 |
|
780 | |||
783 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): |
|
781 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): | |
784 | # Create the namespace where the user will operate. user_ns is |
|
782 | # Create the namespace where the user will operate. user_ns is | |
785 | # normally the only one used, and it is passed to the exec calls as |
|
783 | # normally the only one used, and it is passed to the exec calls as | |
786 | # the locals argument. But we do carry a user_global_ns namespace |
|
784 | # the locals argument. But we do carry a user_global_ns namespace | |
787 | # given as the exec 'globals' argument, This is useful in embedding |
|
785 | # given as the exec 'globals' argument, This is useful in embedding | |
788 | # situations where the ipython shell opens in a context where the |
|
786 | # situations where the ipython shell opens in a context where the | |
789 | # distinction between locals and globals is meaningful. For |
|
787 | # distinction between locals and globals is meaningful. For | |
790 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
788 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
791 |
|
789 | |||
792 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
790 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
793 | # level as a dict instead of a module. This is a manual fix, but I |
|
791 | # level as a dict instead of a module. This is a manual fix, but I | |
794 | # should really track down where the problem is coming from. Alex |
|
792 | # should really track down where the problem is coming from. Alex | |
795 | # Schmolck reported this problem first. |
|
793 | # Schmolck reported this problem first. | |
796 |
|
794 | |||
797 | # A useful post by Alex Martelli on this topic: |
|
795 | # A useful post by Alex Martelli on this topic: | |
798 | # Re: inconsistent value from __builtins__ |
|
796 | # Re: inconsistent value from __builtins__ | |
799 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
797 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
800 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
798 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
801 | # Gruppen: comp.lang.python |
|
799 | # Gruppen: comp.lang.python | |
802 |
|
800 | |||
803 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
801 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
804 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
802 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
805 | # > <type 'dict'> |
|
803 | # > <type 'dict'> | |
806 | # > >>> print type(__builtins__) |
|
804 | # > >>> print type(__builtins__) | |
807 | # > <type 'module'> |
|
805 | # > <type 'module'> | |
808 | # > Is this difference in return value intentional? |
|
806 | # > Is this difference in return value intentional? | |
809 |
|
807 | |||
810 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
808 | # Well, it's documented that '__builtins__' can be either a dictionary | |
811 | # or a module, and it's been that way for a long time. Whether it's |
|
809 | # or a module, and it's been that way for a long time. Whether it's | |
812 | # intentional (or sensible), I don't know. In any case, the idea is |
|
810 | # intentional (or sensible), I don't know. In any case, the idea is | |
813 | # that if you need to access the built-in namespace directly, you |
|
811 | # that if you need to access the built-in namespace directly, you | |
814 | # should start with "import __builtin__" (note, no 's') which will |
|
812 | # should start with "import __builtin__" (note, no 's') which will | |
815 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
813 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
816 |
|
814 | |||
817 | # These routines return properly built dicts as needed by the rest of |
|
815 | # These routines return properly built dicts as needed by the rest of | |
818 | # the code, and can also be used by extension writers to generate |
|
816 | # the code, and can also be used by extension writers to generate | |
819 | # properly initialized namespaces. |
|
817 | # properly initialized namespaces. | |
820 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, |
|
818 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, | |
821 | user_global_ns) |
|
819 | user_global_ns) | |
822 |
|
820 | |||
823 | # Assign namespaces |
|
821 | # Assign namespaces | |
824 | # This is the namespace where all normal user variables live |
|
822 | # This is the namespace where all normal user variables live | |
825 | self.user_ns = user_ns |
|
823 | self.user_ns = user_ns | |
826 | self.user_global_ns = user_global_ns |
|
824 | self.user_global_ns = user_global_ns | |
827 |
|
825 | |||
828 | # An auxiliary namespace that checks what parts of the user_ns were |
|
826 | # An auxiliary namespace that checks what parts of the user_ns were | |
829 | # loaded at startup, so we can list later only variables defined in |
|
827 | # loaded at startup, so we can list later only variables defined in | |
830 | # actual interactive use. Since it is always a subset of user_ns, it |
|
828 | # actual interactive use. Since it is always a subset of user_ns, it | |
831 | # doesn't need to be seaparately tracked in the ns_table |
|
829 | # doesn't need to be seaparately tracked in the ns_table | |
832 | self.user_config_ns = {} |
|
830 | self.user_config_ns = {} | |
833 |
|
831 | |||
834 | # A namespace to keep track of internal data structures to prevent |
|
832 | # A namespace to keep track of internal data structures to prevent | |
835 | # them from cluttering user-visible stuff. Will be updated later |
|
833 | # them from cluttering user-visible stuff. Will be updated later | |
836 | self.internal_ns = {} |
|
834 | self.internal_ns = {} | |
837 |
|
835 | |||
838 | # Now that FakeModule produces a real module, we've run into a nasty |
|
836 | # Now that FakeModule produces a real module, we've run into a nasty | |
839 | # problem: after script execution (via %run), the module where the user |
|
837 | # problem: after script execution (via %run), the module where the user | |
840 | # code ran is deleted. Now that this object is a true module (needed |
|
838 | # code ran is deleted. Now that this object is a true module (needed | |
841 | # so docetst and other tools work correctly), the Python module |
|
839 | # so docetst and other tools work correctly), the Python module | |
842 | # teardown mechanism runs over it, and sets to None every variable |
|
840 | # teardown mechanism runs over it, and sets to None every variable | |
843 | # present in that module. Top-level references to objects from the |
|
841 | # present in that module. Top-level references to objects from the | |
844 | # script survive, because the user_ns is updated with them. However, |
|
842 | # script survive, because the user_ns is updated with them. However, | |
845 | # calling functions defined in the script that use other things from |
|
843 | # calling functions defined in the script that use other things from | |
846 | # the script will fail, because the function's closure had references |
|
844 | # the script will fail, because the function's closure had references | |
847 | # to the original objects, which are now all None. So we must protect |
|
845 | # to the original objects, which are now all None. So we must protect | |
848 | # these modules from deletion by keeping a cache. |
|
846 | # these modules from deletion by keeping a cache. | |
849 | # |
|
847 | # | |
850 | # To avoid keeping stale modules around (we only need the one from the |
|
848 | # To avoid keeping stale modules around (we only need the one from the | |
851 | # last run), we use a dict keyed with the full path to the script, so |
|
849 | # last run), we use a dict keyed with the full path to the script, so | |
852 | # only the last version of the module is held in the cache. Note, |
|
850 | # only the last version of the module is held in the cache. Note, | |
853 | # however, that we must cache the module *namespace contents* (their |
|
851 | # however, that we must cache the module *namespace contents* (their | |
854 | # __dict__). Because if we try to cache the actual modules, old ones |
|
852 | # __dict__). Because if we try to cache the actual modules, old ones | |
855 | # (uncached) could be destroyed while still holding references (such as |
|
853 | # (uncached) could be destroyed while still holding references (such as | |
856 | # those held by GUI objects that tend to be long-lived)> |
|
854 | # those held by GUI objects that tend to be long-lived)> | |
857 | # |
|
855 | # | |
858 | # The %reset command will flush this cache. See the cache_main_mod() |
|
856 | # The %reset command will flush this cache. See the cache_main_mod() | |
859 | # and clear_main_mod_cache() methods for details on use. |
|
857 | # and clear_main_mod_cache() methods for details on use. | |
860 |
|
858 | |||
861 | # This is the cache used for 'main' namespaces |
|
859 | # This is the cache used for 'main' namespaces | |
862 | self._main_ns_cache = {} |
|
860 | self._main_ns_cache = {} | |
863 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
861 | # And this is the single instance of FakeModule whose __dict__ we keep | |
864 | # copying and clearing for reuse on each %run |
|
862 | # copying and clearing for reuse on each %run | |
865 | self._user_main_module = FakeModule() |
|
863 | self._user_main_module = FakeModule() | |
866 |
|
864 | |||
867 | # A table holding all the namespaces IPython deals with, so that |
|
865 | # A table holding all the namespaces IPython deals with, so that | |
868 | # introspection facilities can search easily. |
|
866 | # introspection facilities can search easily. | |
869 | self.ns_table = {'user':user_ns, |
|
867 | self.ns_table = {'user':user_ns, | |
870 | 'user_global':user_global_ns, |
|
868 | 'user_global':user_global_ns, | |
871 | 'internal':self.internal_ns, |
|
869 | 'internal':self.internal_ns, | |
872 | 'builtin':__builtin__.__dict__ |
|
870 | 'builtin':__builtin__.__dict__ | |
873 | } |
|
871 | } | |
874 |
|
872 | |||
875 | # Similarly, track all namespaces where references can be held and that |
|
873 | # Similarly, track all namespaces where references can be held and that | |
876 | # we can safely clear (so it can NOT include builtin). This one can be |
|
874 | # we can safely clear (so it can NOT include builtin). This one can be | |
877 | # a simple list. |
|
875 | # a simple list. | |
878 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, |
|
876 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, | |
879 | self.internal_ns, self._main_ns_cache ] |
|
877 | self.internal_ns, self._main_ns_cache ] | |
880 |
|
878 | |||
881 | def init_sys_modules(self): |
|
879 | def init_sys_modules(self): | |
882 | # We need to insert into sys.modules something that looks like a |
|
880 | # We need to insert into sys.modules something that looks like a | |
883 | # module but which accesses the IPython namespace, for shelve and |
|
881 | # module but which accesses the IPython namespace, for shelve and | |
884 | # pickle to work interactively. Normally they rely on getting |
|
882 | # pickle to work interactively. Normally they rely on getting | |
885 | # everything out of __main__, but for embedding purposes each IPython |
|
883 | # everything out of __main__, but for embedding purposes each IPython | |
886 | # instance has its own private namespace, so we can't go shoving |
|
884 | # instance has its own private namespace, so we can't go shoving | |
887 | # everything into __main__. |
|
885 | # everything into __main__. | |
888 |
|
886 | |||
889 | # note, however, that we should only do this for non-embedded |
|
887 | # note, however, that we should only do this for non-embedded | |
890 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
888 | # ipythons, which really mimic the __main__.__dict__ with their own | |
891 | # namespace. Embedded instances, on the other hand, should not do |
|
889 | # namespace. Embedded instances, on the other hand, should not do | |
892 | # this because they need to manage the user local/global namespaces |
|
890 | # this because they need to manage the user local/global namespaces | |
893 | # only, but they live within a 'normal' __main__ (meaning, they |
|
891 | # only, but they live within a 'normal' __main__ (meaning, they | |
894 | # shouldn't overtake the execution environment of the script they're |
|
892 | # shouldn't overtake the execution environment of the script they're | |
895 | # embedded in). |
|
893 | # embedded in). | |
896 |
|
894 | |||
897 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
895 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. | |
898 |
|
896 | |||
899 | try: |
|
897 | try: | |
900 | main_name = self.user_ns['__name__'] |
|
898 | main_name = self.user_ns['__name__'] | |
901 | except KeyError: |
|
899 | except KeyError: | |
902 | raise KeyError('user_ns dictionary MUST have a "__name__" key') |
|
900 | raise KeyError('user_ns dictionary MUST have a "__name__" key') | |
903 | else: |
|
901 | else: | |
904 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
902 | sys.modules[main_name] = FakeModule(self.user_ns) | |
905 |
|
903 | |||
906 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): |
|
904 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): | |
907 | """Return a valid local and global user interactive namespaces. |
|
905 | """Return a valid local and global user interactive namespaces. | |
908 |
|
906 | |||
909 | This builds a dict with the minimal information needed to operate as a |
|
907 | This builds a dict with the minimal information needed to operate as a | |
910 | valid IPython user namespace, which you can pass to the various |
|
908 | valid IPython user namespace, which you can pass to the various | |
911 | embedding classes in ipython. The default implementation returns the |
|
909 | embedding classes in ipython. The default implementation returns the | |
912 | same dict for both the locals and the globals to allow functions to |
|
910 | same dict for both the locals and the globals to allow functions to | |
913 | refer to variables in the namespace. Customized implementations can |
|
911 | refer to variables in the namespace. Customized implementations can | |
914 | return different dicts. The locals dictionary can actually be anything |
|
912 | return different dicts. The locals dictionary can actually be anything | |
915 | following the basic mapping protocol of a dict, but the globals dict |
|
913 | following the basic mapping protocol of a dict, but the globals dict | |
916 | must be a true dict, not even a subclass. It is recommended that any |
|
914 | must be a true dict, not even a subclass. It is recommended that any | |
917 | custom object for the locals namespace synchronize with the globals |
|
915 | custom object for the locals namespace synchronize with the globals | |
918 | dict somehow. |
|
916 | dict somehow. | |
919 |
|
917 | |||
920 | Raises TypeError if the provided globals namespace is not a true dict. |
|
918 | Raises TypeError if the provided globals namespace is not a true dict. | |
921 |
|
919 | |||
922 | :Parameters: |
|
920 | :Parameters: | |
923 | user_ns : dict-like, optional |
|
921 | user_ns : dict-like, optional | |
924 | The current user namespace. The items in this namespace should |
|
922 | The current user namespace. The items in this namespace should | |
925 | be included in the output. If None, an appropriate blank |
|
923 | be included in the output. If None, an appropriate blank | |
926 | namespace should be created. |
|
924 | namespace should be created. | |
927 | user_global_ns : dict, optional |
|
925 | user_global_ns : dict, optional | |
928 | The current user global namespace. The items in this namespace |
|
926 | The current user global namespace. The items in this namespace | |
929 | should be included in the output. If None, an appropriate |
|
927 | should be included in the output. If None, an appropriate | |
930 | blank namespace should be created. |
|
928 | blank namespace should be created. | |
931 |
|
929 | |||
932 | :Returns: |
|
930 | :Returns: | |
933 | A tuple pair of dictionary-like object to be used as the local namespace |
|
931 | A tuple pair of dictionary-like object to be used as the local namespace | |
934 | of the interpreter and a dict to be used as the global namespace. |
|
932 | of the interpreter and a dict to be used as the global namespace. | |
935 | """ |
|
933 | """ | |
936 |
|
934 | |||
937 | if user_ns is None: |
|
935 | if user_ns is None: | |
938 | # Set __name__ to __main__ to better match the behavior of the |
|
936 | # Set __name__ to __main__ to better match the behavior of the | |
939 | # normal interpreter. |
|
937 | # normal interpreter. | |
940 | user_ns = {'__name__' :'__main__', |
|
938 | user_ns = {'__name__' :'__main__', | |
941 | '__builtins__' : __builtin__, |
|
939 | '__builtins__' : __builtin__, | |
942 | } |
|
940 | } | |
943 | else: |
|
941 | else: | |
944 | user_ns.setdefault('__name__','__main__') |
|
942 | user_ns.setdefault('__name__','__main__') | |
945 | user_ns.setdefault('__builtins__',__builtin__) |
|
943 | user_ns.setdefault('__builtins__',__builtin__) | |
946 |
|
944 | |||
947 | if user_global_ns is None: |
|
945 | if user_global_ns is None: | |
948 | user_global_ns = user_ns |
|
946 | user_global_ns = user_ns | |
949 | if type(user_global_ns) is not dict: |
|
947 | if type(user_global_ns) is not dict: | |
950 | raise TypeError("user_global_ns must be a true dict; got %r" |
|
948 | raise TypeError("user_global_ns must be a true dict; got %r" | |
951 | % type(user_global_ns)) |
|
949 | % type(user_global_ns)) | |
952 |
|
950 | |||
953 | return user_ns, user_global_ns |
|
951 | return user_ns, user_global_ns | |
954 |
|
952 | |||
955 | def init_user_ns(self): |
|
953 | def init_user_ns(self): | |
956 | """Initialize all user-visible namespaces to their minimum defaults. |
|
954 | """Initialize all user-visible namespaces to their minimum defaults. | |
957 |
|
955 | |||
958 | Certain history lists are also initialized here, as they effectively |
|
956 | Certain history lists are also initialized here, as they effectively | |
959 | act as user namespaces. |
|
957 | act as user namespaces. | |
960 |
|
958 | |||
961 | Notes |
|
959 | Notes | |
962 | ----- |
|
960 | ----- | |
963 | All data structures here are only filled in, they are NOT reset by this |
|
961 | All data structures here are only filled in, they are NOT reset by this | |
964 | method. If they were not empty before, data will simply be added to |
|
962 | method. If they were not empty before, data will simply be added to | |
965 | therm. |
|
963 | therm. | |
966 | """ |
|
964 | """ | |
967 | # Store myself as the public api!!! |
|
965 | # Store myself as the public api!!! | |
968 | self.user_ns['get_ipython'] = self.get_ipython |
|
966 | self.user_ns['get_ipython'] = self.get_ipython | |
969 |
|
967 | |||
970 | # make global variables for user access to the histories |
|
968 | # make global variables for user access to the histories | |
971 | self.user_ns['_ih'] = self.input_hist |
|
969 | self.user_ns['_ih'] = self.input_hist | |
972 | self.user_ns['_oh'] = self.output_hist |
|
970 | self.user_ns['_oh'] = self.output_hist | |
973 | self.user_ns['_dh'] = self.dir_hist |
|
971 | self.user_ns['_dh'] = self.dir_hist | |
974 |
|
972 | |||
975 | # user aliases to input and output histories |
|
973 | # user aliases to input and output histories | |
976 | self.user_ns['In'] = self.input_hist |
|
974 | self.user_ns['In'] = self.input_hist | |
977 | self.user_ns['Out'] = self.output_hist |
|
975 | self.user_ns['Out'] = self.output_hist | |
978 |
|
976 | |||
979 | self.user_ns['_sh'] = shadowns |
|
977 | self.user_ns['_sh'] = shadowns | |
980 |
|
978 | |||
981 | # Put 'help' in the user namespace |
|
979 | # Put 'help' in the user namespace | |
982 | try: |
|
980 | try: | |
983 | from site import _Helper |
|
981 | from site import _Helper | |
984 | self.user_ns['help'] = _Helper() |
|
982 | self.user_ns['help'] = _Helper() | |
985 | except ImportError: |
|
983 | except ImportError: | |
986 | warn('help() not available - check site.py') |
|
984 | warn('help() not available - check site.py') | |
987 |
|
985 | |||
988 | def reset(self): |
|
986 | def reset(self): | |
989 | """Clear all internal namespaces. |
|
987 | """Clear all internal namespaces. | |
990 |
|
988 | |||
991 | Note that this is much more aggressive than %reset, since it clears |
|
989 | Note that this is much more aggressive than %reset, since it clears | |
992 | fully all namespaces, as well as all input/output lists. |
|
990 | fully all namespaces, as well as all input/output lists. | |
993 | """ |
|
991 | """ | |
994 | for ns in self.ns_refs_table: |
|
992 | for ns in self.ns_refs_table: | |
995 | ns.clear() |
|
993 | ns.clear() | |
996 |
|
994 | |||
997 | self.alias_manager.clear_aliases() |
|
995 | self.alias_manager.clear_aliases() | |
998 |
|
996 | |||
999 | # Clear input and output histories |
|
997 | # Clear input and output histories | |
1000 | self.input_hist[:] = [] |
|
998 | self.input_hist[:] = [] | |
1001 | self.input_hist_raw[:] = [] |
|
999 | self.input_hist_raw[:] = [] | |
1002 | self.output_hist.clear() |
|
1000 | self.output_hist.clear() | |
1003 |
|
1001 | |||
1004 | # Restore the user namespaces to minimal usability |
|
1002 | # Restore the user namespaces to minimal usability | |
1005 | self.init_user_ns() |
|
1003 | self.init_user_ns() | |
1006 |
|
1004 | |||
1007 | # Restore the default and user aliases |
|
1005 | # Restore the default and user aliases | |
1008 | self.alias_manager.init_aliases() |
|
1006 | self.alias_manager.init_aliases() | |
1009 |
|
1007 | |||
1010 | def push(self, variables, interactive=True): |
|
1008 | def push(self, variables, interactive=True): | |
1011 | """Inject a group of variables into the IPython user namespace. |
|
1009 | """Inject a group of variables into the IPython user namespace. | |
1012 |
|
1010 | |||
1013 | Parameters |
|
1011 | Parameters | |
1014 | ---------- |
|
1012 | ---------- | |
1015 | variables : dict, str or list/tuple of str |
|
1013 | variables : dict, str or list/tuple of str | |
1016 | The variables to inject into the user's namespace. If a dict, |
|
1014 | The variables to inject into the user's namespace. If a dict, | |
1017 | a simple update is done. If a str, the string is assumed to |
|
1015 | a simple update is done. If a str, the string is assumed to | |
1018 | have variable names separated by spaces. A list/tuple of str |
|
1016 | have variable names separated by spaces. A list/tuple of str | |
1019 | can also be used to give the variable names. If just the variable |
|
1017 | can also be used to give the variable names. If just the variable | |
1020 | names are give (list/tuple/str) then the variable values looked |
|
1018 | names are give (list/tuple/str) then the variable values looked | |
1021 | up in the callers frame. |
|
1019 | up in the callers frame. | |
1022 | interactive : bool |
|
1020 | interactive : bool | |
1023 | If True (default), the variables will be listed with the ``who`` |
|
1021 | If True (default), the variables will be listed with the ``who`` | |
1024 | magic. |
|
1022 | magic. | |
1025 | """ |
|
1023 | """ | |
1026 | vdict = None |
|
1024 | vdict = None | |
1027 |
|
1025 | |||
1028 | # We need a dict of name/value pairs to do namespace updates. |
|
1026 | # We need a dict of name/value pairs to do namespace updates. | |
1029 | if isinstance(variables, dict): |
|
1027 | if isinstance(variables, dict): | |
1030 | vdict = variables |
|
1028 | vdict = variables | |
1031 | elif isinstance(variables, (basestring, list, tuple)): |
|
1029 | elif isinstance(variables, (basestring, list, tuple)): | |
1032 | if isinstance(variables, basestring): |
|
1030 | if isinstance(variables, basestring): | |
1033 | vlist = variables.split() |
|
1031 | vlist = variables.split() | |
1034 | else: |
|
1032 | else: | |
1035 | vlist = variables |
|
1033 | vlist = variables | |
1036 | vdict = {} |
|
1034 | vdict = {} | |
1037 | cf = sys._getframe(1) |
|
1035 | cf = sys._getframe(1) | |
1038 | for name in vlist: |
|
1036 | for name in vlist: | |
1039 | try: |
|
1037 | try: | |
1040 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1038 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) | |
1041 | except: |
|
1039 | except: | |
1042 | print ('Could not get variable %s from %s' % |
|
1040 | print ('Could not get variable %s from %s' % | |
1043 | (name,cf.f_code.co_name)) |
|
1041 | (name,cf.f_code.co_name)) | |
1044 | else: |
|
1042 | else: | |
1045 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1043 | raise ValueError('variables must be a dict/str/list/tuple') | |
1046 |
|
1044 | |||
1047 | # Propagate variables to user namespace |
|
1045 | # Propagate variables to user namespace | |
1048 | self.user_ns.update(vdict) |
|
1046 | self.user_ns.update(vdict) | |
1049 |
|
1047 | |||
1050 | # And configure interactive visibility |
|
1048 | # And configure interactive visibility | |
1051 | config_ns = self.user_config_ns |
|
1049 | config_ns = self.user_config_ns | |
1052 | if interactive: |
|
1050 | if interactive: | |
1053 | for name, val in vdict.iteritems(): |
|
1051 | for name, val in vdict.iteritems(): | |
1054 | config_ns.pop(name, None) |
|
1052 | config_ns.pop(name, None) | |
1055 | else: |
|
1053 | else: | |
1056 | for name,val in vdict.iteritems(): |
|
1054 | for name,val in vdict.iteritems(): | |
1057 | config_ns[name] = val |
|
1055 | config_ns[name] = val | |
1058 |
|
1056 | |||
1059 | #------------------------------------------------------------------------- |
|
1057 | #------------------------------------------------------------------------- | |
1060 | # Things related to history management |
|
1058 | # Things related to history management | |
1061 | #------------------------------------------------------------------------- |
|
1059 | #------------------------------------------------------------------------- | |
1062 |
|
1060 | |||
1063 | def init_history(self): |
|
1061 | def init_history(self): | |
1064 | # List of input with multi-line handling. |
|
1062 | # List of input with multi-line handling. | |
1065 | self.input_hist = InputList() |
|
1063 | self.input_hist = InputList() | |
1066 | # This one will hold the 'raw' input history, without any |
|
1064 | # This one will hold the 'raw' input history, without any | |
1067 | # pre-processing. This will allow users to retrieve the input just as |
|
1065 | # pre-processing. This will allow users to retrieve the input just as | |
1068 | # it was exactly typed in by the user, with %hist -r. |
|
1066 | # it was exactly typed in by the user, with %hist -r. | |
1069 | self.input_hist_raw = InputList() |
|
1067 | self.input_hist_raw = InputList() | |
1070 |
|
1068 | |||
1071 | # list of visited directories |
|
1069 | # list of visited directories | |
1072 | try: |
|
1070 | try: | |
1073 | self.dir_hist = [os.getcwd()] |
|
1071 | self.dir_hist = [os.getcwd()] | |
1074 | except OSError: |
|
1072 | except OSError: | |
1075 | self.dir_hist = [] |
|
1073 | self.dir_hist = [] | |
1076 |
|
1074 | |||
1077 | # dict of output history |
|
1075 | # dict of output history | |
1078 | self.output_hist = {} |
|
1076 | self.output_hist = {} | |
1079 |
|
1077 | |||
1080 | # Now the history file |
|
1078 | # Now the history file | |
1081 | if self.profile: |
|
1079 | if self.profile: | |
1082 | histfname = 'history-%s' % self.profile |
|
1080 | histfname = 'history-%s' % self.profile | |
1083 | else: |
|
1081 | else: | |
1084 | histfname = 'history' |
|
1082 | histfname = 'history' | |
1085 | self.histfile = os.path.join(self.ipythondir, histfname) |
|
1083 | self.histfile = os.path.join(self.ipythondir, histfname) | |
1086 |
|
1084 | |||
1087 | # Fill the history zero entry, user counter starts at 1 |
|
1085 | # Fill the history zero entry, user counter starts at 1 | |
1088 | self.input_hist.append('\n') |
|
1086 | self.input_hist.append('\n') | |
1089 | self.input_hist_raw.append('\n') |
|
1087 | self.input_hist_raw.append('\n') | |
1090 |
|
1088 | |||
1091 | def init_shadow_hist(self): |
|
1089 | def init_shadow_hist(self): | |
1092 | try: |
|
1090 | try: | |
1093 | self.db = pickleshare.PickleShareDB(self.ipythondir + "/db") |
|
1091 | self.db = pickleshare.PickleShareDB(self.ipythondir + "/db") | |
1094 | except exceptions.UnicodeDecodeError: |
|
1092 | except exceptions.UnicodeDecodeError: | |
1095 | print "Your ipythondir can't be decoded to unicode!" |
|
1093 | print "Your ipythondir can't be decoded to unicode!" | |
1096 | print "Please set HOME environment variable to something that" |
|
1094 | print "Please set HOME environment variable to something that" | |
1097 | print r"only has ASCII characters, e.g. c:\home" |
|
1095 | print r"only has ASCII characters, e.g. c:\home" | |
1098 | print "Now it is", self.ipythondir |
|
1096 | print "Now it is", self.ipythondir | |
1099 | sys.exit() |
|
1097 | sys.exit() | |
1100 | self.shadowhist = ipcorehist.ShadowHist(self.db) |
|
1098 | self.shadowhist = ipcorehist.ShadowHist(self.db) | |
1101 |
|
1099 | |||
1102 | def savehist(self): |
|
1100 | def savehist(self): | |
1103 | """Save input history to a file (via readline library).""" |
|
1101 | """Save input history to a file (via readline library).""" | |
1104 |
|
1102 | |||
1105 | if not self.has_readline: |
|
1103 | if not self.has_readline: | |
1106 | return |
|
1104 | return | |
1107 |
|
1105 | |||
1108 | try: |
|
1106 | try: | |
1109 | self.readline.write_history_file(self.histfile) |
|
1107 | self.readline.write_history_file(self.histfile) | |
1110 | except: |
|
1108 | except: | |
1111 | print 'Unable to save IPython command history to file: ' + \ |
|
1109 | print 'Unable to save IPython command history to file: ' + \ | |
1112 | `self.histfile` |
|
1110 | `self.histfile` | |
1113 |
|
1111 | |||
1114 | def reloadhist(self): |
|
1112 | def reloadhist(self): | |
1115 | """Reload the input history from disk file.""" |
|
1113 | """Reload the input history from disk file.""" | |
1116 |
|
1114 | |||
1117 | if self.has_readline: |
|
1115 | if self.has_readline: | |
1118 | try: |
|
1116 | try: | |
1119 | self.readline.clear_history() |
|
1117 | self.readline.clear_history() | |
1120 | self.readline.read_history_file(self.shell.histfile) |
|
1118 | self.readline.read_history_file(self.shell.histfile) | |
1121 | except AttributeError: |
|
1119 | except AttributeError: | |
1122 | pass |
|
1120 | pass | |
1123 |
|
1121 | |||
1124 | def history_saving_wrapper(self, func): |
|
1122 | def history_saving_wrapper(self, func): | |
1125 | """ Wrap func for readline history saving |
|
1123 | """ Wrap func for readline history saving | |
1126 |
|
1124 | |||
1127 | Convert func into callable that saves & restores |
|
1125 | Convert func into callable that saves & restores | |
1128 | history around the call """ |
|
1126 | history around the call """ | |
1129 |
|
1127 | |||
1130 | if not self.has_readline: |
|
1128 | if not self.has_readline: | |
1131 | return func |
|
1129 | return func | |
1132 |
|
1130 | |||
1133 | def wrapper(): |
|
1131 | def wrapper(): | |
1134 | self.savehist() |
|
1132 | self.savehist() | |
1135 | try: |
|
1133 | try: | |
1136 | func() |
|
1134 | func() | |
1137 | finally: |
|
1135 | finally: | |
1138 | readline.read_history_file(self.histfile) |
|
1136 | readline.read_history_file(self.histfile) | |
1139 | return wrapper |
|
1137 | return wrapper | |
1140 |
|
1138 | |||
1141 | #------------------------------------------------------------------------- |
|
1139 | #------------------------------------------------------------------------- | |
1142 | # Things related to exception handling and tracebacks (not debugging) |
|
1140 | # Things related to exception handling and tracebacks (not debugging) | |
1143 | #------------------------------------------------------------------------- |
|
1141 | #------------------------------------------------------------------------- | |
1144 |
|
1142 | |||
1145 | def init_traceback_handlers(self, custom_exceptions): |
|
1143 | def init_traceback_handlers(self, custom_exceptions): | |
1146 | # Syntax error handler. |
|
1144 | # Syntax error handler. | |
1147 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
1145 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') | |
1148 |
|
1146 | |||
1149 | # The interactive one is initialized with an offset, meaning we always |
|
1147 | # The interactive one is initialized with an offset, meaning we always | |
1150 | # want to remove the topmost item in the traceback, which is our own |
|
1148 | # want to remove the topmost item in the traceback, which is our own | |
1151 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1149 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
1152 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1150 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', | |
1153 | color_scheme='NoColor', |
|
1151 | color_scheme='NoColor', | |
1154 | tb_offset = 1) |
|
1152 | tb_offset = 1) | |
1155 |
|
1153 | |||
1156 | # IPython itself shouldn't crash. This will produce a detailed |
|
1154 | # IPython itself shouldn't crash. This will produce a detailed | |
1157 | # post-mortem if it does. But we only install the crash handler for |
|
1155 | # post-mortem if it does. But we only install the crash handler for | |
1158 | # non-threaded shells, the threaded ones use a normal verbose reporter |
|
1156 | # non-threaded shells, the threaded ones use a normal verbose reporter | |
1159 | # and lose the crash handler. This is because exceptions in the main |
|
1157 | # and lose the crash handler. This is because exceptions in the main | |
1160 | # thread (such as in GUI code) propagate directly to sys.excepthook, |
|
1158 | # thread (such as in GUI code) propagate directly to sys.excepthook, | |
1161 | # and there's no point in printing crash dumps for every user exception. |
|
1159 | # and there's no point in printing crash dumps for every user exception. | |
1162 | if self.isthreaded: |
|
1160 | if self.isthreaded: | |
1163 | ipCrashHandler = ultratb.FormattedTB() |
|
1161 | ipCrashHandler = ultratb.FormattedTB() | |
1164 | else: |
|
1162 | else: | |
1165 | from IPython.core import crashhandler |
|
1163 | from IPython.core import crashhandler | |
1166 | ipCrashHandler = crashhandler.IPythonCrashHandler(self) |
|
1164 | ipCrashHandler = crashhandler.IPythonCrashHandler(self) | |
1167 | self.set_crash_handler(ipCrashHandler) |
|
1165 | self.set_crash_handler(ipCrashHandler) | |
1168 |
|
1166 | |||
1169 | # and add any custom exception handlers the user may have specified |
|
1167 | # and add any custom exception handlers the user may have specified | |
1170 | self.set_custom_exc(*custom_exceptions) |
|
1168 | self.set_custom_exc(*custom_exceptions) | |
1171 |
|
1169 | |||
1172 | def set_crash_handler(self, crashHandler): |
|
1170 | def set_crash_handler(self, crashHandler): | |
1173 | """Set the IPython crash handler. |
|
1171 | """Set the IPython crash handler. | |
1174 |
|
1172 | |||
1175 | This must be a callable with a signature suitable for use as |
|
1173 | This must be a callable with a signature suitable for use as | |
1176 | sys.excepthook.""" |
|
1174 | sys.excepthook.""" | |
1177 |
|
1175 | |||
1178 | # Install the given crash handler as the Python exception hook |
|
1176 | # Install the given crash handler as the Python exception hook | |
1179 | sys.excepthook = crashHandler |
|
1177 | sys.excepthook = crashHandler | |
1180 |
|
1178 | |||
1181 | # The instance will store a pointer to this, so that runtime code |
|
1179 | # The instance will store a pointer to this, so that runtime code | |
1182 | # (such as magics) can access it. This is because during the |
|
1180 | # (such as magics) can access it. This is because during the | |
1183 | # read-eval loop, it gets temporarily overwritten (to deal with GUI |
|
1181 | # read-eval loop, it gets temporarily overwritten (to deal with GUI | |
1184 | # frameworks). |
|
1182 | # frameworks). | |
1185 | self.sys_excepthook = sys.excepthook |
|
1183 | self.sys_excepthook = sys.excepthook | |
1186 |
|
1184 | |||
1187 | def set_custom_exc(self,exc_tuple,handler): |
|
1185 | def set_custom_exc(self,exc_tuple,handler): | |
1188 | """set_custom_exc(exc_tuple,handler) |
|
1186 | """set_custom_exc(exc_tuple,handler) | |
1189 |
|
1187 | |||
1190 | Set a custom exception handler, which will be called if any of the |
|
1188 | Set a custom exception handler, which will be called if any of the | |
1191 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1189 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1192 | runcode() method. |
|
1190 | runcode() method. | |
1193 |
|
1191 | |||
1194 | Inputs: |
|
1192 | Inputs: | |
1195 |
|
1193 | |||
1196 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1194 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
1197 | handler for. It is very important that you use a tuple, and NOT A |
|
1195 | handler for. It is very important that you use a tuple, and NOT A | |
1198 | LIST here, because of the way Python's except statement works. If |
|
1196 | LIST here, because of the way Python's except statement works. If | |
1199 | you only want to trap a single exception, use a singleton tuple: |
|
1197 | you only want to trap a single exception, use a singleton tuple: | |
1200 |
|
1198 | |||
1201 | exc_tuple == (MyCustomException,) |
|
1199 | exc_tuple == (MyCustomException,) | |
1202 |
|
1200 | |||
1203 | - handler: this must be defined as a function with the following |
|
1201 | - handler: this must be defined as a function with the following | |
1204 | basic interface: def my_handler(self,etype,value,tb). |
|
1202 | basic interface: def my_handler(self,etype,value,tb). | |
1205 |
|
1203 | |||
1206 | This will be made into an instance method (via new.instancemethod) |
|
1204 | This will be made into an instance method (via new.instancemethod) | |
1207 | of IPython itself, and it will be called if any of the exceptions |
|
1205 | of IPython itself, and it will be called if any of the exceptions | |
1208 | listed in the exc_tuple are caught. If the handler is None, an |
|
1206 | listed in the exc_tuple are caught. If the handler is None, an | |
1209 | internal basic one is used, which just prints basic info. |
|
1207 | internal basic one is used, which just prints basic info. | |
1210 |
|
1208 | |||
1211 | WARNING: by putting in your own exception handler into IPython's main |
|
1209 | WARNING: by putting in your own exception handler into IPython's main | |
1212 | execution loop, you run a very good chance of nasty crashes. This |
|
1210 | execution loop, you run a very good chance of nasty crashes. This | |
1213 | facility should only be used if you really know what you are doing.""" |
|
1211 | facility should only be used if you really know what you are doing.""" | |
1214 |
|
1212 | |||
1215 | assert type(exc_tuple)==type(()) , \ |
|
1213 | assert type(exc_tuple)==type(()) , \ | |
1216 | "The custom exceptions must be given AS A TUPLE." |
|
1214 | "The custom exceptions must be given AS A TUPLE." | |
1217 |
|
1215 | |||
1218 | def dummy_handler(self,etype,value,tb): |
|
1216 | def dummy_handler(self,etype,value,tb): | |
1219 | print '*** Simple custom exception handler ***' |
|
1217 | print '*** Simple custom exception handler ***' | |
1220 | print 'Exception type :',etype |
|
1218 | print 'Exception type :',etype | |
1221 | print 'Exception value:',value |
|
1219 | print 'Exception value:',value | |
1222 | print 'Traceback :',tb |
|
1220 | print 'Traceback :',tb | |
1223 | print 'Source code :','\n'.join(self.buffer) |
|
1221 | print 'Source code :','\n'.join(self.buffer) | |
1224 |
|
1222 | |||
1225 | if handler is None: handler = dummy_handler |
|
1223 | if handler is None: handler = dummy_handler | |
1226 |
|
1224 | |||
1227 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
1225 | self.CustomTB = new.instancemethod(handler,self,self.__class__) | |
1228 | self.custom_exceptions = exc_tuple |
|
1226 | self.custom_exceptions = exc_tuple | |
1229 |
|
1227 | |||
1230 | def excepthook(self, etype, value, tb): |
|
1228 | def excepthook(self, etype, value, tb): | |
1231 | """One more defense for GUI apps that call sys.excepthook. |
|
1229 | """One more defense for GUI apps that call sys.excepthook. | |
1232 |
|
1230 | |||
1233 | GUI frameworks like wxPython trap exceptions and call |
|
1231 | GUI frameworks like wxPython trap exceptions and call | |
1234 | sys.excepthook themselves. I guess this is a feature that |
|
1232 | sys.excepthook themselves. I guess this is a feature that | |
1235 | enables them to keep running after exceptions that would |
|
1233 | enables them to keep running after exceptions that would | |
1236 | otherwise kill their mainloop. This is a bother for IPython |
|
1234 | otherwise kill their mainloop. This is a bother for IPython | |
1237 | which excepts to catch all of the program exceptions with a try: |
|
1235 | which excepts to catch all of the program exceptions with a try: | |
1238 | except: statement. |
|
1236 | except: statement. | |
1239 |
|
1237 | |||
1240 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1238 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1241 | any app directly invokes sys.excepthook, it will look to the user like |
|
1239 | any app directly invokes sys.excepthook, it will look to the user like | |
1242 | IPython crashed. In order to work around this, we can disable the |
|
1240 | IPython crashed. In order to work around this, we can disable the | |
1243 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1241 | CrashHandler and replace it with this excepthook instead, which prints a | |
1244 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1242 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1245 | call sys.excepthook will generate a regular-looking exception from |
|
1243 | call sys.excepthook will generate a regular-looking exception from | |
1246 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1244 | IPython, and the CrashHandler will only be triggered by real IPython | |
1247 | crashes. |
|
1245 | crashes. | |
1248 |
|
1246 | |||
1249 | This hook should be used sparingly, only in places which are not likely |
|
1247 | This hook should be used sparingly, only in places which are not likely | |
1250 | to be true IPython errors. |
|
1248 | to be true IPython errors. | |
1251 | """ |
|
1249 | """ | |
1252 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1250 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1253 |
|
1251 | |||
1254 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): |
|
1252 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): | |
1255 | """Display the exception that just occurred. |
|
1253 | """Display the exception that just occurred. | |
1256 |
|
1254 | |||
1257 | If nothing is known about the exception, this is the method which |
|
1255 | If nothing is known about the exception, this is the method which | |
1258 | should be used throughout the code for presenting user tracebacks, |
|
1256 | should be used throughout the code for presenting user tracebacks, | |
1259 | rather than directly invoking the InteractiveTB object. |
|
1257 | rather than directly invoking the InteractiveTB object. | |
1260 |
|
1258 | |||
1261 | A specific showsyntaxerror() also exists, but this method can take |
|
1259 | A specific showsyntaxerror() also exists, but this method can take | |
1262 | care of calling it if needed, so unless you are explicitly catching a |
|
1260 | care of calling it if needed, so unless you are explicitly catching a | |
1263 | SyntaxError exception, don't try to analyze the stack manually and |
|
1261 | SyntaxError exception, don't try to analyze the stack manually and | |
1264 | simply call this method.""" |
|
1262 | simply call this method.""" | |
1265 |
|
1263 | |||
1266 |
|
1264 | |||
1267 | # Though this won't be called by syntax errors in the input line, |
|
1265 | # Though this won't be called by syntax errors in the input line, | |
1268 | # there may be SyntaxError cases whith imported code. |
|
1266 | # there may be SyntaxError cases whith imported code. | |
1269 |
|
1267 | |||
1270 | try: |
|
1268 | try: | |
1271 | if exc_tuple is None: |
|
1269 | if exc_tuple is None: | |
1272 | etype, value, tb = sys.exc_info() |
|
1270 | etype, value, tb = sys.exc_info() | |
1273 | else: |
|
1271 | else: | |
1274 | etype, value, tb = exc_tuple |
|
1272 | etype, value, tb = exc_tuple | |
1275 |
|
1273 | |||
1276 | if etype is SyntaxError: |
|
1274 | if etype is SyntaxError: | |
1277 | self.showsyntaxerror(filename) |
|
1275 | self.showsyntaxerror(filename) | |
1278 | elif etype is UsageError: |
|
1276 | elif etype is UsageError: | |
1279 | print "UsageError:", value |
|
1277 | print "UsageError:", value | |
1280 | else: |
|
1278 | else: | |
1281 | # WARNING: these variables are somewhat deprecated and not |
|
1279 | # WARNING: these variables are somewhat deprecated and not | |
1282 | # necessarily safe to use in a threaded environment, but tools |
|
1280 | # necessarily safe to use in a threaded environment, but tools | |
1283 | # like pdb depend on their existence, so let's set them. If we |
|
1281 | # like pdb depend on their existence, so let's set them. If we | |
1284 | # find problems in the field, we'll need to revisit their use. |
|
1282 | # find problems in the field, we'll need to revisit their use. | |
1285 | sys.last_type = etype |
|
1283 | sys.last_type = etype | |
1286 | sys.last_value = value |
|
1284 | sys.last_value = value | |
1287 | sys.last_traceback = tb |
|
1285 | sys.last_traceback = tb | |
1288 |
|
1286 | |||
1289 | if etype in self.custom_exceptions: |
|
1287 | if etype in self.custom_exceptions: | |
1290 | self.CustomTB(etype,value,tb) |
|
1288 | self.CustomTB(etype,value,tb) | |
1291 | else: |
|
1289 | else: | |
1292 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) |
|
1290 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) | |
1293 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1291 | if self.InteractiveTB.call_pdb and self.has_readline: | |
1294 | # pdb mucks up readline, fix it back |
|
1292 | # pdb mucks up readline, fix it back | |
1295 | self.set_completer() |
|
1293 | self.set_completer() | |
1296 | except KeyboardInterrupt: |
|
1294 | except KeyboardInterrupt: | |
1297 | self.write("\nKeyboardInterrupt\n") |
|
1295 | self.write("\nKeyboardInterrupt\n") | |
1298 |
|
1296 | |||
1299 | def showsyntaxerror(self, filename=None): |
|
1297 | def showsyntaxerror(self, filename=None): | |
1300 | """Display the syntax error that just occurred. |
|
1298 | """Display the syntax error that just occurred. | |
1301 |
|
1299 | |||
1302 | This doesn't display a stack trace because there isn't one. |
|
1300 | This doesn't display a stack trace because there isn't one. | |
1303 |
|
1301 | |||
1304 | If a filename is given, it is stuffed in the exception instead |
|
1302 | If a filename is given, it is stuffed in the exception instead | |
1305 | of what was there before (because Python's parser always uses |
|
1303 | of what was there before (because Python's parser always uses | |
1306 | "<string>" when reading from a string). |
|
1304 | "<string>" when reading from a string). | |
1307 | """ |
|
1305 | """ | |
1308 | etype, value, last_traceback = sys.exc_info() |
|
1306 | etype, value, last_traceback = sys.exc_info() | |
1309 |
|
1307 | |||
1310 | # See note about these variables in showtraceback() below |
|
1308 | # See note about these variables in showtraceback() below | |
1311 | sys.last_type = etype |
|
1309 | sys.last_type = etype | |
1312 | sys.last_value = value |
|
1310 | sys.last_value = value | |
1313 | sys.last_traceback = last_traceback |
|
1311 | sys.last_traceback = last_traceback | |
1314 |
|
1312 | |||
1315 | if filename and etype is SyntaxError: |
|
1313 | if filename and etype is SyntaxError: | |
1316 | # Work hard to stuff the correct filename in the exception |
|
1314 | # Work hard to stuff the correct filename in the exception | |
1317 | try: |
|
1315 | try: | |
1318 | msg, (dummy_filename, lineno, offset, line) = value |
|
1316 | msg, (dummy_filename, lineno, offset, line) = value | |
1319 | except: |
|
1317 | except: | |
1320 | # Not the format we expect; leave it alone |
|
1318 | # Not the format we expect; leave it alone | |
1321 | pass |
|
1319 | pass | |
1322 | else: |
|
1320 | else: | |
1323 | # Stuff in the right filename |
|
1321 | # Stuff in the right filename | |
1324 | try: |
|
1322 | try: | |
1325 | # Assume SyntaxError is a class exception |
|
1323 | # Assume SyntaxError is a class exception | |
1326 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1324 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1327 | except: |
|
1325 | except: | |
1328 | # If that failed, assume SyntaxError is a string |
|
1326 | # If that failed, assume SyntaxError is a string | |
1329 | value = msg, (filename, lineno, offset, line) |
|
1327 | value = msg, (filename, lineno, offset, line) | |
1330 | self.SyntaxTB(etype,value,[]) |
|
1328 | self.SyntaxTB(etype,value,[]) | |
1331 |
|
1329 | |||
1332 | def edit_syntax_error(self): |
|
1330 | def edit_syntax_error(self): | |
1333 | """The bottom half of the syntax error handler called in the main loop. |
|
1331 | """The bottom half of the syntax error handler called in the main loop. | |
1334 |
|
1332 | |||
1335 | Loop until syntax error is fixed or user cancels. |
|
1333 | Loop until syntax error is fixed or user cancels. | |
1336 | """ |
|
1334 | """ | |
1337 |
|
1335 | |||
1338 | while self.SyntaxTB.last_syntax_error: |
|
1336 | while self.SyntaxTB.last_syntax_error: | |
1339 | # copy and clear last_syntax_error |
|
1337 | # copy and clear last_syntax_error | |
1340 | err = self.SyntaxTB.clear_err_state() |
|
1338 | err = self.SyntaxTB.clear_err_state() | |
1341 | if not self._should_recompile(err): |
|
1339 | if not self._should_recompile(err): | |
1342 | return |
|
1340 | return | |
1343 | try: |
|
1341 | try: | |
1344 | # may set last_syntax_error again if a SyntaxError is raised |
|
1342 | # may set last_syntax_error again if a SyntaxError is raised | |
1345 | self.safe_execfile(err.filename,self.user_ns) |
|
1343 | self.safe_execfile(err.filename,self.user_ns) | |
1346 | except: |
|
1344 | except: | |
1347 | self.showtraceback() |
|
1345 | self.showtraceback() | |
1348 | else: |
|
1346 | else: | |
1349 | try: |
|
1347 | try: | |
1350 | f = file(err.filename) |
|
1348 | f = file(err.filename) | |
1351 | try: |
|
1349 | try: | |
1352 | # This should be inside a display_trap block and I |
|
1350 | # This should be inside a display_trap block and I | |
1353 | # think it is. |
|
1351 | # think it is. | |
1354 | sys.displayhook(f.read()) |
|
1352 | sys.displayhook(f.read()) | |
1355 | finally: |
|
1353 | finally: | |
1356 | f.close() |
|
1354 | f.close() | |
1357 | except: |
|
1355 | except: | |
1358 | self.showtraceback() |
|
1356 | self.showtraceback() | |
1359 |
|
1357 | |||
1360 | def _should_recompile(self,e): |
|
1358 | def _should_recompile(self,e): | |
1361 | """Utility routine for edit_syntax_error""" |
|
1359 | """Utility routine for edit_syntax_error""" | |
1362 |
|
1360 | |||
1363 | if e.filename in ('<ipython console>','<input>','<string>', |
|
1361 | if e.filename in ('<ipython console>','<input>','<string>', | |
1364 | '<console>','<BackgroundJob compilation>', |
|
1362 | '<console>','<BackgroundJob compilation>', | |
1365 | None): |
|
1363 | None): | |
1366 |
|
1364 | |||
1367 | return False |
|
1365 | return False | |
1368 | try: |
|
1366 | try: | |
1369 | if (self.autoedit_syntax and |
|
1367 | if (self.autoedit_syntax and | |
1370 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
1368 | not self.ask_yes_no('Return to editor to correct syntax error? ' | |
1371 | '[Y/n] ','y')): |
|
1369 | '[Y/n] ','y')): | |
1372 | return False |
|
1370 | return False | |
1373 | except EOFError: |
|
1371 | except EOFError: | |
1374 | return False |
|
1372 | return False | |
1375 |
|
1373 | |||
1376 | def int0(x): |
|
1374 | def int0(x): | |
1377 | try: |
|
1375 | try: | |
1378 | return int(x) |
|
1376 | return int(x) | |
1379 | except TypeError: |
|
1377 | except TypeError: | |
1380 | return 0 |
|
1378 | return 0 | |
1381 | # always pass integer line and offset values to editor hook |
|
1379 | # always pass integer line and offset values to editor hook | |
1382 | try: |
|
1380 | try: | |
1383 | self.hooks.fix_error_editor(e.filename, |
|
1381 | self.hooks.fix_error_editor(e.filename, | |
1384 | int0(e.lineno),int0(e.offset),e.msg) |
|
1382 | int0(e.lineno),int0(e.offset),e.msg) | |
1385 | except TryNext: |
|
1383 | except TryNext: | |
1386 | warn('Could not open editor') |
|
1384 | warn('Could not open editor') | |
1387 | return False |
|
1385 | return False | |
1388 | return True |
|
1386 | return True | |
1389 |
|
1387 | |||
1390 | #------------------------------------------------------------------------- |
|
1388 | #------------------------------------------------------------------------- | |
1391 | # Things related to tab completion |
|
1389 | # Things related to tab completion | |
1392 | #------------------------------------------------------------------------- |
|
1390 | #------------------------------------------------------------------------- | |
1393 |
|
1391 | |||
1394 | def complete(self, text): |
|
1392 | def complete(self, text): | |
1395 | """Return a sorted list of all possible completions on text. |
|
1393 | """Return a sorted list of all possible completions on text. | |
1396 |
|
1394 | |||
1397 | Inputs: |
|
1395 | Inputs: | |
1398 |
|
1396 | |||
1399 | - text: a string of text to be completed on. |
|
1397 | - text: a string of text to be completed on. | |
1400 |
|
1398 | |||
1401 | This is a wrapper around the completion mechanism, similar to what |
|
1399 | This is a wrapper around the completion mechanism, similar to what | |
1402 | readline does at the command line when the TAB key is hit. By |
|
1400 | readline does at the command line when the TAB key is hit. By | |
1403 | exposing it as a method, it can be used by other non-readline |
|
1401 | exposing it as a method, it can be used by other non-readline | |
1404 | environments (such as GUIs) for text completion. |
|
1402 | environments (such as GUIs) for text completion. | |
1405 |
|
1403 | |||
1406 | Simple usage example: |
|
1404 | Simple usage example: | |
1407 |
|
1405 | |||
1408 | In [7]: x = 'hello' |
|
1406 | In [7]: x = 'hello' | |
1409 |
|
1407 | |||
1410 | In [8]: x |
|
1408 | In [8]: x | |
1411 | Out[8]: 'hello' |
|
1409 | Out[8]: 'hello' | |
1412 |
|
1410 | |||
1413 | In [9]: print x |
|
1411 | In [9]: print x | |
1414 | hello |
|
1412 | hello | |
1415 |
|
1413 | |||
1416 | In [10]: _ip.complete('x.l') |
|
1414 | In [10]: _ip.complete('x.l') | |
1417 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] |
|
1415 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] | |
1418 | """ |
|
1416 | """ | |
1419 |
|
1417 | |||
1420 | # Inject names into __builtin__ so we can complete on the added names. |
|
1418 | # Inject names into __builtin__ so we can complete on the added names. | |
1421 | with self.builtin_trap: |
|
1419 | with self.builtin_trap: | |
1422 | complete = self.Completer.complete |
|
1420 | complete = self.Completer.complete | |
1423 | state = 0 |
|
1421 | state = 0 | |
1424 | # use a dict so we get unique keys, since ipyhton's multiple |
|
1422 | # use a dict so we get unique keys, since ipyhton's multiple | |
1425 | # completers can return duplicates. When we make 2.4 a requirement, |
|
1423 | # completers can return duplicates. When we make 2.4 a requirement, | |
1426 | # start using sets instead, which are faster. |
|
1424 | # start using sets instead, which are faster. | |
1427 | comps = {} |
|
1425 | comps = {} | |
1428 | while True: |
|
1426 | while True: | |
1429 | newcomp = complete(text,state,line_buffer=text) |
|
1427 | newcomp = complete(text,state,line_buffer=text) | |
1430 | if newcomp is None: |
|
1428 | if newcomp is None: | |
1431 | break |
|
1429 | break | |
1432 | comps[newcomp] = 1 |
|
1430 | comps[newcomp] = 1 | |
1433 | state += 1 |
|
1431 | state += 1 | |
1434 | outcomps = comps.keys() |
|
1432 | outcomps = comps.keys() | |
1435 | outcomps.sort() |
|
1433 | outcomps.sort() | |
1436 | #print "T:",text,"OC:",outcomps # dbg |
|
1434 | #print "T:",text,"OC:",outcomps # dbg | |
1437 | #print "vars:",self.user_ns.keys() |
|
1435 | #print "vars:",self.user_ns.keys() | |
1438 | return outcomps |
|
1436 | return outcomps | |
1439 |
|
1437 | |||
1440 | def set_custom_completer(self,completer,pos=0): |
|
1438 | def set_custom_completer(self,completer,pos=0): | |
1441 | """set_custom_completer(completer,pos=0) |
|
1439 | """set_custom_completer(completer,pos=0) | |
1442 |
|
1440 | |||
1443 | Adds a new custom completer function. |
|
1441 | Adds a new custom completer function. | |
1444 |
|
1442 | |||
1445 | The position argument (defaults to 0) is the index in the completers |
|
1443 | The position argument (defaults to 0) is the index in the completers | |
1446 | list where you want the completer to be inserted.""" |
|
1444 | list where you want the completer to be inserted.""" | |
1447 |
|
1445 | |||
1448 | newcomp = new.instancemethod(completer,self.Completer, |
|
1446 | newcomp = new.instancemethod(completer,self.Completer, | |
1449 | self.Completer.__class__) |
|
1447 | self.Completer.__class__) | |
1450 | self.Completer.matchers.insert(pos,newcomp) |
|
1448 | self.Completer.matchers.insert(pos,newcomp) | |
1451 |
|
1449 | |||
1452 | def set_completer(self): |
|
1450 | def set_completer(self): | |
1453 | """reset readline's completer to be our own.""" |
|
1451 | """reset readline's completer to be our own.""" | |
1454 | self.readline.set_completer(self.Completer.complete) |
|
1452 | self.readline.set_completer(self.Completer.complete) | |
1455 |
|
1453 | |||
1456 | #------------------------------------------------------------------------- |
|
1454 | #------------------------------------------------------------------------- | |
1457 | # Things related to readline |
|
1455 | # Things related to readline | |
1458 | #------------------------------------------------------------------------- |
|
1456 | #------------------------------------------------------------------------- | |
1459 |
|
1457 | |||
1460 | def init_readline(self): |
|
1458 | def init_readline(self): | |
1461 | """Command history completion/saving/reloading.""" |
|
1459 | """Command history completion/saving/reloading.""" | |
1462 |
|
1460 | |||
1463 | self.rl_next_input = None |
|
1461 | self.rl_next_input = None | |
1464 | self.rl_do_indent = False |
|
1462 | self.rl_do_indent = False | |
1465 |
|
1463 | |||
1466 | if not self.readline_use: |
|
1464 | if not self.readline_use: | |
1467 | return |
|
1465 | return | |
1468 |
|
1466 | |||
1469 | import IPython.utils.rlineimpl as readline |
|
1467 | import IPython.utils.rlineimpl as readline | |
1470 |
|
1468 | |||
1471 | if not readline.have_readline: |
|
1469 | if not readline.have_readline: | |
1472 | self.has_readline = 0 |
|
1470 | self.has_readline = 0 | |
1473 | self.readline = None |
|
1471 | self.readline = None | |
1474 | # no point in bugging windows users with this every time: |
|
1472 | # no point in bugging windows users with this every time: | |
1475 | warn('Readline services not available on this platform.') |
|
1473 | warn('Readline services not available on this platform.') | |
1476 | else: |
|
1474 | else: | |
1477 | sys.modules['readline'] = readline |
|
1475 | sys.modules['readline'] = readline | |
1478 | import atexit |
|
1476 | import atexit | |
1479 | from IPython.core.completer import IPCompleter |
|
1477 | from IPython.core.completer import IPCompleter | |
1480 | self.Completer = IPCompleter(self, |
|
1478 | self.Completer = IPCompleter(self, | |
1481 | self.user_ns, |
|
1479 | self.user_ns, | |
1482 | self.user_global_ns, |
|
1480 | self.user_global_ns, | |
1483 | self.readline_omit__names, |
|
1481 | self.readline_omit__names, | |
1484 | self.alias_manager.alias_table) |
|
1482 | self.alias_manager.alias_table) | |
1485 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1483 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1486 | self.strdispatchers['complete_command'] = sdisp |
|
1484 | self.strdispatchers['complete_command'] = sdisp | |
1487 | self.Completer.custom_completers = sdisp |
|
1485 | self.Completer.custom_completers = sdisp | |
1488 | # Platform-specific configuration |
|
1486 | # Platform-specific configuration | |
1489 | if os.name == 'nt': |
|
1487 | if os.name == 'nt': | |
1490 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1488 | self.readline_startup_hook = readline.set_pre_input_hook | |
1491 | else: |
|
1489 | else: | |
1492 | self.readline_startup_hook = readline.set_startup_hook |
|
1490 | self.readline_startup_hook = readline.set_startup_hook | |
1493 |
|
1491 | |||
1494 | # Load user's initrc file (readline config) |
|
1492 | # Load user's initrc file (readline config) | |
1495 | # Or if libedit is used, load editrc. |
|
1493 | # Or if libedit is used, load editrc. | |
1496 | inputrc_name = os.environ.get('INPUTRC') |
|
1494 | inputrc_name = os.environ.get('INPUTRC') | |
1497 | if inputrc_name is None: |
|
1495 | if inputrc_name is None: | |
1498 | home_dir = get_home_dir() |
|
1496 | home_dir = get_home_dir() | |
1499 | if home_dir is not None: |
|
1497 | if home_dir is not None: | |
1500 | inputrc_name = '.inputrc' |
|
1498 | inputrc_name = '.inputrc' | |
1501 | if readline.uses_libedit: |
|
1499 | if readline.uses_libedit: | |
1502 | inputrc_name = '.editrc' |
|
1500 | inputrc_name = '.editrc' | |
1503 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1501 | inputrc_name = os.path.join(home_dir, inputrc_name) | |
1504 | if os.path.isfile(inputrc_name): |
|
1502 | if os.path.isfile(inputrc_name): | |
1505 | try: |
|
1503 | try: | |
1506 | readline.read_init_file(inputrc_name) |
|
1504 | readline.read_init_file(inputrc_name) | |
1507 | except: |
|
1505 | except: | |
1508 | warn('Problems reading readline initialization file <%s>' |
|
1506 | warn('Problems reading readline initialization file <%s>' | |
1509 | % inputrc_name) |
|
1507 | % inputrc_name) | |
1510 |
|
1508 | |||
1511 | self.has_readline = 1 |
|
1509 | self.has_readline = 1 | |
1512 | self.readline = readline |
|
1510 | self.readline = readline | |
1513 | # save this in sys so embedded copies can restore it properly |
|
1511 | # save this in sys so embedded copies can restore it properly | |
1514 | sys.ipcompleter = self.Completer.complete |
|
1512 | sys.ipcompleter = self.Completer.complete | |
1515 | self.set_completer() |
|
1513 | self.set_completer() | |
1516 |
|
1514 | |||
1517 | # Configure readline according to user's prefs |
|
1515 | # Configure readline according to user's prefs | |
1518 | # This is only done if GNU readline is being used. If libedit |
|
1516 | # This is only done if GNU readline is being used. If libedit | |
1519 | # is being used (as on Leopard) the readline config is |
|
1517 | # is being used (as on Leopard) the readline config is | |
1520 | # not run as the syntax for libedit is different. |
|
1518 | # not run as the syntax for libedit is different. | |
1521 | if not readline.uses_libedit: |
|
1519 | if not readline.uses_libedit: | |
1522 | for rlcommand in self.readline_parse_and_bind: |
|
1520 | for rlcommand in self.readline_parse_and_bind: | |
1523 | #print "loading rl:",rlcommand # dbg |
|
1521 | #print "loading rl:",rlcommand # dbg | |
1524 | readline.parse_and_bind(rlcommand) |
|
1522 | readline.parse_and_bind(rlcommand) | |
1525 |
|
1523 | |||
1526 | # Remove some chars from the delimiters list. If we encounter |
|
1524 | # Remove some chars from the delimiters list. If we encounter | |
1527 | # unicode chars, discard them. |
|
1525 | # unicode chars, discard them. | |
1528 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
1526 | delims = readline.get_completer_delims().encode("ascii", "ignore") | |
1529 | delims = delims.translate(string._idmap, |
|
1527 | delims = delims.translate(string._idmap, | |
1530 | self.readline_remove_delims) |
|
1528 | self.readline_remove_delims) | |
1531 | readline.set_completer_delims(delims) |
|
1529 | readline.set_completer_delims(delims) | |
1532 | # otherwise we end up with a monster history after a while: |
|
1530 | # otherwise we end up with a monster history after a while: | |
1533 | readline.set_history_length(1000) |
|
1531 | readline.set_history_length(1000) | |
1534 | try: |
|
1532 | try: | |
1535 | #print '*** Reading readline history' # dbg |
|
1533 | #print '*** Reading readline history' # dbg | |
1536 | readline.read_history_file(self.histfile) |
|
1534 | readline.read_history_file(self.histfile) | |
1537 | except IOError: |
|
1535 | except IOError: | |
1538 | pass # It doesn't exist yet. |
|
1536 | pass # It doesn't exist yet. | |
1539 |
|
1537 | |||
1540 | atexit.register(self.atexit_operations) |
|
1538 | atexit.register(self.atexit_operations) | |
1541 | del atexit |
|
1539 | del atexit | |
1542 |
|
1540 | |||
1543 | # Configure auto-indent for all platforms |
|
1541 | # Configure auto-indent for all platforms | |
1544 | self.set_autoindent(self.autoindent) |
|
1542 | self.set_autoindent(self.autoindent) | |
1545 |
|
1543 | |||
1546 | def set_next_input(self, s): |
|
1544 | def set_next_input(self, s): | |
1547 | """ Sets the 'default' input string for the next command line. |
|
1545 | """ Sets the 'default' input string for the next command line. | |
1548 |
|
1546 | |||
1549 | Requires readline. |
|
1547 | Requires readline. | |
1550 |
|
1548 | |||
1551 | Example: |
|
1549 | Example: | |
1552 |
|
1550 | |||
1553 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1551 | [D:\ipython]|1> _ip.set_next_input("Hello Word") | |
1554 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1552 | [D:\ipython]|2> Hello Word_ # cursor is here | |
1555 | """ |
|
1553 | """ | |
1556 |
|
1554 | |||
1557 | self.rl_next_input = s |
|
1555 | self.rl_next_input = s | |
1558 |
|
1556 | |||
1559 | def pre_readline(self): |
|
1557 | def pre_readline(self): | |
1560 | """readline hook to be used at the start of each line. |
|
1558 | """readline hook to be used at the start of each line. | |
1561 |
|
1559 | |||
1562 | Currently it handles auto-indent only.""" |
|
1560 | Currently it handles auto-indent only.""" | |
1563 |
|
1561 | |||
1564 | #debugx('self.indent_current_nsp','pre_readline:') |
|
1562 | #debugx('self.indent_current_nsp','pre_readline:') | |
1565 |
|
1563 | |||
1566 | if self.rl_do_indent: |
|
1564 | if self.rl_do_indent: | |
1567 | self.readline.insert_text(self._indent_current_str()) |
|
1565 | self.readline.insert_text(self._indent_current_str()) | |
1568 | if self.rl_next_input is not None: |
|
1566 | if self.rl_next_input is not None: | |
1569 | self.readline.insert_text(self.rl_next_input) |
|
1567 | self.readline.insert_text(self.rl_next_input) | |
1570 | self.rl_next_input = None |
|
1568 | self.rl_next_input = None | |
1571 |
|
1569 | |||
1572 | def _indent_current_str(self): |
|
1570 | def _indent_current_str(self): | |
1573 | """return the current level of indentation as a string""" |
|
1571 | """return the current level of indentation as a string""" | |
1574 | return self.indent_current_nsp * ' ' |
|
1572 | return self.indent_current_nsp * ' ' | |
1575 |
|
1573 | |||
1576 | #------------------------------------------------------------------------- |
|
1574 | #------------------------------------------------------------------------- | |
1577 | # Things related to magics |
|
1575 | # Things related to magics | |
1578 | #------------------------------------------------------------------------- |
|
1576 | #------------------------------------------------------------------------- | |
1579 |
|
1577 | |||
1580 | def init_magics(self): |
|
1578 | def init_magics(self): | |
1581 | # Set user colors (don't do it in the constructor above so that it |
|
1579 | # Set user colors (don't do it in the constructor above so that it | |
1582 | # doesn't crash if colors option is invalid) |
|
1580 | # doesn't crash if colors option is invalid) | |
1583 | self.magic_colors(self.colors) |
|
1581 | self.magic_colors(self.colors) | |
1584 |
|
1582 | |||
1585 | def magic(self,arg_s): |
|
1583 | def magic(self,arg_s): | |
1586 | """Call a magic function by name. |
|
1584 | """Call a magic function by name. | |
1587 |
|
1585 | |||
1588 | Input: a string containing the name of the magic function to call and any |
|
1586 | Input: a string containing the name of the magic function to call and any | |
1589 | additional arguments to be passed to the magic. |
|
1587 | additional arguments to be passed to the magic. | |
1590 |
|
1588 | |||
1591 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
1589 | magic('name -opt foo bar') is equivalent to typing at the ipython | |
1592 | prompt: |
|
1590 | prompt: | |
1593 |
|
1591 | |||
1594 | In[1]: %name -opt foo bar |
|
1592 | In[1]: %name -opt foo bar | |
1595 |
|
1593 | |||
1596 | To call a magic without arguments, simply use magic('name'). |
|
1594 | To call a magic without arguments, simply use magic('name'). | |
1597 |
|
1595 | |||
1598 | This provides a proper Python function to call IPython's magics in any |
|
1596 | This provides a proper Python function to call IPython's magics in any | |
1599 | valid Python code you can type at the interpreter, including loops and |
|
1597 | valid Python code you can type at the interpreter, including loops and | |
1600 | compound statements. |
|
1598 | compound statements. | |
1601 | """ |
|
1599 | """ | |
1602 |
|
1600 | |||
1603 | args = arg_s.split(' ',1) |
|
1601 | args = arg_s.split(' ',1) | |
1604 | magic_name = args[0] |
|
1602 | magic_name = args[0] | |
1605 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
1603 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) | |
1606 |
|
1604 | |||
1607 | try: |
|
1605 | try: | |
1608 | magic_args = args[1] |
|
1606 | magic_args = args[1] | |
1609 | except IndexError: |
|
1607 | except IndexError: | |
1610 | magic_args = '' |
|
1608 | magic_args = '' | |
1611 | fn = getattr(self,'magic_'+magic_name,None) |
|
1609 | fn = getattr(self,'magic_'+magic_name,None) | |
1612 | if fn is None: |
|
1610 | if fn is None: | |
1613 | error("Magic function `%s` not found." % magic_name) |
|
1611 | error("Magic function `%s` not found." % magic_name) | |
1614 | else: |
|
1612 | else: | |
1615 | magic_args = self.var_expand(magic_args,1) |
|
1613 | magic_args = self.var_expand(magic_args,1) | |
1616 | with nested(self.builtin_trap,): |
|
1614 | with nested(self.builtin_trap,): | |
1617 | result = fn(magic_args) |
|
1615 | result = fn(magic_args) | |
1618 | # Unfortunately, the return statement is what will trigger |
|
1616 | # Unfortunately, the return statement is what will trigger | |
1619 | # the displayhook, but it is no longer set! |
|
1617 | # the displayhook, but it is no longer set! | |
1620 | return result |
|
1618 | return result | |
1621 |
|
1619 | |||
1622 | def define_magic(self, magicname, func): |
|
1620 | def define_magic(self, magicname, func): | |
1623 | """Expose own function as magic function for ipython |
|
1621 | """Expose own function as magic function for ipython | |
1624 |
|
1622 | |||
1625 | def foo_impl(self,parameter_s=''): |
|
1623 | def foo_impl(self,parameter_s=''): | |
1626 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
1624 | 'My very own magic!. (Use docstrings, IPython reads them).' | |
1627 | print 'Magic function. Passed parameter is between < >:' |
|
1625 | print 'Magic function. Passed parameter is between < >:' | |
1628 | print '<%s>' % parameter_s |
|
1626 | print '<%s>' % parameter_s | |
1629 | print 'The self object is:',self |
|
1627 | print 'The self object is:',self | |
1630 |
|
1628 | |||
1631 | self.define_magic('foo',foo_impl) |
|
1629 | self.define_magic('foo',foo_impl) | |
1632 | """ |
|
1630 | """ | |
1633 |
|
1631 | |||
1634 | import new |
|
1632 | import new | |
1635 | im = new.instancemethod(func,self, self.__class__) |
|
1633 | im = new.instancemethod(func,self, self.__class__) | |
1636 | old = getattr(self, "magic_" + magicname, None) |
|
1634 | old = getattr(self, "magic_" + magicname, None) | |
1637 | setattr(self, "magic_" + magicname, im) |
|
1635 | setattr(self, "magic_" + magicname, im) | |
1638 | return old |
|
1636 | return old | |
1639 |
|
1637 | |||
1640 | #------------------------------------------------------------------------- |
|
1638 | #------------------------------------------------------------------------- | |
1641 | # Things related to macros |
|
1639 | # Things related to macros | |
1642 | #------------------------------------------------------------------------- |
|
1640 | #------------------------------------------------------------------------- | |
1643 |
|
1641 | |||
1644 | def define_macro(self, name, themacro): |
|
1642 | def define_macro(self, name, themacro): | |
1645 | """Define a new macro |
|
1643 | """Define a new macro | |
1646 |
|
1644 | |||
1647 | Parameters |
|
1645 | Parameters | |
1648 | ---------- |
|
1646 | ---------- | |
1649 | name : str |
|
1647 | name : str | |
1650 | The name of the macro. |
|
1648 | The name of the macro. | |
1651 | themacro : str or Macro |
|
1649 | themacro : str or Macro | |
1652 | The action to do upon invoking the macro. If a string, a new |
|
1650 | The action to do upon invoking the macro. If a string, a new | |
1653 | Macro object is created by passing the string to it. |
|
1651 | Macro object is created by passing the string to it. | |
1654 | """ |
|
1652 | """ | |
1655 |
|
1653 | |||
1656 | from IPython.core import macro |
|
1654 | from IPython.core import macro | |
1657 |
|
1655 | |||
1658 | if isinstance(themacro, basestring): |
|
1656 | if isinstance(themacro, basestring): | |
1659 | themacro = macro.Macro(themacro) |
|
1657 | themacro = macro.Macro(themacro) | |
1660 | if not isinstance(themacro, macro.Macro): |
|
1658 | if not isinstance(themacro, macro.Macro): | |
1661 | raise ValueError('A macro must be a string or a Macro instance.') |
|
1659 | raise ValueError('A macro must be a string or a Macro instance.') | |
1662 | self.user_ns[name] = themacro |
|
1660 | self.user_ns[name] = themacro | |
1663 |
|
1661 | |||
1664 | #------------------------------------------------------------------------- |
|
1662 | #------------------------------------------------------------------------- | |
1665 | # Things related to the running of system commands |
|
1663 | # Things related to the running of system commands | |
1666 | #------------------------------------------------------------------------- |
|
1664 | #------------------------------------------------------------------------- | |
1667 |
|
1665 | |||
1668 | def system(self, cmd): |
|
1666 | def system(self, cmd): | |
1669 | """Make a system call, using IPython.""" |
|
1667 | """Make a system call, using IPython.""" | |
1670 | return self.hooks.shell_hook(self.var_expand(cmd, depth=2)) |
|
1668 | return self.hooks.shell_hook(self.var_expand(cmd, depth=2)) | |
1671 |
|
1669 | |||
1672 | #------------------------------------------------------------------------- |
|
1670 | #------------------------------------------------------------------------- | |
1673 | # Things related to aliases |
|
1671 | # Things related to aliases | |
1674 | #------------------------------------------------------------------------- |
|
1672 | #------------------------------------------------------------------------- | |
1675 |
|
1673 | |||
1676 | def init_alias(self): |
|
1674 | def init_alias(self): | |
1677 | self.alias_manager = AliasManager(self, config=self.config) |
|
1675 | self.alias_manager = AliasManager(self, config=self.config) | |
1678 | self.ns_table['alias'] = self.alias_manager.alias_table, |
|
1676 | self.ns_table['alias'] = self.alias_manager.alias_table, | |
1679 |
|
1677 | |||
1680 | #------------------------------------------------------------------------- |
|
1678 | #------------------------------------------------------------------------- | |
1681 | # Things related to the running of code |
|
1679 | # Things related to the running of code | |
1682 | #------------------------------------------------------------------------- |
|
1680 | #------------------------------------------------------------------------- | |
1683 |
|
1681 | |||
1684 | def ex(self, cmd): |
|
1682 | def ex(self, cmd): | |
1685 | """Execute a normal python statement in user namespace.""" |
|
1683 | """Execute a normal python statement in user namespace.""" | |
1686 | with nested(self.builtin_trap,): |
|
1684 | with nested(self.builtin_trap,): | |
1687 | exec cmd in self.user_global_ns, self.user_ns |
|
1685 | exec cmd in self.user_global_ns, self.user_ns | |
1688 |
|
1686 | |||
1689 | def ev(self, expr): |
|
1687 | def ev(self, expr): | |
1690 | """Evaluate python expression expr in user namespace. |
|
1688 | """Evaluate python expression expr in user namespace. | |
1691 |
|
1689 | |||
1692 | Returns the result of evaluation |
|
1690 | Returns the result of evaluation | |
1693 | """ |
|
1691 | """ | |
1694 | with nested(self.builtin_trap,): |
|
1692 | with nested(self.builtin_trap,): | |
1695 | return eval(expr, self.user_global_ns, self.user_ns) |
|
1693 | return eval(expr, self.user_global_ns, self.user_ns) | |
1696 |
|
1694 | |||
1697 | def mainloop(self, display_banner=None): |
|
1695 | def mainloop(self, display_banner=None): | |
1698 | """Start the mainloop. |
|
1696 | """Start the mainloop. | |
1699 |
|
1697 | |||
1700 | If an optional banner argument is given, it will override the |
|
1698 | If an optional banner argument is given, it will override the | |
1701 | internally created default banner. |
|
1699 | internally created default banner. | |
1702 | """ |
|
1700 | """ | |
1703 |
|
1701 | |||
1704 | with nested(self.builtin_trap, self.display_trap): |
|
1702 | with nested(self.builtin_trap, self.display_trap): | |
1705 | if self.c: # Emulate Python's -c option |
|
|||
1706 | self.exec_init_cmd() |
|
|||
1707 |
|
1703 | |||
1708 | # if you run stuff with -c <cmd>, raw hist is not updated |
|
1704 | # if you run stuff with -c <cmd>, raw hist is not updated | |
1709 | # ensure that it's in sync |
|
1705 | # ensure that it's in sync | |
1710 | if len(self.input_hist) != len (self.input_hist_raw): |
|
1706 | if len(self.input_hist) != len (self.input_hist_raw): | |
1711 | self.input_hist_raw = InputList(self.input_hist) |
|
1707 | self.input_hist_raw = InputList(self.input_hist) | |
1712 |
|
1708 | |||
1713 | while 1: |
|
1709 | while 1: | |
1714 | try: |
|
1710 | try: | |
1715 | self.interact(display_banner=display_banner) |
|
1711 | self.interact(display_banner=display_banner) | |
1716 | #self.interact_with_readline() |
|
1712 | #self.interact_with_readline() | |
1717 | # XXX for testing of a readline-decoupled repl loop, call |
|
1713 | # XXX for testing of a readline-decoupled repl loop, call | |
1718 | # interact_with_readline above |
|
1714 | # interact_with_readline above | |
1719 | break |
|
1715 | break | |
1720 | except KeyboardInterrupt: |
|
1716 | except KeyboardInterrupt: | |
1721 | # this should not be necessary, but KeyboardInterrupt |
|
1717 | # this should not be necessary, but KeyboardInterrupt | |
1722 | # handling seems rather unpredictable... |
|
1718 | # handling seems rather unpredictable... | |
1723 | self.write("\nKeyboardInterrupt in interact()\n") |
|
1719 | self.write("\nKeyboardInterrupt in interact()\n") | |
1724 |
|
1720 | |||
1725 | def exec_init_cmd(self): |
|
|||
1726 | """Execute a command given at the command line. |
|
|||
1727 |
|
||||
1728 | This emulates Python's -c option.""" |
|
|||
1729 |
|
||||
1730 | #sys.argv = ['-c'] |
|
|||
1731 | self.push_line(self.prefilter_manager.prefilter_lines(self.c, False)) |
|
|||
1732 | if not self.interactive: |
|
|||
1733 | self.ask_exit() |
|
|||
1734 |
|
||||
1735 | def interact_prompt(self): |
|
1721 | def interact_prompt(self): | |
1736 | """ Print the prompt (in read-eval-print loop) |
|
1722 | """ Print the prompt (in read-eval-print loop) | |
1737 |
|
1723 | |||
1738 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1724 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not | |
1739 | used in standard IPython flow. |
|
1725 | used in standard IPython flow. | |
1740 | """ |
|
1726 | """ | |
1741 | if self.more: |
|
1727 | if self.more: | |
1742 | try: |
|
1728 | try: | |
1743 | prompt = self.hooks.generate_prompt(True) |
|
1729 | prompt = self.hooks.generate_prompt(True) | |
1744 | except: |
|
1730 | except: | |
1745 | self.showtraceback() |
|
1731 | self.showtraceback() | |
1746 | if self.autoindent: |
|
1732 | if self.autoindent: | |
1747 | self.rl_do_indent = True |
|
1733 | self.rl_do_indent = True | |
1748 |
|
1734 | |||
1749 | else: |
|
1735 | else: | |
1750 | try: |
|
1736 | try: | |
1751 | prompt = self.hooks.generate_prompt(False) |
|
1737 | prompt = self.hooks.generate_prompt(False) | |
1752 | except: |
|
1738 | except: | |
1753 | self.showtraceback() |
|
1739 | self.showtraceback() | |
1754 | self.write(prompt) |
|
1740 | self.write(prompt) | |
1755 |
|
1741 | |||
1756 | def interact_handle_input(self,line): |
|
1742 | def interact_handle_input(self,line): | |
1757 | """ Handle the input line (in read-eval-print loop) |
|
1743 | """ Handle the input line (in read-eval-print loop) | |
1758 |
|
1744 | |||
1759 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1745 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not | |
1760 | used in standard IPython flow. |
|
1746 | used in standard IPython flow. | |
1761 | """ |
|
1747 | """ | |
1762 | if line.lstrip() == line: |
|
1748 | if line.lstrip() == line: | |
1763 | self.shadowhist.add(line.strip()) |
|
1749 | self.shadowhist.add(line.strip()) | |
1764 | lineout = self.prefilter_manager.prefilter_lines(line,self.more) |
|
1750 | lineout = self.prefilter_manager.prefilter_lines(line,self.more) | |
1765 |
|
1751 | |||
1766 | if line.strip(): |
|
1752 | if line.strip(): | |
1767 | if self.more: |
|
1753 | if self.more: | |
1768 | self.input_hist_raw[-1] += '%s\n' % line |
|
1754 | self.input_hist_raw[-1] += '%s\n' % line | |
1769 | else: |
|
1755 | else: | |
1770 | self.input_hist_raw.append('%s\n' % line) |
|
1756 | self.input_hist_raw.append('%s\n' % line) | |
1771 |
|
1757 | |||
1772 |
|
1758 | |||
1773 | self.more = self.push_line(lineout) |
|
1759 | self.more = self.push_line(lineout) | |
1774 | if (self.SyntaxTB.last_syntax_error and |
|
1760 | if (self.SyntaxTB.last_syntax_error and | |
1775 | self.autoedit_syntax): |
|
1761 | self.autoedit_syntax): | |
1776 | self.edit_syntax_error() |
|
1762 | self.edit_syntax_error() | |
1777 |
|
1763 | |||
1778 | def interact_with_readline(self): |
|
1764 | def interact_with_readline(self): | |
1779 | """ Demo of using interact_handle_input, interact_prompt |
|
1765 | """ Demo of using interact_handle_input, interact_prompt | |
1780 |
|
1766 | |||
1781 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), |
|
1767 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), | |
1782 | it should work like this. |
|
1768 | it should work like this. | |
1783 | """ |
|
1769 | """ | |
1784 | self.readline_startup_hook(self.pre_readline) |
|
1770 | self.readline_startup_hook(self.pre_readline) | |
1785 | while not self.exit_now: |
|
1771 | while not self.exit_now: | |
1786 | self.interact_prompt() |
|
1772 | self.interact_prompt() | |
1787 | if self.more: |
|
1773 | if self.more: | |
1788 | self.rl_do_indent = True |
|
1774 | self.rl_do_indent = True | |
1789 | else: |
|
1775 | else: | |
1790 | self.rl_do_indent = False |
|
1776 | self.rl_do_indent = False | |
1791 | line = raw_input_original().decode(self.stdin_encoding) |
|
1777 | line = raw_input_original().decode(self.stdin_encoding) | |
1792 | self.interact_handle_input(line) |
|
1778 | self.interact_handle_input(line) | |
1793 |
|
1779 | |||
1794 | def interact(self, display_banner=None): |
|
1780 | def interact(self, display_banner=None): | |
1795 | """Closely emulate the interactive Python console.""" |
|
1781 | """Closely emulate the interactive Python console.""" | |
1796 |
|
1782 | |||
1797 | # batch run -> do not interact |
|
1783 | # batch run -> do not interact | |
1798 | if self.exit_now: |
|
1784 | if self.exit_now: | |
1799 | return |
|
1785 | return | |
1800 |
|
1786 | |||
1801 | if display_banner is None: |
|
1787 | if display_banner is None: | |
1802 | display_banner = self.display_banner |
|
1788 | display_banner = self.display_banner | |
1803 | if display_banner: |
|
1789 | if display_banner: | |
1804 | self.show_banner() |
|
1790 | self.show_banner() | |
1805 |
|
1791 | |||
1806 | more = 0 |
|
1792 | more = 0 | |
1807 |
|
1793 | |||
1808 | # Mark activity in the builtins |
|
1794 | # Mark activity in the builtins | |
1809 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1795 | __builtin__.__dict__['__IPYTHON__active'] += 1 | |
1810 |
|
1796 | |||
1811 | if self.has_readline: |
|
1797 | if self.has_readline: | |
1812 | self.readline_startup_hook(self.pre_readline) |
|
1798 | self.readline_startup_hook(self.pre_readline) | |
1813 | # exit_now is set by a call to %Exit or %Quit, through the |
|
1799 | # exit_now is set by a call to %Exit or %Quit, through the | |
1814 | # ask_exit callback. |
|
1800 | # ask_exit callback. | |
1815 |
|
1801 | |||
1816 | while not self.exit_now: |
|
1802 | while not self.exit_now: | |
1817 | self.hooks.pre_prompt_hook() |
|
1803 | self.hooks.pre_prompt_hook() | |
1818 | if more: |
|
1804 | if more: | |
1819 | try: |
|
1805 | try: | |
1820 | prompt = self.hooks.generate_prompt(True) |
|
1806 | prompt = self.hooks.generate_prompt(True) | |
1821 | except: |
|
1807 | except: | |
1822 | self.showtraceback() |
|
1808 | self.showtraceback() | |
1823 | if self.autoindent: |
|
1809 | if self.autoindent: | |
1824 | self.rl_do_indent = True |
|
1810 | self.rl_do_indent = True | |
1825 |
|
1811 | |||
1826 | else: |
|
1812 | else: | |
1827 | try: |
|
1813 | try: | |
1828 | prompt = self.hooks.generate_prompt(False) |
|
1814 | prompt = self.hooks.generate_prompt(False) | |
1829 | except: |
|
1815 | except: | |
1830 | self.showtraceback() |
|
1816 | self.showtraceback() | |
1831 | try: |
|
1817 | try: | |
1832 | line = self.raw_input(prompt, more) |
|
1818 | line = self.raw_input(prompt, more) | |
1833 | if self.exit_now: |
|
1819 | if self.exit_now: | |
1834 | # quick exit on sys.std[in|out] close |
|
1820 | # quick exit on sys.std[in|out] close | |
1835 | break |
|
1821 | break | |
1836 | if self.autoindent: |
|
1822 | if self.autoindent: | |
1837 | self.rl_do_indent = False |
|
1823 | self.rl_do_indent = False | |
1838 |
|
1824 | |||
1839 | except KeyboardInterrupt: |
|
1825 | except KeyboardInterrupt: | |
1840 | #double-guard against keyboardinterrupts during kbdint handling |
|
1826 | #double-guard against keyboardinterrupts during kbdint handling | |
1841 | try: |
|
1827 | try: | |
1842 | self.write('\nKeyboardInterrupt\n') |
|
1828 | self.write('\nKeyboardInterrupt\n') | |
1843 | self.resetbuffer() |
|
1829 | self.resetbuffer() | |
1844 | # keep cache in sync with the prompt counter: |
|
1830 | # keep cache in sync with the prompt counter: | |
1845 | self.outputcache.prompt_count -= 1 |
|
1831 | self.outputcache.prompt_count -= 1 | |
1846 |
|
1832 | |||
1847 | if self.autoindent: |
|
1833 | if self.autoindent: | |
1848 | self.indent_current_nsp = 0 |
|
1834 | self.indent_current_nsp = 0 | |
1849 | more = 0 |
|
1835 | more = 0 | |
1850 | except KeyboardInterrupt: |
|
1836 | except KeyboardInterrupt: | |
1851 | pass |
|
1837 | pass | |
1852 | except EOFError: |
|
1838 | except EOFError: | |
1853 | if self.autoindent: |
|
1839 | if self.autoindent: | |
1854 | self.rl_do_indent = False |
|
1840 | self.rl_do_indent = False | |
1855 | self.readline_startup_hook(None) |
|
1841 | self.readline_startup_hook(None) | |
1856 | self.write('\n') |
|
1842 | self.write('\n') | |
1857 | self.exit() |
|
1843 | self.exit() | |
1858 | except bdb.BdbQuit: |
|
1844 | except bdb.BdbQuit: | |
1859 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
1845 | warn('The Python debugger has exited with a BdbQuit exception.\n' | |
1860 | 'Because of how pdb handles the stack, it is impossible\n' |
|
1846 | 'Because of how pdb handles the stack, it is impossible\n' | |
1861 | 'for IPython to properly format this particular exception.\n' |
|
1847 | 'for IPython to properly format this particular exception.\n' | |
1862 | 'IPython will resume normal operation.') |
|
1848 | 'IPython will resume normal operation.') | |
1863 | except: |
|
1849 | except: | |
1864 | # exceptions here are VERY RARE, but they can be triggered |
|
1850 | # exceptions here are VERY RARE, but they can be triggered | |
1865 | # asynchronously by signal handlers, for example. |
|
1851 | # asynchronously by signal handlers, for example. | |
1866 | self.showtraceback() |
|
1852 | self.showtraceback() | |
1867 | else: |
|
1853 | else: | |
1868 | more = self.push_line(line) |
|
1854 | more = self.push_line(line) | |
1869 | if (self.SyntaxTB.last_syntax_error and |
|
1855 | if (self.SyntaxTB.last_syntax_error and | |
1870 | self.autoedit_syntax): |
|
1856 | self.autoedit_syntax): | |
1871 | self.edit_syntax_error() |
|
1857 | self.edit_syntax_error() | |
1872 |
|
1858 | |||
1873 | # We are off again... |
|
1859 | # We are off again... | |
1874 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
1860 | __builtin__.__dict__['__IPYTHON__active'] -= 1 | |
1875 |
|
1861 | |||
1876 | def safe_execfile(self, fname, *where, **kw): |
|
1862 | def safe_execfile(self, fname, *where, **kw): | |
1877 | """A safe version of the builtin execfile(). |
|
1863 | """A safe version of the builtin execfile(). | |
1878 |
|
1864 | |||
1879 | This version will never throw an exception, but instead print |
|
1865 | This version will never throw an exception, but instead print | |
1880 | helpful error messages to the screen. This only works on pure |
|
1866 | helpful error messages to the screen. This only works on pure | |
1881 | Python files with the .py extension. |
|
1867 | Python files with the .py extension. | |
1882 |
|
1868 | |||
1883 | Parameters |
|
1869 | Parameters | |
1884 | ---------- |
|
1870 | ---------- | |
1885 | fname : string |
|
1871 | fname : string | |
1886 | The name of the file to be executed. |
|
1872 | The name of the file to be executed. | |
1887 | where : tuple |
|
1873 | where : tuple | |
1888 | One or two namespaces, passed to execfile() as (globals,locals). |
|
1874 | One or two namespaces, passed to execfile() as (globals,locals). | |
1889 | If only one is given, it is passed as both. |
|
1875 | If only one is given, it is passed as both. | |
1890 | exit_ignore : bool (False) |
|
1876 | exit_ignore : bool (False) | |
1891 | If True, then don't print errors for non-zero exit statuses. |
|
1877 | If True, then don't print errors for non-zero exit statuses. | |
1892 | """ |
|
1878 | """ | |
1893 | kw.setdefault('exit_ignore', False) |
|
1879 | kw.setdefault('exit_ignore', False) | |
1894 |
|
1880 | |||
1895 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
1881 | fname = os.path.abspath(os.path.expanduser(fname)) | |
1896 |
|
1882 | |||
1897 | # Make sure we have a .py file |
|
1883 | # Make sure we have a .py file | |
1898 | if not fname.endswith('.py'): |
|
1884 | if not fname.endswith('.py'): | |
1899 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
1885 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
1900 |
|
1886 | |||
1901 | # Make sure we can open the file |
|
1887 | # Make sure we can open the file | |
1902 | try: |
|
1888 | try: | |
1903 | with open(fname) as thefile: |
|
1889 | with open(fname) as thefile: | |
1904 | pass |
|
1890 | pass | |
1905 | except: |
|
1891 | except: | |
1906 | warn('Could not open file <%s> for safe execution.' % fname) |
|
1892 | warn('Could not open file <%s> for safe execution.' % fname) | |
1907 | return |
|
1893 | return | |
1908 |
|
1894 | |||
1909 | # Find things also in current directory. This is needed to mimic the |
|
1895 | # Find things also in current directory. This is needed to mimic the | |
1910 | # behavior of running a script from the system command line, where |
|
1896 | # behavior of running a script from the system command line, where | |
1911 | # Python inserts the script's directory into sys.path |
|
1897 | # Python inserts the script's directory into sys.path | |
1912 | dname = os.path.dirname(fname) |
|
1898 | dname = os.path.dirname(fname) | |
1913 |
|
1899 | |||
1914 | with prepended_to_syspath(dname): |
|
1900 | with prepended_to_syspath(dname): | |
1915 | try: |
|
1901 | try: | |
1916 | if sys.platform == 'win32' and sys.version_info < (2,5,1): |
|
1902 | if sys.platform == 'win32' and sys.version_info < (2,5,1): | |
1917 | # Work around a bug in Python for Windows. The bug was |
|
1903 | # Work around a bug in Python for Windows. The bug was | |
1918 | # fixed in in Python 2.5 r54159 and 54158, but that's still |
|
1904 | # fixed in in Python 2.5 r54159 and 54158, but that's still | |
1919 | # SVN Python as of March/07. For details, see: |
|
1905 | # SVN Python as of March/07. For details, see: | |
1920 | # http://projects.scipy.org/ipython/ipython/ticket/123 |
|
1906 | # http://projects.scipy.org/ipython/ipython/ticket/123 | |
1921 | try: |
|
1907 | try: | |
1922 | globs,locs = where[0:2] |
|
1908 | globs,locs = where[0:2] | |
1923 | except: |
|
1909 | except: | |
1924 | try: |
|
1910 | try: | |
1925 | globs = locs = where[0] |
|
1911 | globs = locs = where[0] | |
1926 | except: |
|
1912 | except: | |
1927 | globs = locs = globals() |
|
1913 | globs = locs = globals() | |
1928 | exec file(fname) in globs,locs |
|
1914 | exec file(fname) in globs,locs | |
1929 | else: |
|
1915 | else: | |
1930 | execfile(fname,*where) |
|
1916 | execfile(fname,*where) | |
1931 | except SyntaxError: |
|
1917 | except SyntaxError: | |
1932 | self.showsyntaxerror() |
|
1918 | self.showsyntaxerror() | |
1933 | warn('Failure executing file: <%s>' % fname) |
|
1919 | warn('Failure executing file: <%s>' % fname) | |
1934 | except SystemExit, status: |
|
1920 | except SystemExit, status: | |
1935 | # Code that correctly sets the exit status flag to success (0) |
|
1921 | # Code that correctly sets the exit status flag to success (0) | |
1936 | # shouldn't be bothered with a traceback. Note that a plain |
|
1922 | # shouldn't be bothered with a traceback. Note that a plain | |
1937 | # sys.exit() does NOT set the message to 0 (it's empty) so that |
|
1923 | # sys.exit() does NOT set the message to 0 (it's empty) so that | |
1938 | # will still get a traceback. Note that the structure of the |
|
1924 | # will still get a traceback. Note that the structure of the | |
1939 | # SystemExit exception changed between Python 2.4 and 2.5, so |
|
1925 | # SystemExit exception changed between Python 2.4 and 2.5, so | |
1940 | # the checks must be done in a version-dependent way. |
|
1926 | # the checks must be done in a version-dependent way. | |
1941 | show = False |
|
1927 | show = False | |
1942 | if status.message!=0 and not kw['exit_ignore']: |
|
1928 | if status.message!=0 and not kw['exit_ignore']: | |
1943 | show = True |
|
1929 | show = True | |
1944 | if show: |
|
1930 | if show: | |
1945 | self.showtraceback() |
|
1931 | self.showtraceback() | |
1946 | warn('Failure executing file: <%s>' % fname) |
|
1932 | warn('Failure executing file: <%s>' % fname) | |
1947 | except: |
|
1933 | except: | |
1948 | self.showtraceback() |
|
1934 | self.showtraceback() | |
1949 | warn('Failure executing file: <%s>' % fname) |
|
1935 | warn('Failure executing file: <%s>' % fname) | |
1950 |
|
1936 | |||
1951 | def safe_execfile_ipy(self, fname): |
|
1937 | def safe_execfile_ipy(self, fname): | |
1952 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
1938 | """Like safe_execfile, but for .ipy files with IPython syntax. | |
1953 |
|
1939 | |||
1954 | Parameters |
|
1940 | Parameters | |
1955 | ---------- |
|
1941 | ---------- | |
1956 | fname : str |
|
1942 | fname : str | |
1957 | The name of the file to execute. The filename must have a |
|
1943 | The name of the file to execute. The filename must have a | |
1958 | .ipy extension. |
|
1944 | .ipy extension. | |
1959 | """ |
|
1945 | """ | |
1960 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
1946 | fname = os.path.abspath(os.path.expanduser(fname)) | |
1961 |
|
1947 | |||
1962 | # Make sure we have a .py file |
|
1948 | # Make sure we have a .py file | |
1963 | if not fname.endswith('.ipy'): |
|
1949 | if not fname.endswith('.ipy'): | |
1964 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
1950 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
1965 |
|
1951 | |||
1966 | # Make sure we can open the file |
|
1952 | # Make sure we can open the file | |
1967 | try: |
|
1953 | try: | |
1968 | with open(fname) as thefile: |
|
1954 | with open(fname) as thefile: | |
1969 | pass |
|
1955 | pass | |
1970 | except: |
|
1956 | except: | |
1971 | warn('Could not open file <%s> for safe execution.' % fname) |
|
1957 | warn('Could not open file <%s> for safe execution.' % fname) | |
1972 | return |
|
1958 | return | |
1973 |
|
1959 | |||
1974 | # Find things also in current directory. This is needed to mimic the |
|
1960 | # Find things also in current directory. This is needed to mimic the | |
1975 | # behavior of running a script from the system command line, where |
|
1961 | # behavior of running a script from the system command line, where | |
1976 | # Python inserts the script's directory into sys.path |
|
1962 | # Python inserts the script's directory into sys.path | |
1977 | dname = os.path.dirname(fname) |
|
1963 | dname = os.path.dirname(fname) | |
1978 |
|
1964 | |||
1979 | with prepended_to_syspath(dname): |
|
1965 | with prepended_to_syspath(dname): | |
1980 | try: |
|
1966 | try: | |
1981 | with open(fname) as thefile: |
|
1967 | with open(fname) as thefile: | |
1982 | script = thefile.read() |
|
1968 | script = thefile.read() | |
1983 | # self.runlines currently captures all exceptions |
|
1969 | # self.runlines currently captures all exceptions | |
1984 | # raise in user code. It would be nice if there were |
|
1970 | # raise in user code. It would be nice if there were | |
1985 | # versions of runlines, execfile that did raise, so |
|
1971 | # versions of runlines, execfile that did raise, so | |
1986 | # we could catch the errors. |
|
1972 | # we could catch the errors. | |
1987 | self.runlines(script, clean=True) |
|
1973 | self.runlines(script, clean=True) | |
1988 | except: |
|
1974 | except: | |
1989 | self.showtraceback() |
|
1975 | self.showtraceback() | |
1990 | warn('Unknown failure executing file: <%s>' % fname) |
|
1976 | warn('Unknown failure executing file: <%s>' % fname) | |
1991 |
|
1977 | |||
1992 | def _is_secondary_block_start(self, s): |
|
1978 | def _is_secondary_block_start(self, s): | |
1993 | if not s.endswith(':'): |
|
1979 | if not s.endswith(':'): | |
1994 | return False |
|
1980 | return False | |
1995 | if (s.startswith('elif') or |
|
1981 | if (s.startswith('elif') or | |
1996 | s.startswith('else') or |
|
1982 | s.startswith('else') or | |
1997 | s.startswith('except') or |
|
1983 | s.startswith('except') or | |
1998 | s.startswith('finally')): |
|
1984 | s.startswith('finally')): | |
1999 | return True |
|
1985 | return True | |
2000 |
|
1986 | |||
2001 | def cleanup_ipy_script(self, script): |
|
1987 | def cleanup_ipy_script(self, script): | |
2002 | """Make a script safe for self.runlines() |
|
1988 | """Make a script safe for self.runlines() | |
2003 |
|
1989 | |||
2004 | Currently, IPython is lines based, with blocks being detected by |
|
1990 | Currently, IPython is lines based, with blocks being detected by | |
2005 | empty lines. This is a problem for block based scripts that may |
|
1991 | empty lines. This is a problem for block based scripts that may | |
2006 | not have empty lines after blocks. This script adds those empty |
|
1992 | not have empty lines after blocks. This script adds those empty | |
2007 | lines to make scripts safe for running in the current line based |
|
1993 | lines to make scripts safe for running in the current line based | |
2008 | IPython. |
|
1994 | IPython. | |
2009 | """ |
|
1995 | """ | |
2010 | res = [] |
|
1996 | res = [] | |
2011 | lines = script.splitlines() |
|
1997 | lines = script.splitlines() | |
2012 | level = 0 |
|
1998 | level = 0 | |
2013 |
|
1999 | |||
2014 | for l in lines: |
|
2000 | for l in lines: | |
2015 | lstripped = l.lstrip() |
|
2001 | lstripped = l.lstrip() | |
2016 | stripped = l.strip() |
|
2002 | stripped = l.strip() | |
2017 | if not stripped: |
|
2003 | if not stripped: | |
2018 | continue |
|
2004 | continue | |
2019 | newlevel = len(l) - len(lstripped) |
|
2005 | newlevel = len(l) - len(lstripped) | |
2020 | if level > 0 and newlevel == 0 and \ |
|
2006 | if level > 0 and newlevel == 0 and \ | |
2021 | not self._is_secondary_block_start(stripped): |
|
2007 | not self._is_secondary_block_start(stripped): | |
2022 | # add empty line |
|
2008 | # add empty line | |
2023 | res.append('') |
|
2009 | res.append('') | |
2024 | res.append(l) |
|
2010 | res.append(l) | |
2025 | level = newlevel |
|
2011 | level = newlevel | |
2026 |
|
2012 | |||
2027 | return '\n'.join(res) + '\n' |
|
2013 | return '\n'.join(res) + '\n' | |
2028 |
|
2014 | |||
2029 | def runlines(self, lines, clean=False): |
|
2015 | def runlines(self, lines, clean=False): | |
2030 | """Run a string of one or more lines of source. |
|
2016 | """Run a string of one or more lines of source. | |
2031 |
|
2017 | |||
2032 | This method is capable of running a string containing multiple source |
|
2018 | This method is capable of running a string containing multiple source | |
2033 | lines, as if they had been entered at the IPython prompt. Since it |
|
2019 | lines, as if they had been entered at the IPython prompt. Since it | |
2034 | exposes IPython's processing machinery, the given strings can contain |
|
2020 | exposes IPython's processing machinery, the given strings can contain | |
2035 | magic calls (%magic), special shell access (!cmd), etc. |
|
2021 | magic calls (%magic), special shell access (!cmd), etc. | |
2036 | """ |
|
2022 | """ | |
2037 |
|
2023 | |||
2038 | if isinstance(lines, (list, tuple)): |
|
2024 | if isinstance(lines, (list, tuple)): | |
2039 | lines = '\n'.join(lines) |
|
2025 | lines = '\n'.join(lines) | |
2040 |
|
2026 | |||
2041 | if clean: |
|
2027 | if clean: | |
2042 | lines = self.cleanup_ipy_script(lines) |
|
2028 | lines = self.cleanup_ipy_script(lines) | |
2043 |
|
2029 | |||
2044 | # We must start with a clean buffer, in case this is run from an |
|
2030 | # We must start with a clean buffer, in case this is run from an | |
2045 | # interactive IPython session (via a magic, for example). |
|
2031 | # interactive IPython session (via a magic, for example). | |
2046 | self.resetbuffer() |
|
2032 | self.resetbuffer() | |
2047 | lines = lines.splitlines() |
|
2033 | lines = lines.splitlines() | |
2048 | more = 0 |
|
2034 | more = 0 | |
2049 |
|
2035 | |||
2050 | with nested(self.builtin_trap, self.display_trap): |
|
2036 | with nested(self.builtin_trap, self.display_trap): | |
2051 | for line in lines: |
|
2037 | for line in lines: | |
2052 | # skip blank lines so we don't mess up the prompt counter, but do |
|
2038 | # skip blank lines so we don't mess up the prompt counter, but do | |
2053 | # NOT skip even a blank line if we are in a code block (more is |
|
2039 | # NOT skip even a blank line if we are in a code block (more is | |
2054 | # true) |
|
2040 | # true) | |
2055 |
|
2041 | |||
2056 | if line or more: |
|
2042 | if line or more: | |
2057 | # push to raw history, so hist line numbers stay in sync |
|
2043 | # push to raw history, so hist line numbers stay in sync | |
2058 | self.input_hist_raw.append("# " + line + "\n") |
|
2044 | self.input_hist_raw.append("# " + line + "\n") | |
2059 | prefiltered = self.prefilter_manager.prefilter_lines(line,more) |
|
2045 | prefiltered = self.prefilter_manager.prefilter_lines(line,more) | |
2060 | more = self.push_line(prefiltered) |
|
2046 | more = self.push_line(prefiltered) | |
2061 | # IPython's runsource returns None if there was an error |
|
2047 | # IPython's runsource returns None if there was an error | |
2062 | # compiling the code. This allows us to stop processing right |
|
2048 | # compiling the code. This allows us to stop processing right | |
2063 | # away, so the user gets the error message at the right place. |
|
2049 | # away, so the user gets the error message at the right place. | |
2064 | if more is None: |
|
2050 | if more is None: | |
2065 | break |
|
2051 | break | |
2066 | else: |
|
2052 | else: | |
2067 | self.input_hist_raw.append("\n") |
|
2053 | self.input_hist_raw.append("\n") | |
2068 | # final newline in case the input didn't have it, so that the code |
|
2054 | # final newline in case the input didn't have it, so that the code | |
2069 | # actually does get executed |
|
2055 | # actually does get executed | |
2070 | if more: |
|
2056 | if more: | |
2071 | self.push_line('\n') |
|
2057 | self.push_line('\n') | |
2072 |
|
2058 | |||
2073 | def runsource(self, source, filename='<input>', symbol='single'): |
|
2059 | def runsource(self, source, filename='<input>', symbol='single'): | |
2074 | """Compile and run some source in the interpreter. |
|
2060 | """Compile and run some source in the interpreter. | |
2075 |
|
2061 | |||
2076 | Arguments are as for compile_command(). |
|
2062 | Arguments are as for compile_command(). | |
2077 |
|
2063 | |||
2078 | One several things can happen: |
|
2064 | One several things can happen: | |
2079 |
|
2065 | |||
2080 | 1) The input is incorrect; compile_command() raised an |
|
2066 | 1) The input is incorrect; compile_command() raised an | |
2081 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2067 | exception (SyntaxError or OverflowError). A syntax traceback | |
2082 | will be printed by calling the showsyntaxerror() method. |
|
2068 | will be printed by calling the showsyntaxerror() method. | |
2083 |
|
2069 | |||
2084 | 2) The input is incomplete, and more input is required; |
|
2070 | 2) The input is incomplete, and more input is required; | |
2085 | compile_command() returned None. Nothing happens. |
|
2071 | compile_command() returned None. Nothing happens. | |
2086 |
|
2072 | |||
2087 | 3) The input is complete; compile_command() returned a code |
|
2073 | 3) The input is complete; compile_command() returned a code | |
2088 | object. The code is executed by calling self.runcode() (which |
|
2074 | object. The code is executed by calling self.runcode() (which | |
2089 | also handles run-time exceptions, except for SystemExit). |
|
2075 | also handles run-time exceptions, except for SystemExit). | |
2090 |
|
2076 | |||
2091 | The return value is: |
|
2077 | The return value is: | |
2092 |
|
2078 | |||
2093 | - True in case 2 |
|
2079 | - True in case 2 | |
2094 |
|
2080 | |||
2095 | - False in the other cases, unless an exception is raised, where |
|
2081 | - False in the other cases, unless an exception is raised, where | |
2096 | None is returned instead. This can be used by external callers to |
|
2082 | None is returned instead. This can be used by external callers to | |
2097 | know whether to continue feeding input or not. |
|
2083 | know whether to continue feeding input or not. | |
2098 |
|
2084 | |||
2099 | The return value can be used to decide whether to use sys.ps1 or |
|
2085 | The return value can be used to decide whether to use sys.ps1 or | |
2100 | sys.ps2 to prompt the next line.""" |
|
2086 | sys.ps2 to prompt the next line.""" | |
2101 |
|
2087 | |||
2102 | # if the source code has leading blanks, add 'if 1:\n' to it |
|
2088 | # if the source code has leading blanks, add 'if 1:\n' to it | |
2103 | # this allows execution of indented pasted code. It is tempting |
|
2089 | # this allows execution of indented pasted code. It is tempting | |
2104 | # to add '\n' at the end of source to run commands like ' a=1' |
|
2090 | # to add '\n' at the end of source to run commands like ' a=1' | |
2105 | # directly, but this fails for more complicated scenarios |
|
2091 | # directly, but this fails for more complicated scenarios | |
2106 | source=source.encode(self.stdin_encoding) |
|
2092 | source=source.encode(self.stdin_encoding) | |
2107 | if source[:1] in [' ', '\t']: |
|
2093 | if source[:1] in [' ', '\t']: | |
2108 | source = 'if 1:\n%s' % source |
|
2094 | source = 'if 1:\n%s' % source | |
2109 |
|
2095 | |||
2110 | try: |
|
2096 | try: | |
2111 | code = self.compile(source,filename,symbol) |
|
2097 | code = self.compile(source,filename,symbol) | |
2112 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2098 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): | |
2113 | # Case 1 |
|
2099 | # Case 1 | |
2114 | self.showsyntaxerror(filename) |
|
2100 | self.showsyntaxerror(filename) | |
2115 | return None |
|
2101 | return None | |
2116 |
|
2102 | |||
2117 | if code is None: |
|
2103 | if code is None: | |
2118 | # Case 2 |
|
2104 | # Case 2 | |
2119 | return True |
|
2105 | return True | |
2120 |
|
2106 | |||
2121 | # Case 3 |
|
2107 | # Case 3 | |
2122 | # We store the code object so that threaded shells and |
|
2108 | # We store the code object so that threaded shells and | |
2123 | # custom exception handlers can access all this info if needed. |
|
2109 | # custom exception handlers can access all this info if needed. | |
2124 | # The source corresponding to this can be obtained from the |
|
2110 | # The source corresponding to this can be obtained from the | |
2125 | # buffer attribute as '\n'.join(self.buffer). |
|
2111 | # buffer attribute as '\n'.join(self.buffer). | |
2126 | self.code_to_run = code |
|
2112 | self.code_to_run = code | |
2127 | # now actually execute the code object |
|
2113 | # now actually execute the code object | |
2128 | if self.runcode(code) == 0: |
|
2114 | if self.runcode(code) == 0: | |
2129 | return False |
|
2115 | return False | |
2130 | else: |
|
2116 | else: | |
2131 | return None |
|
2117 | return None | |
2132 |
|
2118 | |||
2133 | def runcode(self,code_obj): |
|
2119 | def runcode(self,code_obj): | |
2134 | """Execute a code object. |
|
2120 | """Execute a code object. | |
2135 |
|
2121 | |||
2136 | When an exception occurs, self.showtraceback() is called to display a |
|
2122 | When an exception occurs, self.showtraceback() is called to display a | |
2137 | traceback. |
|
2123 | traceback. | |
2138 |
|
2124 | |||
2139 | Return value: a flag indicating whether the code to be run completed |
|
2125 | Return value: a flag indicating whether the code to be run completed | |
2140 | successfully: |
|
2126 | successfully: | |
2141 |
|
2127 | |||
2142 | - 0: successful execution. |
|
2128 | - 0: successful execution. | |
2143 | - 1: an error occurred. |
|
2129 | - 1: an error occurred. | |
2144 | """ |
|
2130 | """ | |
2145 |
|
2131 | |||
2146 | # Set our own excepthook in case the user code tries to call it |
|
2132 | # Set our own excepthook in case the user code tries to call it | |
2147 | # directly, so that the IPython crash handler doesn't get triggered |
|
2133 | # directly, so that the IPython crash handler doesn't get triggered | |
2148 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2134 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
2149 |
|
2135 | |||
2150 | # we save the original sys.excepthook in the instance, in case config |
|
2136 | # we save the original sys.excepthook in the instance, in case config | |
2151 | # code (such as magics) needs access to it. |
|
2137 | # code (such as magics) needs access to it. | |
2152 | self.sys_excepthook = old_excepthook |
|
2138 | self.sys_excepthook = old_excepthook | |
2153 | outflag = 1 # happens in more places, so it's easier as default |
|
2139 | outflag = 1 # happens in more places, so it's easier as default | |
2154 | try: |
|
2140 | try: | |
2155 | try: |
|
2141 | try: | |
2156 | self.hooks.pre_runcode_hook() |
|
2142 | self.hooks.pre_runcode_hook() | |
2157 | exec code_obj in self.user_global_ns, self.user_ns |
|
2143 | exec code_obj in self.user_global_ns, self.user_ns | |
2158 | finally: |
|
2144 | finally: | |
2159 | # Reset our crash handler in place |
|
2145 | # Reset our crash handler in place | |
2160 | sys.excepthook = old_excepthook |
|
2146 | sys.excepthook = old_excepthook | |
2161 | except SystemExit: |
|
2147 | except SystemExit: | |
2162 | self.resetbuffer() |
|
2148 | self.resetbuffer() | |
2163 | self.showtraceback() |
|
2149 | self.showtraceback() | |
2164 | warn("Type %exit or %quit to exit IPython " |
|
2150 | warn("Type %exit or %quit to exit IPython " | |
2165 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
2151 | "(%Exit or %Quit do so unconditionally).",level=1) | |
2166 | except self.custom_exceptions: |
|
2152 | except self.custom_exceptions: | |
2167 | etype,value,tb = sys.exc_info() |
|
2153 | etype,value,tb = sys.exc_info() | |
2168 | self.CustomTB(etype,value,tb) |
|
2154 | self.CustomTB(etype,value,tb) | |
2169 | except: |
|
2155 | except: | |
2170 | self.showtraceback() |
|
2156 | self.showtraceback() | |
2171 | else: |
|
2157 | else: | |
2172 | outflag = 0 |
|
2158 | outflag = 0 | |
2173 | if softspace(sys.stdout, 0): |
|
2159 | if softspace(sys.stdout, 0): | |
2174 |
|
2160 | |||
2175 | # Flush out code object which has been run (and source) |
|
2161 | # Flush out code object which has been run (and source) | |
2176 | self.code_to_run = None |
|
2162 | self.code_to_run = None | |
2177 | return outflag |
|
2163 | return outflag | |
2178 |
|
2164 | |||
2179 | def push_line(self, line): |
|
2165 | def push_line(self, line): | |
2180 | """Push a line to the interpreter. |
|
2166 | """Push a line to the interpreter. | |
2181 |
|
2167 | |||
2182 | The line should not have a trailing newline; it may have |
|
2168 | The line should not have a trailing newline; it may have | |
2183 | internal newlines. The line is appended to a buffer and the |
|
2169 | internal newlines. The line is appended to a buffer and the | |
2184 | interpreter's runsource() method is called with the |
|
2170 | interpreter's runsource() method is called with the | |
2185 | concatenated contents of the buffer as source. If this |
|
2171 | concatenated contents of the buffer as source. If this | |
2186 | indicates that the command was executed or invalid, the buffer |
|
2172 | indicates that the command was executed or invalid, the buffer | |
2187 | is reset; otherwise, the command is incomplete, and the buffer |
|
2173 | is reset; otherwise, the command is incomplete, and the buffer | |
2188 | is left as it was after the line was appended. The return |
|
2174 | is left as it was after the line was appended. The return | |
2189 | value is 1 if more input is required, 0 if the line was dealt |
|
2175 | value is 1 if more input is required, 0 if the line was dealt | |
2190 | with in some way (this is the same as runsource()). |
|
2176 | with in some way (this is the same as runsource()). | |
2191 | """ |
|
2177 | """ | |
2192 |
|
2178 | |||
2193 | # autoindent management should be done here, and not in the |
|
2179 | # autoindent management should be done here, and not in the | |
2194 | # interactive loop, since that one is only seen by keyboard input. We |
|
2180 | # interactive loop, since that one is only seen by keyboard input. We | |
2195 | # need this done correctly even for code run via runlines (which uses |
|
2181 | # need this done correctly even for code run via runlines (which uses | |
2196 | # push). |
|
2182 | # push). | |
2197 |
|
2183 | |||
2198 | #print 'push line: <%s>' % line # dbg |
|
2184 | #print 'push line: <%s>' % line # dbg | |
2199 | for subline in line.splitlines(): |
|
2185 | for subline in line.splitlines(): | |
2200 | self._autoindent_update(subline) |
|
2186 | self._autoindent_update(subline) | |
2201 | self.buffer.append(line) |
|
2187 | self.buffer.append(line) | |
2202 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
2188 | more = self.runsource('\n'.join(self.buffer), self.filename) | |
2203 | if not more: |
|
2189 | if not more: | |
2204 | self.resetbuffer() |
|
2190 | self.resetbuffer() | |
2205 | return more |
|
2191 | return more | |
2206 |
|
2192 | |||
2207 | def _autoindent_update(self,line): |
|
2193 | def _autoindent_update(self,line): | |
2208 | """Keep track of the indent level.""" |
|
2194 | """Keep track of the indent level.""" | |
2209 |
|
2195 | |||
2210 | #debugx('line') |
|
2196 | #debugx('line') | |
2211 | #debugx('self.indent_current_nsp') |
|
2197 | #debugx('self.indent_current_nsp') | |
2212 | if self.autoindent: |
|
2198 | if self.autoindent: | |
2213 | if line: |
|
2199 | if line: | |
2214 | inisp = num_ini_spaces(line) |
|
2200 | inisp = num_ini_spaces(line) | |
2215 | if inisp < self.indent_current_nsp: |
|
2201 | if inisp < self.indent_current_nsp: | |
2216 | self.indent_current_nsp = inisp |
|
2202 | self.indent_current_nsp = inisp | |
2217 |
|
2203 | |||
2218 | if line[-1] == ':': |
|
2204 | if line[-1] == ':': | |
2219 | self.indent_current_nsp += 4 |
|
2205 | self.indent_current_nsp += 4 | |
2220 | elif dedent_re.match(line): |
|
2206 | elif dedent_re.match(line): | |
2221 | self.indent_current_nsp -= 4 |
|
2207 | self.indent_current_nsp -= 4 | |
2222 | else: |
|
2208 | else: | |
2223 | self.indent_current_nsp = 0 |
|
2209 | self.indent_current_nsp = 0 | |
2224 |
|
2210 | |||
2225 | def resetbuffer(self): |
|
2211 | def resetbuffer(self): | |
2226 | """Reset the input buffer.""" |
|
2212 | """Reset the input buffer.""" | |
2227 | self.buffer[:] = [] |
|
2213 | self.buffer[:] = [] | |
2228 |
|
2214 | |||
2229 | def raw_input(self,prompt='',continue_prompt=False): |
|
2215 | def raw_input(self,prompt='',continue_prompt=False): | |
2230 | """Write a prompt and read a line. |
|
2216 | """Write a prompt and read a line. | |
2231 |
|
2217 | |||
2232 | The returned line does not include the trailing newline. |
|
2218 | The returned line does not include the trailing newline. | |
2233 | When the user enters the EOF key sequence, EOFError is raised. |
|
2219 | When the user enters the EOF key sequence, EOFError is raised. | |
2234 |
|
2220 | |||
2235 | Optional inputs: |
|
2221 | Optional inputs: | |
2236 |
|
2222 | |||
2237 | - prompt(''): a string to be printed to prompt the user. |
|
2223 | - prompt(''): a string to be printed to prompt the user. | |
2238 |
|
2224 | |||
2239 | - continue_prompt(False): whether this line is the first one or a |
|
2225 | - continue_prompt(False): whether this line is the first one or a | |
2240 | continuation in a sequence of inputs. |
|
2226 | continuation in a sequence of inputs. | |
2241 | """ |
|
2227 | """ | |
2242 | # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt)) |
|
2228 | # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt)) | |
2243 |
|
2229 | |||
2244 | # Code run by the user may have modified the readline completer state. |
|
2230 | # Code run by the user may have modified the readline completer state. | |
2245 | # We must ensure that our completer is back in place. |
|
2231 | # We must ensure that our completer is back in place. | |
2246 |
|
2232 | |||
2247 | if self.has_readline: |
|
2233 | if self.has_readline: | |
2248 | self.set_completer() |
|
2234 | self.set_completer() | |
2249 |
|
2235 | |||
2250 | try: |
|
2236 | try: | |
2251 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
2237 | line = raw_input_original(prompt).decode(self.stdin_encoding) | |
2252 | except ValueError: |
|
2238 | except ValueError: | |
2253 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
2239 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" | |
2254 | " or sys.stdout.close()!\nExiting IPython!") |
|
2240 | " or sys.stdout.close()!\nExiting IPython!") | |
2255 | self.ask_exit() |
|
2241 | self.ask_exit() | |
2256 | return "" |
|
2242 | return "" | |
2257 |
|
2243 | |||
2258 | # Try to be reasonably smart about not re-indenting pasted input more |
|
2244 | # Try to be reasonably smart about not re-indenting pasted input more | |
2259 | # than necessary. We do this by trimming out the auto-indent initial |
|
2245 | # than necessary. We do this by trimming out the auto-indent initial | |
2260 | # spaces, if the user's actual input started itself with whitespace. |
|
2246 | # spaces, if the user's actual input started itself with whitespace. | |
2261 | #debugx('self.buffer[-1]') |
|
2247 | #debugx('self.buffer[-1]') | |
2262 |
|
2248 | |||
2263 | if self.autoindent: |
|
2249 | if self.autoindent: | |
2264 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
2250 | if num_ini_spaces(line) > self.indent_current_nsp: | |
2265 | line = line[self.indent_current_nsp:] |
|
2251 | line = line[self.indent_current_nsp:] | |
2266 | self.indent_current_nsp = 0 |
|
2252 | self.indent_current_nsp = 0 | |
2267 |
|
2253 | |||
2268 | # store the unfiltered input before the user has any chance to modify |
|
2254 | # store the unfiltered input before the user has any chance to modify | |
2269 | # it. |
|
2255 | # it. | |
2270 | if line.strip(): |
|
2256 | if line.strip(): | |
2271 | if continue_prompt: |
|
2257 | if continue_prompt: | |
2272 | self.input_hist_raw[-1] += '%s\n' % line |
|
2258 | self.input_hist_raw[-1] += '%s\n' % line | |
2273 | if self.has_readline and self.readline_use: |
|
2259 | if self.has_readline and self.readline_use: | |
2274 | try: |
|
2260 | try: | |
2275 | histlen = self.readline.get_current_history_length() |
|
2261 | histlen = self.readline.get_current_history_length() | |
2276 | if histlen > 1: |
|
2262 | if histlen > 1: | |
2277 | newhist = self.input_hist_raw[-1].rstrip() |
|
2263 | newhist = self.input_hist_raw[-1].rstrip() | |
2278 | self.readline.remove_history_item(histlen-1) |
|
2264 | self.readline.remove_history_item(histlen-1) | |
2279 | self.readline.replace_history_item(histlen-2, |
|
2265 | self.readline.replace_history_item(histlen-2, | |
2280 | newhist.encode(self.stdin_encoding)) |
|
2266 | newhist.encode(self.stdin_encoding)) | |
2281 | except AttributeError: |
|
2267 | except AttributeError: | |
2282 | pass # re{move,place}_history_item are new in 2.4. |
|
2268 | pass # re{move,place}_history_item are new in 2.4. | |
2283 | else: |
|
2269 | else: | |
2284 | self.input_hist_raw.append('%s\n' % line) |
|
2270 | self.input_hist_raw.append('%s\n' % line) | |
2285 | # only entries starting at first column go to shadow history |
|
2271 | # only entries starting at first column go to shadow history | |
2286 | if line.lstrip() == line: |
|
2272 | if line.lstrip() == line: | |
2287 | self.shadowhist.add(line.strip()) |
|
2273 | self.shadowhist.add(line.strip()) | |
2288 | elif not continue_prompt: |
|
2274 | elif not continue_prompt: | |
2289 | self.input_hist_raw.append('\n') |
|
2275 | self.input_hist_raw.append('\n') | |
2290 | try: |
|
2276 | try: | |
2291 | lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt) |
|
2277 | lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt) | |
2292 | except: |
|
2278 | except: | |
2293 | # blanket except, in case a user-defined prefilter crashes, so it |
|
2279 | # blanket except, in case a user-defined prefilter crashes, so it | |
2294 | # can't take all of ipython with it. |
|
2280 | # can't take all of ipython with it. | |
2295 | self.showtraceback() |
|
2281 | self.showtraceback() | |
2296 | return '' |
|
2282 | return '' | |
2297 | else: |
|
2283 | else: | |
2298 | return lineout |
|
2284 | return lineout | |
2299 |
|
2285 | |||
2300 | # def init_exec_commands(self): |
|
|||
2301 | # for cmd in self.config.EXECUTE: |
|
|||
2302 | # print "execute:", cmd |
|
|||
2303 | # self.api.runlines(cmd) |
|
|||
2304 | # |
|
|||
2305 | # batchrun = False |
|
|||
2306 | # if self.config.has_key('EXECFILE'): |
|
|||
2307 | # for batchfile in [path(arg) for arg in self.config.EXECFILE |
|
|||
2308 | # if arg.lower().endswith('.ipy')]: |
|
|||
2309 | # if not batchfile.isfile(): |
|
|||
2310 | # print "No such batch file:", batchfile |
|
|||
2311 | # continue |
|
|||
2312 | # self.api.runlines(batchfile.text()) |
|
|||
2313 | # batchrun = True |
|
|||
2314 | # # without -i option, exit after running the batch file |
|
|||
2315 | # if batchrun and not self.interactive: |
|
|||
2316 | # self.ask_exit() |
|
|||
2317 |
|
||||
2318 | #------------------------------------------------------------------------- |
|
2286 | #------------------------------------------------------------------------- | |
2319 | # IPython extensions |
|
2287 | # IPython extensions | |
2320 | #------------------------------------------------------------------------- |
|
2288 | #------------------------------------------------------------------------- | |
2321 |
|
2289 | |||
2322 | def load_extension(self, module_str): |
|
2290 | def load_extension(self, module_str): | |
2323 | """Load an IPython extension. |
|
2291 | """Load an IPython extension. | |
2324 |
|
2292 | |||
2325 | An IPython extension is an importable Python module that has |
|
2293 | An IPython extension is an importable Python module that has | |
2326 | a function with the signature:: |
|
2294 | a function with the signature:: | |
2327 |
|
2295 | |||
2328 | def load_in_ipython(ipython): |
|
2296 | def load_in_ipython(ipython): | |
2329 | # Do things with ipython |
|
2297 | # Do things with ipython | |
2330 |
|
2298 | |||
2331 | This function is called after your extension is imported and the |
|
2299 | This function is called after your extension is imported and the | |
2332 | currently active :class:`InteractiveShell` instance is passed as |
|
2300 | currently active :class:`InteractiveShell` instance is passed as | |
2333 | the only argument. You can do anything you want with IPython at |
|
2301 | the only argument. You can do anything you want with IPython at | |
2334 | that point, including defining new magic and aliases, adding new |
|
2302 | that point, including defining new magic and aliases, adding new | |
2335 | components, etc. |
|
2303 | components, etc. | |
2336 |
|
2304 | |||
2337 | You can put your extension modules anywhere you want, as long as |
|
2305 | You can put your extension modules anywhere you want, as long as | |
2338 | they can be imported by Python's standard import mechanism. However, |
|
2306 | they can be imported by Python's standard import mechanism. However, | |
2339 | to make it easy to write extensions, you can also put your extensions |
|
2307 | to make it easy to write extensions, you can also put your extensions | |
2340 | in ``os.path.join(self.ipythondir, 'extensions')``. This directory |
|
2308 | in ``os.path.join(self.ipythondir, 'extensions')``. This directory | |
2341 | is added to ``sys.path`` automatically. |
|
2309 | is added to ``sys.path`` automatically. | |
2342 | """ |
|
2310 | """ | |
2343 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
2311 | from IPython.utils.syspathcontext import prepended_to_syspath | |
2344 |
|
2312 | |||
2345 | if module_str in sys.modules: |
|
2313 | if module_str in sys.modules: | |
2346 | return |
|
2314 | return | |
2347 |
|
2315 | |||
2348 | with prepended_to_syspath(self.ipython_extension_dir): |
|
2316 | with prepended_to_syspath(self.ipython_extension_dir): | |
2349 | __import__(module_str) |
|
2317 | __import__(module_str) | |
2350 | mod = sys.modules[module_str] |
|
2318 | mod = sys.modules[module_str] | |
2351 | self._call_load_in_ipython(mod) |
|
2319 | self._call_load_in_ipython(mod) | |
2352 |
|
2320 | |||
2353 | def reload_extension(self, module_str): |
|
2321 | def reload_extension(self, module_str): | |
2354 | """Reload an IPython extension by doing reload.""" |
|
2322 | """Reload an IPython extension by doing reload.""" | |
2355 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
2323 | from IPython.utils.syspathcontext import prepended_to_syspath | |
2356 |
|
2324 | |||
2357 | with prepended_to_syspath(self.ipython_extension_dir): |
|
2325 | with prepended_to_syspath(self.ipython_extension_dir): | |
2358 | if module_str in sys.modules: |
|
2326 | if module_str in sys.modules: | |
2359 | mod = sys.modules[module_str] |
|
2327 | mod = sys.modules[module_str] | |
2360 | reload(mod) |
|
2328 | reload(mod) | |
2361 | self._call_load_in_ipython(mod) |
|
2329 | self._call_load_in_ipython(mod) | |
2362 | else: |
|
2330 | else: | |
2363 | self.load_extension(self, module_str) |
|
2331 | self.load_extension(self, module_str) | |
2364 |
|
2332 | |||
2365 | def _call_load_in_ipython(self, mod): |
|
2333 | def _call_load_in_ipython(self, mod): | |
2366 | if hasattr(mod, 'load_in_ipython'): |
|
2334 | if hasattr(mod, 'load_in_ipython'): | |
2367 | mod.load_in_ipython(self) |
|
2335 | mod.load_in_ipython(self) | |
2368 |
|
2336 | |||
2369 | #------------------------------------------------------------------------- |
|
2337 | #------------------------------------------------------------------------- | |
2370 | # Things related to the prefilter |
|
2338 | # Things related to the prefilter | |
2371 | #------------------------------------------------------------------------- |
|
2339 | #------------------------------------------------------------------------- | |
2372 |
|
2340 | |||
2373 | def init_prefilter(self): |
|
2341 | def init_prefilter(self): | |
2374 | self.prefilter_manager = PrefilterManager(self, config=self.config) |
|
2342 | self.prefilter_manager = PrefilterManager(self, config=self.config) | |
2375 |
|
2343 | |||
2376 | #------------------------------------------------------------------------- |
|
2344 | #------------------------------------------------------------------------- | |
2377 | # Utilities |
|
2345 | # Utilities | |
2378 | #------------------------------------------------------------------------- |
|
2346 | #------------------------------------------------------------------------- | |
2379 |
|
2347 | |||
2380 | def getoutput(self, cmd): |
|
2348 | def getoutput(self, cmd): | |
2381 | return getoutput(self.var_expand(cmd,depth=2), |
|
2349 | return getoutput(self.var_expand(cmd,depth=2), | |
2382 | header=self.system_header, |
|
2350 | header=self.system_header, | |
2383 | verbose=self.system_verbose) |
|
2351 | verbose=self.system_verbose) | |
2384 |
|
2352 | |||
2385 | def getoutputerror(self, cmd): |
|
2353 | def getoutputerror(self, cmd): | |
2386 | return getoutputerror(self.var_expand(cmd,depth=2), |
|
2354 | return getoutputerror(self.var_expand(cmd,depth=2), | |
2387 | header=self.system_header, |
|
2355 | header=self.system_header, | |
2388 | verbose=self.system_verbose) |
|
2356 | verbose=self.system_verbose) | |
2389 |
|
2357 | |||
2390 | def var_expand(self,cmd,depth=0): |
|
2358 | def var_expand(self,cmd,depth=0): | |
2391 | """Expand python variables in a string. |
|
2359 | """Expand python variables in a string. | |
2392 |
|
2360 | |||
2393 | The depth argument indicates how many frames above the caller should |
|
2361 | The depth argument indicates how many frames above the caller should | |
2394 | be walked to look for the local namespace where to expand variables. |
|
2362 | be walked to look for the local namespace where to expand variables. | |
2395 |
|
2363 | |||
2396 | The global namespace for expansion is always the user's interactive |
|
2364 | The global namespace for expansion is always the user's interactive | |
2397 | namespace. |
|
2365 | namespace. | |
2398 | """ |
|
2366 | """ | |
2399 |
|
2367 | |||
2400 | return str(ItplNS(cmd, |
|
2368 | return str(ItplNS(cmd, | |
2401 | self.user_ns, # globals |
|
2369 | self.user_ns, # globals | |
2402 | # Skip our own frame in searching for locals: |
|
2370 | # Skip our own frame in searching for locals: | |
2403 | sys._getframe(depth+1).f_locals # locals |
|
2371 | sys._getframe(depth+1).f_locals # locals | |
2404 | )) |
|
2372 | )) | |
2405 |
|
2373 | |||
2406 | def mktempfile(self,data=None): |
|
2374 | def mktempfile(self,data=None): | |
2407 | """Make a new tempfile and return its filename. |
|
2375 | """Make a new tempfile and return its filename. | |
2408 |
|
2376 | |||
2409 | This makes a call to tempfile.mktemp, but it registers the created |
|
2377 | This makes a call to tempfile.mktemp, but it registers the created | |
2410 | filename internally so ipython cleans it up at exit time. |
|
2378 | filename internally so ipython cleans it up at exit time. | |
2411 |
|
2379 | |||
2412 | Optional inputs: |
|
2380 | Optional inputs: | |
2413 |
|
2381 | |||
2414 | - data(None): if data is given, it gets written out to the temp file |
|
2382 | - data(None): if data is given, it gets written out to the temp file | |
2415 | immediately, and the file is closed again.""" |
|
2383 | immediately, and the file is closed again.""" | |
2416 |
|
2384 | |||
2417 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2385 | filename = tempfile.mktemp('.py','ipython_edit_') | |
2418 | self.tempfiles.append(filename) |
|
2386 | self.tempfiles.append(filename) | |
2419 |
|
2387 | |||
2420 | if data: |
|
2388 | if data: | |
2421 | tmp_file = open(filename,'w') |
|
2389 | tmp_file = open(filename,'w') | |
2422 | tmp_file.write(data) |
|
2390 | tmp_file.write(data) | |
2423 | tmp_file.close() |
|
2391 | tmp_file.close() | |
2424 | return filename |
|
2392 | return filename | |
2425 |
|
2393 | |||
2426 | def write(self,data): |
|
2394 | def write(self,data): | |
2427 | """Write a string to the default output""" |
|
2395 | """Write a string to the default output""" | |
2428 | Term.cout.write(data) |
|
2396 | Term.cout.write(data) | |
2429 |
|
2397 | |||
2430 | def write_err(self,data): |
|
2398 | def write_err(self,data): | |
2431 | """Write a string to the default error output""" |
|
2399 | """Write a string to the default error output""" | |
2432 | Term.cerr.write(data) |
|
2400 | Term.cerr.write(data) | |
2433 |
|
2401 | |||
2434 | def ask_yes_no(self,prompt,default=True): |
|
2402 | def ask_yes_no(self,prompt,default=True): | |
2435 | if self.quiet: |
|
2403 | if self.quiet: | |
2436 | return True |
|
2404 | return True | |
2437 | return ask_yes_no(prompt,default) |
|
2405 | return ask_yes_no(prompt,default) | |
2438 |
|
2406 | |||
2439 | #------------------------------------------------------------------------- |
|
2407 | #------------------------------------------------------------------------- | |
2440 | # Things related to IPython exiting |
|
2408 | # Things related to IPython exiting | |
2441 | #------------------------------------------------------------------------- |
|
2409 | #------------------------------------------------------------------------- | |
2442 |
|
2410 | |||
2443 | def ask_exit(self): |
|
2411 | def ask_exit(self): | |
2444 | """ Call for exiting. Can be overiden and used as a callback. """ |
|
2412 | """ Call for exiting. Can be overiden and used as a callback. """ | |
2445 | self.exit_now = True |
|
2413 | self.exit_now = True | |
2446 |
|
2414 | |||
2447 | def exit(self): |
|
2415 | def exit(self): | |
2448 | """Handle interactive exit. |
|
2416 | """Handle interactive exit. | |
2449 |
|
2417 | |||
2450 | This method calls the ask_exit callback.""" |
|
2418 | This method calls the ask_exit callback.""" | |
2451 | if self.confirm_exit: |
|
2419 | if self.confirm_exit: | |
2452 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
2420 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): | |
2453 | self.ask_exit() |
|
2421 | self.ask_exit() | |
2454 | else: |
|
2422 | else: | |
2455 | self.ask_exit() |
|
2423 | self.ask_exit() | |
2456 |
|
2424 | |||
2457 | def atexit_operations(self): |
|
2425 | def atexit_operations(self): | |
2458 | """This will be executed at the time of exit. |
|
2426 | """This will be executed at the time of exit. | |
2459 |
|
2427 | |||
2460 | Saving of persistent data should be performed here. |
|
2428 | Saving of persistent data should be performed here. | |
2461 | """ |
|
2429 | """ | |
2462 | self.savehist() |
|
2430 | self.savehist() | |
2463 |
|
2431 | |||
2464 | # Cleanup all tempfiles left around |
|
2432 | # Cleanup all tempfiles left around | |
2465 | for tfile in self.tempfiles: |
|
2433 | for tfile in self.tempfiles: | |
2466 | try: |
|
2434 | try: | |
2467 | os.unlink(tfile) |
|
2435 | os.unlink(tfile) | |
2468 | except OSError: |
|
2436 | except OSError: | |
2469 | pass |
|
2437 | pass | |
2470 |
|
2438 | |||
2471 | # Clear all user namespaces to release all references cleanly. |
|
2439 | # Clear all user namespaces to release all references cleanly. | |
2472 | self.reset() |
|
2440 | self.reset() | |
2473 |
|
2441 | |||
2474 | # Run user hooks |
|
2442 | # Run user hooks | |
2475 | self.hooks.shutdown_hook() |
|
2443 | self.hooks.shutdown_hook() | |
2476 |
|
2444 | |||
2477 | def cleanup(self): |
|
2445 | def cleanup(self): | |
2478 | self.restore_sys_module_state() |
|
2446 | self.restore_sys_module_state() | |
2479 |
|
2447 | |||
2480 |
|
2448 |
General Comments 0
You need to be logged in to leave comments.
Login now