Show More
@@ -1,703 +1,703 b'' | |||||
1 | """A simple configuration system. |
|
1 | """A simple configuration system. | |
2 |
|
2 | |||
3 | Authors |
|
3 | Authors | |
4 | ------- |
|
4 | ------- | |
5 | * Brian Granger |
|
5 | * Brian Granger | |
6 | * Fernando Perez |
|
6 | * Fernando Perez | |
7 | * Min RK |
|
7 | * Min RK | |
8 | """ |
|
8 | """ | |
9 |
|
9 | |||
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 | # Copyright (C) 2008-2011 The IPython Development Team |
|
11 | # Copyright (C) 2008-2011 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__ as builtin_mod |
|
21 | import __builtin__ as builtin_mod | |
22 | import os |
|
22 | import os | |
23 | import re |
|
23 | import re | |
24 | import sys |
|
24 | import sys | |
25 |
|
25 | |||
26 | from IPython.external import argparse |
|
26 | from IPython.external import argparse | |
27 | from IPython.utils.path import filefind, get_ipython_dir |
|
27 | from IPython.utils.path import filefind, get_ipython_dir | |
28 | from IPython.utils import py3compat, text, warn |
|
28 | from IPython.utils import py3compat, text, warn | |
29 |
from IPython.utils.encoding import |
|
29 | from IPython.utils.encoding import DEFAULT_ENCODING | |
30 |
|
30 | |||
31 | #----------------------------------------------------------------------------- |
|
31 | #----------------------------------------------------------------------------- | |
32 | # Exceptions |
|
32 | # Exceptions | |
33 | #----------------------------------------------------------------------------- |
|
33 | #----------------------------------------------------------------------------- | |
34 |
|
34 | |||
35 |
|
35 | |||
36 | class ConfigError(Exception): |
|
36 | class ConfigError(Exception): | |
37 | pass |
|
37 | pass | |
38 |
|
38 | |||
39 | class ConfigLoaderError(ConfigError): |
|
39 | class ConfigLoaderError(ConfigError): | |
40 | pass |
|
40 | pass | |
41 |
|
41 | |||
42 | class ConfigFileNotFound(ConfigError): |
|
42 | class ConfigFileNotFound(ConfigError): | |
43 | pass |
|
43 | pass | |
44 |
|
44 | |||
45 | class ArgumentError(ConfigLoaderError): |
|
45 | class ArgumentError(ConfigLoaderError): | |
46 | pass |
|
46 | pass | |
47 |
|
47 | |||
48 | #----------------------------------------------------------------------------- |
|
48 | #----------------------------------------------------------------------------- | |
49 | # Argparse fix |
|
49 | # Argparse fix | |
50 | #----------------------------------------------------------------------------- |
|
50 | #----------------------------------------------------------------------------- | |
51 |
|
51 | |||
52 | # Unfortunately argparse by default prints help messages to stderr instead of |
|
52 | # Unfortunately argparse by default prints help messages to stderr instead of | |
53 | # stdout. This makes it annoying to capture long help screens at the command |
|
53 | # stdout. This makes it annoying to capture long help screens at the command | |
54 | # line, since one must know how to pipe stderr, which many users don't know how |
|
54 | # line, since one must know how to pipe stderr, which many users don't know how | |
55 | # to do. So we override the print_help method with one that defaults to |
|
55 | # to do. So we override the print_help method with one that defaults to | |
56 | # stdout and use our class instead. |
|
56 | # stdout and use our class instead. | |
57 |
|
57 | |||
58 | class ArgumentParser(argparse.ArgumentParser): |
|
58 | class ArgumentParser(argparse.ArgumentParser): | |
59 | """Simple argparse subclass that prints help to stdout by default.""" |
|
59 | """Simple argparse subclass that prints help to stdout by default.""" | |
60 |
|
60 | |||
61 | def print_help(self, file=None): |
|
61 | def print_help(self, file=None): | |
62 | if file is None: |
|
62 | if file is None: | |
63 | file = sys.stdout |
|
63 | file = sys.stdout | |
64 | return super(ArgumentParser, self).print_help(file) |
|
64 | return super(ArgumentParser, self).print_help(file) | |
65 |
|
65 | |||
66 | print_help.__doc__ = argparse.ArgumentParser.print_help.__doc__ |
|
66 | print_help.__doc__ = argparse.ArgumentParser.print_help.__doc__ | |
67 |
|
67 | |||
68 | #----------------------------------------------------------------------------- |
|
68 | #----------------------------------------------------------------------------- | |
69 | # Config class for holding config information |
|
69 | # Config class for holding config information | |
70 | #----------------------------------------------------------------------------- |
|
70 | #----------------------------------------------------------------------------- | |
71 |
|
71 | |||
72 |
|
72 | |||
73 | class Config(dict): |
|
73 | class Config(dict): | |
74 | """An attribute based dict that can do smart merges.""" |
|
74 | """An attribute based dict that can do smart merges.""" | |
75 |
|
75 | |||
76 | def __init__(self, *args, **kwds): |
|
76 | def __init__(self, *args, **kwds): | |
77 | dict.__init__(self, *args, **kwds) |
|
77 | dict.__init__(self, *args, **kwds) | |
78 | # This sets self.__dict__ = self, but it has to be done this way |
|
78 | # This sets self.__dict__ = self, but it has to be done this way | |
79 | # because we are also overriding __setattr__. |
|
79 | # because we are also overriding __setattr__. | |
80 | dict.__setattr__(self, '__dict__', self) |
|
80 | dict.__setattr__(self, '__dict__', self) | |
81 |
|
81 | |||
82 | def _merge(self, other): |
|
82 | def _merge(self, other): | |
83 | to_update = {} |
|
83 | to_update = {} | |
84 | for k, v in other.iteritems(): |
|
84 | for k, v in other.iteritems(): | |
85 | if not self.has_key(k): |
|
85 | if not self.has_key(k): | |
86 | to_update[k] = v |
|
86 | to_update[k] = v | |
87 | else: # I have this key |
|
87 | else: # I have this key | |
88 | if isinstance(v, Config): |
|
88 | if isinstance(v, Config): | |
89 | # Recursively merge common sub Configs |
|
89 | # Recursively merge common sub Configs | |
90 | self[k]._merge(v) |
|
90 | self[k]._merge(v) | |
91 | else: |
|
91 | else: | |
92 | # Plain updates for non-Configs |
|
92 | # Plain updates for non-Configs | |
93 | to_update[k] = v |
|
93 | to_update[k] = v | |
94 |
|
94 | |||
95 | self.update(to_update) |
|
95 | self.update(to_update) | |
96 |
|
96 | |||
97 | def _is_section_key(self, key): |
|
97 | def _is_section_key(self, key): | |
98 | if key[0].upper()==key[0] and not key.startswith('_'): |
|
98 | if key[0].upper()==key[0] and not key.startswith('_'): | |
99 | return True |
|
99 | return True | |
100 | else: |
|
100 | else: | |
101 | return False |
|
101 | return False | |
102 |
|
102 | |||
103 | def __contains__(self, key): |
|
103 | def __contains__(self, key): | |
104 | if self._is_section_key(key): |
|
104 | if self._is_section_key(key): | |
105 | return True |
|
105 | return True | |
106 | else: |
|
106 | else: | |
107 | return super(Config, self).__contains__(key) |
|
107 | return super(Config, self).__contains__(key) | |
108 | # .has_key is deprecated for dictionaries. |
|
108 | # .has_key is deprecated for dictionaries. | |
109 | has_key = __contains__ |
|
109 | has_key = __contains__ | |
110 |
|
110 | |||
111 | def _has_section(self, key): |
|
111 | def _has_section(self, key): | |
112 | if self._is_section_key(key): |
|
112 | if self._is_section_key(key): | |
113 | if super(Config, self).__contains__(key): |
|
113 | if super(Config, self).__contains__(key): | |
114 | return True |
|
114 | return True | |
115 | return False |
|
115 | return False | |
116 |
|
116 | |||
117 | def copy(self): |
|
117 | def copy(self): | |
118 | return type(self)(dict.copy(self)) |
|
118 | return type(self)(dict.copy(self)) | |
119 |
|
119 | |||
120 | def __copy__(self): |
|
120 | def __copy__(self): | |
121 | return self.copy() |
|
121 | return self.copy() | |
122 |
|
122 | |||
123 | def __deepcopy__(self, memo): |
|
123 | def __deepcopy__(self, memo): | |
124 | import copy |
|
124 | import copy | |
125 | return type(self)(copy.deepcopy(self.items())) |
|
125 | return type(self)(copy.deepcopy(self.items())) | |
126 |
|
126 | |||
127 | def __getitem__(self, key): |
|
127 | def __getitem__(self, key): | |
128 | # We cannot use directly self._is_section_key, because it triggers |
|
128 | # We cannot use directly self._is_section_key, because it triggers | |
129 | # infinite recursion on top of PyPy. Instead, we manually fish the |
|
129 | # infinite recursion on top of PyPy. Instead, we manually fish the | |
130 | # bound method. |
|
130 | # bound method. | |
131 | is_section_key = self.__class__._is_section_key.__get__(self) |
|
131 | is_section_key = self.__class__._is_section_key.__get__(self) | |
132 |
|
132 | |||
133 | # Because we use this for an exec namespace, we need to delegate |
|
133 | # Because we use this for an exec namespace, we need to delegate | |
134 | # the lookup of names in __builtin__ to itself. This means |
|
134 | # the lookup of names in __builtin__ to itself. This means | |
135 | # that you can't have section or attribute names that are |
|
135 | # that you can't have section or attribute names that are | |
136 | # builtins. |
|
136 | # builtins. | |
137 | try: |
|
137 | try: | |
138 | return getattr(builtin_mod, key) |
|
138 | return getattr(builtin_mod, key) | |
139 | except AttributeError: |
|
139 | except AttributeError: | |
140 | pass |
|
140 | pass | |
141 | if is_section_key(key): |
|
141 | if is_section_key(key): | |
142 | try: |
|
142 | try: | |
143 | return dict.__getitem__(self, key) |
|
143 | return dict.__getitem__(self, key) | |
144 | except KeyError: |
|
144 | except KeyError: | |
145 | c = Config() |
|
145 | c = Config() | |
146 | dict.__setitem__(self, key, c) |
|
146 | dict.__setitem__(self, key, c) | |
147 | return c |
|
147 | return c | |
148 | else: |
|
148 | else: | |
149 | return dict.__getitem__(self, key) |
|
149 | return dict.__getitem__(self, key) | |
150 |
|
150 | |||
151 | def __setitem__(self, key, value): |
|
151 | def __setitem__(self, key, value): | |
152 | # Don't allow names in __builtin__ to be modified. |
|
152 | # Don't allow names in __builtin__ to be modified. | |
153 | if hasattr(builtin_mod, key): |
|
153 | if hasattr(builtin_mod, key): | |
154 | raise ConfigError('Config variable names cannot have the same name ' |
|
154 | raise ConfigError('Config variable names cannot have the same name ' | |
155 | 'as a Python builtin: %s' % key) |
|
155 | 'as a Python builtin: %s' % key) | |
156 | if self._is_section_key(key): |
|
156 | if self._is_section_key(key): | |
157 | if not isinstance(value, Config): |
|
157 | if not isinstance(value, Config): | |
158 | raise ValueError('values whose keys begin with an uppercase ' |
|
158 | raise ValueError('values whose keys begin with an uppercase ' | |
159 | 'char must be Config instances: %r, %r' % (key, value)) |
|
159 | 'char must be Config instances: %r, %r' % (key, value)) | |
160 | else: |
|
160 | else: | |
161 | dict.__setitem__(self, key, value) |
|
161 | dict.__setitem__(self, key, value) | |
162 |
|
162 | |||
163 | def __getattr__(self, key): |
|
163 | def __getattr__(self, key): | |
164 | try: |
|
164 | try: | |
165 | return self.__getitem__(key) |
|
165 | return self.__getitem__(key) | |
166 | except KeyError, e: |
|
166 | except KeyError, e: | |
167 | raise AttributeError(e) |
|
167 | raise AttributeError(e) | |
168 |
|
168 | |||
169 | def __setattr__(self, key, value): |
|
169 | def __setattr__(self, key, value): | |
170 | try: |
|
170 | try: | |
171 | self.__setitem__(key, value) |
|
171 | self.__setitem__(key, value) | |
172 | except KeyError, e: |
|
172 | except KeyError, e: | |
173 | raise AttributeError(e) |
|
173 | raise AttributeError(e) | |
174 |
|
174 | |||
175 | def __delattr__(self, key): |
|
175 | def __delattr__(self, key): | |
176 | try: |
|
176 | try: | |
177 | dict.__delitem__(self, key) |
|
177 | dict.__delitem__(self, key) | |
178 | except KeyError, e: |
|
178 | except KeyError, e: | |
179 | raise AttributeError(e) |
|
179 | raise AttributeError(e) | |
180 |
|
180 | |||
181 |
|
181 | |||
182 | #----------------------------------------------------------------------------- |
|
182 | #----------------------------------------------------------------------------- | |
183 | # Config loading classes |
|
183 | # Config loading classes | |
184 | #----------------------------------------------------------------------------- |
|
184 | #----------------------------------------------------------------------------- | |
185 |
|
185 | |||
186 |
|
186 | |||
187 | class ConfigLoader(object): |
|
187 | class ConfigLoader(object): | |
188 | """A object for loading configurations from just about anywhere. |
|
188 | """A object for loading configurations from just about anywhere. | |
189 |
|
189 | |||
190 | The resulting configuration is packaged as a :class:`Struct`. |
|
190 | The resulting configuration is packaged as a :class:`Struct`. | |
191 |
|
191 | |||
192 | Notes |
|
192 | Notes | |
193 | ----- |
|
193 | ----- | |
194 | A :class:`ConfigLoader` does one thing: load a config from a source |
|
194 | A :class:`ConfigLoader` does one thing: load a config from a source | |
195 | (file, command line arguments) and returns the data as a :class:`Struct`. |
|
195 | (file, command line arguments) and returns the data as a :class:`Struct`. | |
196 | There are lots of things that :class:`ConfigLoader` does not do. It does |
|
196 | There are lots of things that :class:`ConfigLoader` does not do. It does | |
197 | not implement complex logic for finding config files. It does not handle |
|
197 | not implement complex logic for finding config files. It does not handle | |
198 | default values or merge multiple configs. These things need to be |
|
198 | default values or merge multiple configs. These things need to be | |
199 | handled elsewhere. |
|
199 | handled elsewhere. | |
200 | """ |
|
200 | """ | |
201 |
|
201 | |||
202 | def __init__(self): |
|
202 | def __init__(self): | |
203 | """A base class for config loaders. |
|
203 | """A base class for config loaders. | |
204 |
|
204 | |||
205 | Examples |
|
205 | Examples | |
206 | -------- |
|
206 | -------- | |
207 |
|
207 | |||
208 | >>> cl = ConfigLoader() |
|
208 | >>> cl = ConfigLoader() | |
209 | >>> config = cl.load_config() |
|
209 | >>> config = cl.load_config() | |
210 | >>> config |
|
210 | >>> config | |
211 | {} |
|
211 | {} | |
212 | """ |
|
212 | """ | |
213 | self.clear() |
|
213 | self.clear() | |
214 |
|
214 | |||
215 | def clear(self): |
|
215 | def clear(self): | |
216 | self.config = Config() |
|
216 | self.config = Config() | |
217 |
|
217 | |||
218 | def load_config(self): |
|
218 | def load_config(self): | |
219 | """Load a config from somewhere, return a :class:`Config` instance. |
|
219 | """Load a config from somewhere, return a :class:`Config` instance. | |
220 |
|
220 | |||
221 | Usually, this will cause self.config to be set and then returned. |
|
221 | Usually, this will cause self.config to be set and then returned. | |
222 | However, in most cases, :meth:`ConfigLoader.clear` should be called |
|
222 | However, in most cases, :meth:`ConfigLoader.clear` should be called | |
223 | to erase any previous state. |
|
223 | to erase any previous state. | |
224 | """ |
|
224 | """ | |
225 | self.clear() |
|
225 | self.clear() | |
226 | return self.config |
|
226 | return self.config | |
227 |
|
227 | |||
228 |
|
228 | |||
229 | class FileConfigLoader(ConfigLoader): |
|
229 | class FileConfigLoader(ConfigLoader): | |
230 | """A base class for file based configurations. |
|
230 | """A base class for file based configurations. | |
231 |
|
231 | |||
232 | As we add more file based config loaders, the common logic should go |
|
232 | As we add more file based config loaders, the common logic should go | |
233 | here. |
|
233 | here. | |
234 | """ |
|
234 | """ | |
235 | pass |
|
235 | pass | |
236 |
|
236 | |||
237 |
|
237 | |||
238 | class PyFileConfigLoader(FileConfigLoader): |
|
238 | class PyFileConfigLoader(FileConfigLoader): | |
239 | """A config loader for pure python files. |
|
239 | """A config loader for pure python files. | |
240 |
|
240 | |||
241 | This calls execfile on a plain python file and looks for attributes |
|
241 | This calls execfile on a plain python file and looks for attributes | |
242 | that are all caps. These attribute are added to the config Struct. |
|
242 | that are all caps. These attribute are added to the config Struct. | |
243 | """ |
|
243 | """ | |
244 |
|
244 | |||
245 | def __init__(self, filename, path=None): |
|
245 | def __init__(self, filename, path=None): | |
246 | """Build a config loader for a filename and path. |
|
246 | """Build a config loader for a filename and path. | |
247 |
|
247 | |||
248 | Parameters |
|
248 | Parameters | |
249 | ---------- |
|
249 | ---------- | |
250 | filename : str |
|
250 | filename : str | |
251 | The file name of the config file. |
|
251 | The file name of the config file. | |
252 | path : str, list, tuple |
|
252 | path : str, list, tuple | |
253 | The path to search for the config file on, or a sequence of |
|
253 | The path to search for the config file on, or a sequence of | |
254 | paths to try in order. |
|
254 | paths to try in order. | |
255 | """ |
|
255 | """ | |
256 | super(PyFileConfigLoader, self).__init__() |
|
256 | super(PyFileConfigLoader, self).__init__() | |
257 | self.filename = filename |
|
257 | self.filename = filename | |
258 | self.path = path |
|
258 | self.path = path | |
259 | self.full_filename = '' |
|
259 | self.full_filename = '' | |
260 | self.data = None |
|
260 | self.data = None | |
261 |
|
261 | |||
262 | def load_config(self): |
|
262 | def load_config(self): | |
263 | """Load the config from a file and return it as a Struct.""" |
|
263 | """Load the config from a file and return it as a Struct.""" | |
264 | self.clear() |
|
264 | self.clear() | |
265 | try: |
|
265 | try: | |
266 | self._find_file() |
|
266 | self._find_file() | |
267 | except IOError as e: |
|
267 | except IOError as e: | |
268 | raise ConfigFileNotFound(str(e)) |
|
268 | raise ConfigFileNotFound(str(e)) | |
269 | self._read_file_as_dict() |
|
269 | self._read_file_as_dict() | |
270 | self._convert_to_config() |
|
270 | self._convert_to_config() | |
271 | return self.config |
|
271 | return self.config | |
272 |
|
272 | |||
273 | def _find_file(self): |
|
273 | def _find_file(self): | |
274 | """Try to find the file by searching the paths.""" |
|
274 | """Try to find the file by searching the paths.""" | |
275 | self.full_filename = filefind(self.filename, self.path) |
|
275 | self.full_filename = filefind(self.filename, self.path) | |
276 |
|
276 | |||
277 | def _read_file_as_dict(self): |
|
277 | def _read_file_as_dict(self): | |
278 | """Load the config file into self.config, with recursive loading.""" |
|
278 | """Load the config file into self.config, with recursive loading.""" | |
279 | # This closure is made available in the namespace that is used |
|
279 | # This closure is made available in the namespace that is used | |
280 | # to exec the config file. It allows users to call |
|
280 | # to exec the config file. It allows users to call | |
281 | # load_subconfig('myconfig.py') to load config files recursively. |
|
281 | # load_subconfig('myconfig.py') to load config files recursively. | |
282 | # It needs to be a closure because it has references to self.path |
|
282 | # It needs to be a closure because it has references to self.path | |
283 | # and self.config. The sub-config is loaded with the same path |
|
283 | # and self.config. The sub-config is loaded with the same path | |
284 | # as the parent, but it uses an empty config which is then merged |
|
284 | # as the parent, but it uses an empty config which is then merged | |
285 | # with the parents. |
|
285 | # with the parents. | |
286 |
|
286 | |||
287 | # If a profile is specified, the config file will be loaded |
|
287 | # If a profile is specified, the config file will be loaded | |
288 | # from that profile |
|
288 | # from that profile | |
289 |
|
289 | |||
290 | def load_subconfig(fname, profile=None): |
|
290 | def load_subconfig(fname, profile=None): | |
291 | # import here to prevent circular imports |
|
291 | # import here to prevent circular imports | |
292 | from IPython.core.profiledir import ProfileDir, ProfileDirError |
|
292 | from IPython.core.profiledir import ProfileDir, ProfileDirError | |
293 | if profile is not None: |
|
293 | if profile is not None: | |
294 | try: |
|
294 | try: | |
295 | profile_dir = ProfileDir.find_profile_dir_by_name( |
|
295 | profile_dir = ProfileDir.find_profile_dir_by_name( | |
296 | get_ipython_dir(), |
|
296 | get_ipython_dir(), | |
297 | profile, |
|
297 | profile, | |
298 | ) |
|
298 | ) | |
299 | except ProfileDirError: |
|
299 | except ProfileDirError: | |
300 | return |
|
300 | return | |
301 | path = profile_dir.location |
|
301 | path = profile_dir.location | |
302 | else: |
|
302 | else: | |
303 | path = self.path |
|
303 | path = self.path | |
304 | loader = PyFileConfigLoader(fname, path) |
|
304 | loader = PyFileConfigLoader(fname, path) | |
305 | try: |
|
305 | try: | |
306 | sub_config = loader.load_config() |
|
306 | sub_config = loader.load_config() | |
307 | except ConfigFileNotFound: |
|
307 | except ConfigFileNotFound: | |
308 | # Pass silently if the sub config is not there. This happens |
|
308 | # Pass silently if the sub config is not there. This happens | |
309 | # when a user s using a profile, but not the default config. |
|
309 | # when a user s using a profile, but not the default config. | |
310 | pass |
|
310 | pass | |
311 | else: |
|
311 | else: | |
312 | self.config._merge(sub_config) |
|
312 | self.config._merge(sub_config) | |
313 |
|
313 | |||
314 | # Again, this needs to be a closure and should be used in config |
|
314 | # Again, this needs to be a closure and should be used in config | |
315 | # files to get the config being loaded. |
|
315 | # files to get the config being loaded. | |
316 | def get_config(): |
|
316 | def get_config(): | |
317 | return self.config |
|
317 | return self.config | |
318 |
|
318 | |||
319 | namespace = dict(load_subconfig=load_subconfig, get_config=get_config) |
|
319 | namespace = dict(load_subconfig=load_subconfig, get_config=get_config) | |
320 | fs_encoding = sys.getfilesystemencoding() or 'ascii' |
|
320 | fs_encoding = sys.getfilesystemencoding() or 'ascii' | |
321 | conf_filename = self.full_filename.encode(fs_encoding) |
|
321 | conf_filename = self.full_filename.encode(fs_encoding) | |
322 | py3compat.execfile(conf_filename, namespace) |
|
322 | py3compat.execfile(conf_filename, namespace) | |
323 |
|
323 | |||
324 | def _convert_to_config(self): |
|
324 | def _convert_to_config(self): | |
325 | if self.data is None: |
|
325 | if self.data is None: | |
326 | ConfigLoaderError('self.data does not exist') |
|
326 | ConfigLoaderError('self.data does not exist') | |
327 |
|
327 | |||
328 |
|
328 | |||
329 | class CommandLineConfigLoader(ConfigLoader): |
|
329 | class CommandLineConfigLoader(ConfigLoader): | |
330 | """A config loader for command line arguments. |
|
330 | """A config loader for command line arguments. | |
331 |
|
331 | |||
332 | As we add more command line based loaders, the common logic should go |
|
332 | As we add more command line based loaders, the common logic should go | |
333 | here. |
|
333 | here. | |
334 | """ |
|
334 | """ | |
335 |
|
335 | |||
336 | def _exec_config_str(self, lhs, rhs): |
|
336 | def _exec_config_str(self, lhs, rhs): | |
337 | """execute self.config.<lhs>=<rhs> |
|
337 | """execute self.config.<lhs>=<rhs> | |
338 |
|
338 | |||
339 | * expands ~ with expanduser |
|
339 | * expands ~ with expanduser | |
340 | * tries to assign with raw exec, otherwise assigns with just the string, |
|
340 | * tries to assign with raw exec, otherwise assigns with just the string, | |
341 | allowing `--C.a=foobar` and `--C.a="foobar"` to be equivalent. *Not* |
|
341 | allowing `--C.a=foobar` and `--C.a="foobar"` to be equivalent. *Not* | |
342 | equivalent are `--C.a=4` and `--C.a='4'`. |
|
342 | equivalent are `--C.a=4` and `--C.a='4'`. | |
343 | """ |
|
343 | """ | |
344 | rhs = os.path.expanduser(rhs) |
|
344 | rhs = os.path.expanduser(rhs) | |
345 | exec_str = 'self.config.' + lhs + '=' + rhs |
|
345 | exec_str = 'self.config.' + lhs + '=' + rhs | |
346 | try: |
|
346 | try: | |
347 | # Try to see if regular Python syntax will work. This |
|
347 | # Try to see if regular Python syntax will work. This | |
348 | # won't handle strings as the quote marks are removed |
|
348 | # won't handle strings as the quote marks are removed | |
349 | # by the system shell. |
|
349 | # by the system shell. | |
350 | exec exec_str in locals(), globals() |
|
350 | exec exec_str in locals(), globals() | |
351 | except (NameError, SyntaxError): |
|
351 | except (NameError, SyntaxError): | |
352 | # This case happens if the rhs is a string but without |
|
352 | # This case happens if the rhs is a string but without | |
353 | # the quote marks. Use repr, to get quote marks, and |
|
353 | # the quote marks. Use repr, to get quote marks, and | |
354 | # 'u' prefix and see if |
|
354 | # 'u' prefix and see if | |
355 | # it succeeds. If it still fails, we let it raise. |
|
355 | # it succeeds. If it still fails, we let it raise. | |
356 | exec_str = u'self.config.' + lhs + '= rhs' |
|
356 | exec_str = u'self.config.' + lhs + '= rhs' | |
357 | exec exec_str in locals(), globals() |
|
357 | exec exec_str in locals(), globals() | |
358 |
|
358 | |||
359 | def _load_flag(self, cfg): |
|
359 | def _load_flag(self, cfg): | |
360 | """update self.config from a flag, which can be a dict or Config""" |
|
360 | """update self.config from a flag, which can be a dict or Config""" | |
361 | if isinstance(cfg, (dict, Config)): |
|
361 | if isinstance(cfg, (dict, Config)): | |
362 | # don't clobber whole config sections, update |
|
362 | # don't clobber whole config sections, update | |
363 | # each section from config: |
|
363 | # each section from config: | |
364 | for sec,c in cfg.iteritems(): |
|
364 | for sec,c in cfg.iteritems(): | |
365 | self.config[sec].update(c) |
|
365 | self.config[sec].update(c) | |
366 | else: |
|
366 | else: | |
367 | raise TypeError("Invalid flag: %r" % cfg) |
|
367 | raise TypeError("Invalid flag: %r" % cfg) | |
368 |
|
368 | |||
369 | # raw --identifier=value pattern |
|
369 | # raw --identifier=value pattern | |
370 | # but *also* accept '-' as wordsep, for aliases |
|
370 | # but *also* accept '-' as wordsep, for aliases | |
371 | # accepts: --foo=a |
|
371 | # accepts: --foo=a | |
372 | # --Class.trait=value |
|
372 | # --Class.trait=value | |
373 | # --alias-name=value |
|
373 | # --alias-name=value | |
374 | # rejects: -foo=value |
|
374 | # rejects: -foo=value | |
375 | # --foo |
|
375 | # --foo | |
376 | # --Class.trait |
|
376 | # --Class.trait | |
377 | kv_pattern = re.compile(r'\-\-[A-Za-z][\w\-]*(\.[\w\-]+)*\=.*') |
|
377 | kv_pattern = re.compile(r'\-\-[A-Za-z][\w\-]*(\.[\w\-]+)*\=.*') | |
378 |
|
378 | |||
379 | # just flags, no assignments, with two *or one* leading '-' |
|
379 | # just flags, no assignments, with two *or one* leading '-' | |
380 | # accepts: --foo |
|
380 | # accepts: --foo | |
381 | # -foo-bar-again |
|
381 | # -foo-bar-again | |
382 | # rejects: --anything=anything |
|
382 | # rejects: --anything=anything | |
383 | # --two.word |
|
383 | # --two.word | |
384 |
|
384 | |||
385 | flag_pattern = re.compile(r'\-\-?\w+[\-\w]*$') |
|
385 | flag_pattern = re.compile(r'\-\-?\w+[\-\w]*$') | |
386 |
|
386 | |||
387 | class KeyValueConfigLoader(CommandLineConfigLoader): |
|
387 | class KeyValueConfigLoader(CommandLineConfigLoader): | |
388 | """A config loader that loads key value pairs from the command line. |
|
388 | """A config loader that loads key value pairs from the command line. | |
389 |
|
389 | |||
390 | This allows command line options to be gives in the following form:: |
|
390 | This allows command line options to be gives in the following form:: | |
391 |
|
391 | |||
392 | ipython --profile="foo" --InteractiveShell.autocall=False |
|
392 | ipython --profile="foo" --InteractiveShell.autocall=False | |
393 | """ |
|
393 | """ | |
394 |
|
394 | |||
395 | def __init__(self, argv=None, aliases=None, flags=None): |
|
395 | def __init__(self, argv=None, aliases=None, flags=None): | |
396 | """Create a key value pair config loader. |
|
396 | """Create a key value pair config loader. | |
397 |
|
397 | |||
398 | Parameters |
|
398 | Parameters | |
399 | ---------- |
|
399 | ---------- | |
400 | argv : list |
|
400 | argv : list | |
401 | A list that has the form of sys.argv[1:] which has unicode |
|
401 | A list that has the form of sys.argv[1:] which has unicode | |
402 | elements of the form u"key=value". If this is None (default), |
|
402 | elements of the form u"key=value". If this is None (default), | |
403 | then sys.argv[1:] will be used. |
|
403 | then sys.argv[1:] will be used. | |
404 | aliases : dict |
|
404 | aliases : dict | |
405 | A dict of aliases for configurable traits. |
|
405 | A dict of aliases for configurable traits. | |
406 | Keys are the short aliases, Values are the resolved trait. |
|
406 | Keys are the short aliases, Values are the resolved trait. | |
407 | Of the form: `{'alias' : 'Configurable.trait'}` |
|
407 | Of the form: `{'alias' : 'Configurable.trait'}` | |
408 | flags : dict |
|
408 | flags : dict | |
409 | A dict of flags, keyed by str name. Vaues can be Config objects, |
|
409 | A dict of flags, keyed by str name. Vaues can be Config objects, | |
410 | dicts, or "key=value" strings. If Config or dict, when the flag |
|
410 | dicts, or "key=value" strings. If Config or dict, when the flag | |
411 | is triggered, The flag is loaded as `self.config.update(m)`. |
|
411 | is triggered, The flag is loaded as `self.config.update(m)`. | |
412 |
|
412 | |||
413 | Returns |
|
413 | Returns | |
414 | ------- |
|
414 | ------- | |
415 | config : Config |
|
415 | config : Config | |
416 | The resulting Config object. |
|
416 | The resulting Config object. | |
417 |
|
417 | |||
418 | Examples |
|
418 | Examples | |
419 | -------- |
|
419 | -------- | |
420 |
|
420 | |||
421 | >>> from IPython.config.loader import KeyValueConfigLoader |
|
421 | >>> from IPython.config.loader import KeyValueConfigLoader | |
422 | >>> cl = KeyValueConfigLoader() |
|
422 | >>> cl = KeyValueConfigLoader() | |
423 | >>> cl.load_config(["--A.name='brian'","--B.number=0"]) |
|
423 | >>> cl.load_config(["--A.name='brian'","--B.number=0"]) | |
424 | {'A': {'name': 'brian'}, 'B': {'number': 0}} |
|
424 | {'A': {'name': 'brian'}, 'B': {'number': 0}} | |
425 | """ |
|
425 | """ | |
426 | self.clear() |
|
426 | self.clear() | |
427 | if argv is None: |
|
427 | if argv is None: | |
428 | argv = sys.argv[1:] |
|
428 | argv = sys.argv[1:] | |
429 | self.argv = argv |
|
429 | self.argv = argv | |
430 | self.aliases = aliases or {} |
|
430 | self.aliases = aliases or {} | |
431 | self.flags = flags or {} |
|
431 | self.flags = flags or {} | |
432 |
|
432 | |||
433 |
|
433 | |||
434 | def clear(self): |
|
434 | def clear(self): | |
435 | super(KeyValueConfigLoader, self).clear() |
|
435 | super(KeyValueConfigLoader, self).clear() | |
436 | self.extra_args = [] |
|
436 | self.extra_args = [] | |
437 |
|
437 | |||
438 |
|
438 | |||
439 | def _decode_argv(self, argv, enc=None): |
|
439 | def _decode_argv(self, argv, enc=None): | |
440 | """decode argv if bytes, using stin.encoding, falling back on default enc""" |
|
440 | """decode argv if bytes, using stin.encoding, falling back on default enc""" | |
441 | uargv = [] |
|
441 | uargv = [] | |
442 | if enc is None: |
|
442 | if enc is None: | |
443 | enc = getdefaultencoding() |
|
443 | enc = DEFAULT_ENCODING | |
444 | for arg in argv: |
|
444 | for arg in argv: | |
445 | if not isinstance(arg, unicode): |
|
445 | if not isinstance(arg, unicode): | |
446 | # only decode if not already decoded |
|
446 | # only decode if not already decoded | |
447 | arg = arg.decode(enc) |
|
447 | arg = arg.decode(enc) | |
448 | uargv.append(arg) |
|
448 | uargv.append(arg) | |
449 | return uargv |
|
449 | return uargv | |
450 |
|
450 | |||
451 |
|
451 | |||
452 | def load_config(self, argv=None, aliases=None, flags=None): |
|
452 | def load_config(self, argv=None, aliases=None, flags=None): | |
453 | """Parse the configuration and generate the Config object. |
|
453 | """Parse the configuration and generate the Config object. | |
454 |
|
454 | |||
455 | After loading, any arguments that are not key-value or |
|
455 | After loading, any arguments that are not key-value or | |
456 | flags will be stored in self.extra_args - a list of |
|
456 | flags will be stored in self.extra_args - a list of | |
457 | unparsed command-line arguments. This is used for |
|
457 | unparsed command-line arguments. This is used for | |
458 | arguments such as input files or subcommands. |
|
458 | arguments such as input files or subcommands. | |
459 |
|
459 | |||
460 | Parameters |
|
460 | Parameters | |
461 | ---------- |
|
461 | ---------- | |
462 | argv : list, optional |
|
462 | argv : list, optional | |
463 | A list that has the form of sys.argv[1:] which has unicode |
|
463 | A list that has the form of sys.argv[1:] which has unicode | |
464 | elements of the form u"key=value". If this is None (default), |
|
464 | elements of the form u"key=value". If this is None (default), | |
465 | then self.argv will be used. |
|
465 | then self.argv will be used. | |
466 | aliases : dict |
|
466 | aliases : dict | |
467 | A dict of aliases for configurable traits. |
|
467 | A dict of aliases for configurable traits. | |
468 | Keys are the short aliases, Values are the resolved trait. |
|
468 | Keys are the short aliases, Values are the resolved trait. | |
469 | Of the form: `{'alias' : 'Configurable.trait'}` |
|
469 | Of the form: `{'alias' : 'Configurable.trait'}` | |
470 | flags : dict |
|
470 | flags : dict | |
471 | A dict of flags, keyed by str name. Values can be Config objects |
|
471 | A dict of flags, keyed by str name. Values can be Config objects | |
472 | or dicts. When the flag is triggered, The config is loaded as |
|
472 | or dicts. When the flag is triggered, The config is loaded as | |
473 | `self.config.update(cfg)`. |
|
473 | `self.config.update(cfg)`. | |
474 | """ |
|
474 | """ | |
475 | from IPython.config.configurable import Configurable |
|
475 | from IPython.config.configurable import Configurable | |
476 |
|
476 | |||
477 | self.clear() |
|
477 | self.clear() | |
478 | if argv is None: |
|
478 | if argv is None: | |
479 | argv = self.argv |
|
479 | argv = self.argv | |
480 | if aliases is None: |
|
480 | if aliases is None: | |
481 | aliases = self.aliases |
|
481 | aliases = self.aliases | |
482 | if flags is None: |
|
482 | if flags is None: | |
483 | flags = self.flags |
|
483 | flags = self.flags | |
484 |
|
484 | |||
485 | # ensure argv is a list of unicode strings: |
|
485 | # ensure argv is a list of unicode strings: | |
486 | uargv = self._decode_argv(argv) |
|
486 | uargv = self._decode_argv(argv) | |
487 | for idx,raw in enumerate(uargv): |
|
487 | for idx,raw in enumerate(uargv): | |
488 | # strip leading '-' |
|
488 | # strip leading '-' | |
489 | item = raw.lstrip('-') |
|
489 | item = raw.lstrip('-') | |
490 |
|
490 | |||
491 | if raw == '--': |
|
491 | if raw == '--': | |
492 | # don't parse arguments after '--' |
|
492 | # don't parse arguments after '--' | |
493 | # this is useful for relaying arguments to scripts, e.g. |
|
493 | # this is useful for relaying arguments to scripts, e.g. | |
494 | # ipython -i foo.py --pylab=qt -- args after '--' go-to-foo.py |
|
494 | # ipython -i foo.py --pylab=qt -- args after '--' go-to-foo.py | |
495 | self.extra_args.extend(uargv[idx+1:]) |
|
495 | self.extra_args.extend(uargv[idx+1:]) | |
496 | break |
|
496 | break | |
497 |
|
497 | |||
498 | if kv_pattern.match(raw): |
|
498 | if kv_pattern.match(raw): | |
499 | lhs,rhs = item.split('=',1) |
|
499 | lhs,rhs = item.split('=',1) | |
500 | # Substitute longnames for aliases. |
|
500 | # Substitute longnames for aliases. | |
501 | if lhs in aliases: |
|
501 | if lhs in aliases: | |
502 | lhs = aliases[lhs] |
|
502 | lhs = aliases[lhs] | |
503 | if '.' not in lhs: |
|
503 | if '.' not in lhs: | |
504 | # probably a mistyped alias, but not technically illegal |
|
504 | # probably a mistyped alias, but not technically illegal | |
505 | warn.warn("Unrecognized alias: '%s', it will probably have no effect."%lhs) |
|
505 | warn.warn("Unrecognized alias: '%s', it will probably have no effect."%lhs) | |
506 | try: |
|
506 | try: | |
507 | self._exec_config_str(lhs, rhs) |
|
507 | self._exec_config_str(lhs, rhs) | |
508 | except Exception: |
|
508 | except Exception: | |
509 | raise ArgumentError("Invalid argument: '%s'" % raw) |
|
509 | raise ArgumentError("Invalid argument: '%s'" % raw) | |
510 |
|
510 | |||
511 | elif flag_pattern.match(raw): |
|
511 | elif flag_pattern.match(raw): | |
512 | if item in flags: |
|
512 | if item in flags: | |
513 | cfg,help = flags[item] |
|
513 | cfg,help = flags[item] | |
514 | self._load_flag(cfg) |
|
514 | self._load_flag(cfg) | |
515 | else: |
|
515 | else: | |
516 | raise ArgumentError("Unrecognized flag: '%s'"%raw) |
|
516 | raise ArgumentError("Unrecognized flag: '%s'"%raw) | |
517 | elif raw.startswith('-'): |
|
517 | elif raw.startswith('-'): | |
518 | kv = '--'+item |
|
518 | kv = '--'+item | |
519 | if kv_pattern.match(kv): |
|
519 | if kv_pattern.match(kv): | |
520 | raise ArgumentError("Invalid argument: '%s', did you mean '%s'?"%(raw, kv)) |
|
520 | raise ArgumentError("Invalid argument: '%s', did you mean '%s'?"%(raw, kv)) | |
521 | else: |
|
521 | else: | |
522 | raise ArgumentError("Invalid argument: '%s'"%raw) |
|
522 | raise ArgumentError("Invalid argument: '%s'"%raw) | |
523 | else: |
|
523 | else: | |
524 | # keep all args that aren't valid in a list, |
|
524 | # keep all args that aren't valid in a list, | |
525 | # in case our parent knows what to do with them. |
|
525 | # in case our parent knows what to do with them. | |
526 | self.extra_args.append(item) |
|
526 | self.extra_args.append(item) | |
527 | return self.config |
|
527 | return self.config | |
528 |
|
528 | |||
529 | class ArgParseConfigLoader(CommandLineConfigLoader): |
|
529 | class ArgParseConfigLoader(CommandLineConfigLoader): | |
530 | """A loader that uses the argparse module to load from the command line.""" |
|
530 | """A loader that uses the argparse module to load from the command line.""" | |
531 |
|
531 | |||
532 | def __init__(self, argv=None, aliases=None, flags=None, *parser_args, **parser_kw): |
|
532 | def __init__(self, argv=None, aliases=None, flags=None, *parser_args, **parser_kw): | |
533 | """Create a config loader for use with argparse. |
|
533 | """Create a config loader for use with argparse. | |
534 |
|
534 | |||
535 | Parameters |
|
535 | Parameters | |
536 | ---------- |
|
536 | ---------- | |
537 |
|
537 | |||
538 | argv : optional, list |
|
538 | argv : optional, list | |
539 | If given, used to read command-line arguments from, otherwise |
|
539 | If given, used to read command-line arguments from, otherwise | |
540 | sys.argv[1:] is used. |
|
540 | sys.argv[1:] is used. | |
541 |
|
541 | |||
542 | parser_args : tuple |
|
542 | parser_args : tuple | |
543 | A tuple of positional arguments that will be passed to the |
|
543 | A tuple of positional arguments that will be passed to the | |
544 | constructor of :class:`argparse.ArgumentParser`. |
|
544 | constructor of :class:`argparse.ArgumentParser`. | |
545 |
|
545 | |||
546 | parser_kw : dict |
|
546 | parser_kw : dict | |
547 | A tuple of keyword arguments that will be passed to the |
|
547 | A tuple of keyword arguments that will be passed to the | |
548 | constructor of :class:`argparse.ArgumentParser`. |
|
548 | constructor of :class:`argparse.ArgumentParser`. | |
549 |
|
549 | |||
550 | Returns |
|
550 | Returns | |
551 | ------- |
|
551 | ------- | |
552 | config : Config |
|
552 | config : Config | |
553 | The resulting Config object. |
|
553 | The resulting Config object. | |
554 | """ |
|
554 | """ | |
555 | super(CommandLineConfigLoader, self).__init__() |
|
555 | super(CommandLineConfigLoader, self).__init__() | |
556 | self.clear() |
|
556 | self.clear() | |
557 | if argv is None: |
|
557 | if argv is None: | |
558 | argv = sys.argv[1:] |
|
558 | argv = sys.argv[1:] | |
559 | self.argv = argv |
|
559 | self.argv = argv | |
560 | self.aliases = aliases or {} |
|
560 | self.aliases = aliases or {} | |
561 | self.flags = flags or {} |
|
561 | self.flags = flags or {} | |
562 |
|
562 | |||
563 | self.parser_args = parser_args |
|
563 | self.parser_args = parser_args | |
564 | self.version = parser_kw.pop("version", None) |
|
564 | self.version = parser_kw.pop("version", None) | |
565 | kwargs = dict(argument_default=argparse.SUPPRESS) |
|
565 | kwargs = dict(argument_default=argparse.SUPPRESS) | |
566 | kwargs.update(parser_kw) |
|
566 | kwargs.update(parser_kw) | |
567 | self.parser_kw = kwargs |
|
567 | self.parser_kw = kwargs | |
568 |
|
568 | |||
569 | def load_config(self, argv=None, aliases=None, flags=None): |
|
569 | def load_config(self, argv=None, aliases=None, flags=None): | |
570 | """Parse command line arguments and return as a Config object. |
|
570 | """Parse command line arguments and return as a Config object. | |
571 |
|
571 | |||
572 | Parameters |
|
572 | Parameters | |
573 | ---------- |
|
573 | ---------- | |
574 |
|
574 | |||
575 | args : optional, list |
|
575 | args : optional, list | |
576 | If given, a list with the structure of sys.argv[1:] to parse |
|
576 | If given, a list with the structure of sys.argv[1:] to parse | |
577 | arguments from. If not given, the instance's self.argv attribute |
|
577 | arguments from. If not given, the instance's self.argv attribute | |
578 | (given at construction time) is used.""" |
|
578 | (given at construction time) is used.""" | |
579 | self.clear() |
|
579 | self.clear() | |
580 | if argv is None: |
|
580 | if argv is None: | |
581 | argv = self.argv |
|
581 | argv = self.argv | |
582 | if aliases is None: |
|
582 | if aliases is None: | |
583 | aliases = self.aliases |
|
583 | aliases = self.aliases | |
584 | if flags is None: |
|
584 | if flags is None: | |
585 | flags = self.flags |
|
585 | flags = self.flags | |
586 | self._create_parser(aliases, flags) |
|
586 | self._create_parser(aliases, flags) | |
587 | self._parse_args(argv) |
|
587 | self._parse_args(argv) | |
588 | self._convert_to_config() |
|
588 | self._convert_to_config() | |
589 | return self.config |
|
589 | return self.config | |
590 |
|
590 | |||
591 | def get_extra_args(self): |
|
591 | def get_extra_args(self): | |
592 | if hasattr(self, 'extra_args'): |
|
592 | if hasattr(self, 'extra_args'): | |
593 | return self.extra_args |
|
593 | return self.extra_args | |
594 | else: |
|
594 | else: | |
595 | return [] |
|
595 | return [] | |
596 |
|
596 | |||
597 | def _create_parser(self, aliases=None, flags=None): |
|
597 | def _create_parser(self, aliases=None, flags=None): | |
598 | self.parser = ArgumentParser(*self.parser_args, **self.parser_kw) |
|
598 | self.parser = ArgumentParser(*self.parser_args, **self.parser_kw) | |
599 | self._add_arguments(aliases, flags) |
|
599 | self._add_arguments(aliases, flags) | |
600 |
|
600 | |||
601 | def _add_arguments(self, aliases=None, flags=None): |
|
601 | def _add_arguments(self, aliases=None, flags=None): | |
602 | raise NotImplementedError("subclasses must implement _add_arguments") |
|
602 | raise NotImplementedError("subclasses must implement _add_arguments") | |
603 |
|
603 | |||
604 | def _parse_args(self, args): |
|
604 | def _parse_args(self, args): | |
605 | """self.parser->self.parsed_data""" |
|
605 | """self.parser->self.parsed_data""" | |
606 | # decode sys.argv to support unicode command-line options |
|
606 | # decode sys.argv to support unicode command-line options | |
607 | enc = getdefaultencoding() |
|
607 | enc = DEFAULT_ENCODING | |
608 | uargs = [py3compat.cast_unicode(a, enc) for a in args] |
|
608 | uargs = [py3compat.cast_unicode(a, enc) for a in args] | |
609 | self.parsed_data, self.extra_args = self.parser.parse_known_args(uargs) |
|
609 | self.parsed_data, self.extra_args = self.parser.parse_known_args(uargs) | |
610 |
|
610 | |||
611 | def _convert_to_config(self): |
|
611 | def _convert_to_config(self): | |
612 | """self.parsed_data->self.config""" |
|
612 | """self.parsed_data->self.config""" | |
613 | for k, v in vars(self.parsed_data).iteritems(): |
|
613 | for k, v in vars(self.parsed_data).iteritems(): | |
614 | exec "self.config.%s = v"%k in locals(), globals() |
|
614 | exec "self.config.%s = v"%k in locals(), globals() | |
615 |
|
615 | |||
616 | class KVArgParseConfigLoader(ArgParseConfigLoader): |
|
616 | class KVArgParseConfigLoader(ArgParseConfigLoader): | |
617 | """A config loader that loads aliases and flags with argparse, |
|
617 | """A config loader that loads aliases and flags with argparse, | |
618 | but will use KVLoader for the rest. This allows better parsing |
|
618 | but will use KVLoader for the rest. This allows better parsing | |
619 | of common args, such as `ipython -c 'print 5'`, but still gets |
|
619 | of common args, such as `ipython -c 'print 5'`, but still gets | |
620 | arbitrary config with `ipython --InteractiveShell.use_readline=False`""" |
|
620 | arbitrary config with `ipython --InteractiveShell.use_readline=False`""" | |
621 |
|
621 | |||
622 | def _convert_to_config(self): |
|
622 | def _convert_to_config(self): | |
623 | """self.parsed_data->self.config""" |
|
623 | """self.parsed_data->self.config""" | |
624 | for k, v in vars(self.parsed_data).iteritems(): |
|
624 | for k, v in vars(self.parsed_data).iteritems(): | |
625 | self._exec_config_str(k, v) |
|
625 | self._exec_config_str(k, v) | |
626 |
|
626 | |||
627 | def _add_arguments(self, aliases=None, flags=None): |
|
627 | def _add_arguments(self, aliases=None, flags=None): | |
628 | self.alias_flags = {} |
|
628 | self.alias_flags = {} | |
629 | # print aliases, flags |
|
629 | # print aliases, flags | |
630 | if aliases is None: |
|
630 | if aliases is None: | |
631 | aliases = self.aliases |
|
631 | aliases = self.aliases | |
632 | if flags is None: |
|
632 | if flags is None: | |
633 | flags = self.flags |
|
633 | flags = self.flags | |
634 | paa = self.parser.add_argument |
|
634 | paa = self.parser.add_argument | |
635 | for key,value in aliases.iteritems(): |
|
635 | for key,value in aliases.iteritems(): | |
636 | if key in flags: |
|
636 | if key in flags: | |
637 | # flags |
|
637 | # flags | |
638 | nargs = '?' |
|
638 | nargs = '?' | |
639 | else: |
|
639 | else: | |
640 | nargs = None |
|
640 | nargs = None | |
641 | if len(key) is 1: |
|
641 | if len(key) is 1: | |
642 | paa('-'+key, '--'+key, type=unicode, dest=value, nargs=nargs) |
|
642 | paa('-'+key, '--'+key, type=unicode, dest=value, nargs=nargs) | |
643 | else: |
|
643 | else: | |
644 | paa('--'+key, type=unicode, dest=value, nargs=nargs) |
|
644 | paa('--'+key, type=unicode, dest=value, nargs=nargs) | |
645 | for key, (value, help) in flags.iteritems(): |
|
645 | for key, (value, help) in flags.iteritems(): | |
646 | if key in self.aliases: |
|
646 | if key in self.aliases: | |
647 | # |
|
647 | # | |
648 | self.alias_flags[self.aliases[key]] = value |
|
648 | self.alias_flags[self.aliases[key]] = value | |
649 | continue |
|
649 | continue | |
650 | if len(key) is 1: |
|
650 | if len(key) is 1: | |
651 | paa('-'+key, '--'+key, action='append_const', dest='_flags', const=value) |
|
651 | paa('-'+key, '--'+key, action='append_const', dest='_flags', const=value) | |
652 | else: |
|
652 | else: | |
653 | paa('--'+key, action='append_const', dest='_flags', const=value) |
|
653 | paa('--'+key, action='append_const', dest='_flags', const=value) | |
654 |
|
654 | |||
655 | def _convert_to_config(self): |
|
655 | def _convert_to_config(self): | |
656 | """self.parsed_data->self.config, parse unrecognized extra args via KVLoader.""" |
|
656 | """self.parsed_data->self.config, parse unrecognized extra args via KVLoader.""" | |
657 | # remove subconfigs list from namespace before transforming the Namespace |
|
657 | # remove subconfigs list from namespace before transforming the Namespace | |
658 | if '_flags' in self.parsed_data: |
|
658 | if '_flags' in self.parsed_data: | |
659 | subcs = self.parsed_data._flags |
|
659 | subcs = self.parsed_data._flags | |
660 | del self.parsed_data._flags |
|
660 | del self.parsed_data._flags | |
661 | else: |
|
661 | else: | |
662 | subcs = [] |
|
662 | subcs = [] | |
663 |
|
663 | |||
664 | for k, v in vars(self.parsed_data).iteritems(): |
|
664 | for k, v in vars(self.parsed_data).iteritems(): | |
665 | if v is None: |
|
665 | if v is None: | |
666 | # it was a flag that shares the name of an alias |
|
666 | # it was a flag that shares the name of an alias | |
667 | subcs.append(self.alias_flags[k]) |
|
667 | subcs.append(self.alias_flags[k]) | |
668 | else: |
|
668 | else: | |
669 | # eval the KV assignment |
|
669 | # eval the KV assignment | |
670 | self._exec_config_str(k, v) |
|
670 | self._exec_config_str(k, v) | |
671 |
|
671 | |||
672 | for subc in subcs: |
|
672 | for subc in subcs: | |
673 | self._load_flag(subc) |
|
673 | self._load_flag(subc) | |
674 |
|
674 | |||
675 | if self.extra_args: |
|
675 | if self.extra_args: | |
676 | sub_parser = KeyValueConfigLoader() |
|
676 | sub_parser = KeyValueConfigLoader() | |
677 | sub_parser.load_config(self.extra_args) |
|
677 | sub_parser.load_config(self.extra_args) | |
678 | self.config._merge(sub_parser.config) |
|
678 | self.config._merge(sub_parser.config) | |
679 | self.extra_args = sub_parser.extra_args |
|
679 | self.extra_args = sub_parser.extra_args | |
680 |
|
680 | |||
681 |
|
681 | |||
682 | def load_pyconfig_files(config_files, path): |
|
682 | def load_pyconfig_files(config_files, path): | |
683 | """Load multiple Python config files, merging each of them in turn. |
|
683 | """Load multiple Python config files, merging each of them in turn. | |
684 |
|
684 | |||
685 | Parameters |
|
685 | Parameters | |
686 | ========== |
|
686 | ========== | |
687 | config_files : list of str |
|
687 | config_files : list of str | |
688 | List of config files names to load and merge into the config. |
|
688 | List of config files names to load and merge into the config. | |
689 | path : unicode |
|
689 | path : unicode | |
690 | The full path to the location of the config files. |
|
690 | The full path to the location of the config files. | |
691 | """ |
|
691 | """ | |
692 | config = Config() |
|
692 | config = Config() | |
693 | for cf in config_files: |
|
693 | for cf in config_files: | |
694 | loader = PyFileConfigLoader(cf, path=path) |
|
694 | loader = PyFileConfigLoader(cf, path=path) | |
695 | try: |
|
695 | try: | |
696 | next_config = loader.load_config() |
|
696 | next_config = loader.load_config() | |
697 | except ConfigFileNotFound: |
|
697 | except ConfigFileNotFound: | |
698 | pass |
|
698 | pass | |
699 | except: |
|
699 | except: | |
700 | raise |
|
700 | raise | |
701 | else: |
|
701 | else: | |
702 | config._merge(next_config) |
|
702 | config._merge(next_config) | |
703 | return config |
|
703 | return config |
@@ -1,60 +1,60 b'' | |||||
1 | """Support for interactive macros in IPython""" |
|
1 | """Support for interactive macros in IPython""" | |
2 |
|
2 | |||
3 | #***************************************************************************** |
|
3 | #***************************************************************************** | |
4 | # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu> |
|
4 | # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu> | |
5 | # |
|
5 | # | |
6 | # Distributed under the terms of the BSD License. The full license is in |
|
6 | # Distributed under the terms of the BSD License. The full license is in | |
7 | # the file COPYING, distributed as part of this software. |
|
7 | # the file COPYING, distributed as part of this software. | |
8 | #***************************************************************************** |
|
8 | #***************************************************************************** | |
9 |
|
9 | |||
10 | import re |
|
10 | import re | |
11 | import sys |
|
11 | import sys | |
12 |
|
12 | |||
13 | from IPython.utils import py3compat |
|
13 | from IPython.utils import py3compat | |
14 |
from IPython.utils.encoding import |
|
14 | from IPython.utils.encoding import DEFAULT_ENCODING | |
15 |
|
15 | |||
16 | coding_declaration = re.compile(r"#\s*coding[:=]\s*([-\w.]+)") |
|
16 | coding_declaration = re.compile(r"#\s*coding[:=]\s*([-\w.]+)") | |
17 |
|
17 | |||
18 | class Macro(object): |
|
18 | class Macro(object): | |
19 | """Simple class to store the value of macros as strings. |
|
19 | """Simple class to store the value of macros as strings. | |
20 |
|
20 | |||
21 | Macro is just a callable that executes a string of IPython |
|
21 | Macro is just a callable that executes a string of IPython | |
22 | input when called. |
|
22 | input when called. | |
23 |
|
23 | |||
24 | Args to macro are available in _margv list if you need them. |
|
24 | Args to macro are available in _margv list if you need them. | |
25 | """ |
|
25 | """ | |
26 |
|
26 | |||
27 | def __init__(self,code): |
|
27 | def __init__(self,code): | |
28 | """store the macro value, as a single string which can be executed""" |
|
28 | """store the macro value, as a single string which can be executed""" | |
29 | lines = [] |
|
29 | lines = [] | |
30 | enc = None |
|
30 | enc = None | |
31 | for line in code.splitlines(): |
|
31 | for line in code.splitlines(): | |
32 | coding_match = coding_declaration.match(line) |
|
32 | coding_match = coding_declaration.match(line) | |
33 | if coding_match: |
|
33 | if coding_match: | |
34 | enc = coding_match.group(1) |
|
34 | enc = coding_match.group(1) | |
35 | else: |
|
35 | else: | |
36 | lines.append(line) |
|
36 | lines.append(line) | |
37 | code = "\n".join(lines) |
|
37 | code = "\n".join(lines) | |
38 | if isinstance(code, bytes): |
|
38 | if isinstance(code, bytes): | |
39 |
code = code.decode(enc or |
|
39 | code = code.decode(enc or DEFAULT_ENCODING) | |
40 | self.value = code + '\n' |
|
40 | self.value = code + '\n' | |
41 |
|
41 | |||
42 | def __str__(self): |
|
42 | def __str__(self): | |
43 | return py3compat.unicode_to_str(self.value) |
|
43 | return py3compat.unicode_to_str(self.value) | |
44 |
|
44 | |||
45 | def __unicode__(self): |
|
45 | def __unicode__(self): | |
46 | return self.value |
|
46 | return self.value | |
47 |
|
47 | |||
48 | def __repr__(self): |
|
48 | def __repr__(self): | |
49 | return 'IPython.macro.Macro(%s)' % repr(self.value) |
|
49 | return 'IPython.macro.Macro(%s)' % repr(self.value) | |
50 |
|
50 | |||
51 | def __getstate__(self): |
|
51 | def __getstate__(self): | |
52 | """ needed for safe pickling via %store """ |
|
52 | """ needed for safe pickling via %store """ | |
53 | return {'value': self.value} |
|
53 | return {'value': self.value} | |
54 |
|
54 | |||
55 | def __add__(self, other): |
|
55 | def __add__(self, other): | |
56 | if isinstance(other, Macro): |
|
56 | if isinstance(other, Macro): | |
57 | return Macro(self.value + other.value) |
|
57 | return Macro(self.value + other.value) | |
58 | elif isinstance(other, basestring): |
|
58 | elif isinstance(other, basestring): | |
59 | return Macro(self.value + other) |
|
59 | return Macro(self.value + other) | |
60 | raise TypeError |
|
60 | raise TypeError |
@@ -1,3799 +1,3799 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """Magic functions for InteractiveShell. |
|
2 | """Magic functions for InteractiveShell. | |
3 | """ |
|
3 | """ | |
4 |
|
4 | |||
5 | #----------------------------------------------------------------------------- |
|
5 | #----------------------------------------------------------------------------- | |
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
7 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> |
|
7 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> | |
8 | # Copyright (C) 2008-2011 The IPython Development Team |
|
8 | # Copyright (C) 2008-2011 The IPython Development Team | |
9 |
|
9 | |||
10 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | # Distributed under the terms of the BSD License. The full license is in | |
11 | # the file COPYING, distributed as part of this software. |
|
11 | # the file COPYING, distributed as part of this software. | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 | # Imports |
|
15 | # Imports | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | import __builtin__ as builtin_mod |
|
18 | import __builtin__ as builtin_mod | |
19 | import __future__ |
|
19 | import __future__ | |
20 | import bdb |
|
20 | import bdb | |
21 | import inspect |
|
21 | import inspect | |
22 | import imp |
|
22 | import imp | |
23 | import io |
|
23 | import io | |
24 | import os |
|
24 | import os | |
25 | import sys |
|
25 | import sys | |
26 | import shutil |
|
26 | import shutil | |
27 | import re |
|
27 | import re | |
28 | import time |
|
28 | import time | |
29 | import gc |
|
29 | import gc | |
30 | from StringIO import StringIO |
|
30 | from StringIO import StringIO | |
31 | from getopt import getopt,GetoptError |
|
31 | from getopt import getopt,GetoptError | |
32 | from pprint import pformat |
|
32 | from pprint import pformat | |
33 | from xmlrpclib import ServerProxy |
|
33 | from xmlrpclib import ServerProxy | |
34 |
|
34 | |||
35 | # cProfile was added in Python2.5 |
|
35 | # cProfile was added in Python2.5 | |
36 | try: |
|
36 | try: | |
37 | import cProfile as profile |
|
37 | import cProfile as profile | |
38 | import pstats |
|
38 | import pstats | |
39 | except ImportError: |
|
39 | except ImportError: | |
40 | # profile isn't bundled by default in Debian for license reasons |
|
40 | # profile isn't bundled by default in Debian for license reasons | |
41 | try: |
|
41 | try: | |
42 | import profile,pstats |
|
42 | import profile,pstats | |
43 | except ImportError: |
|
43 | except ImportError: | |
44 | profile = pstats = None |
|
44 | profile = pstats = None | |
45 |
|
45 | |||
46 | import IPython |
|
46 | import IPython | |
47 | from IPython.core import debugger, oinspect |
|
47 | from IPython.core import debugger, oinspect | |
48 | from IPython.core.error import TryNext |
|
48 | from IPython.core.error import TryNext | |
49 | from IPython.core.error import UsageError |
|
49 | from IPython.core.error import UsageError | |
50 | from IPython.core.error import StdinNotImplementedError |
|
50 | from IPython.core.error import StdinNotImplementedError | |
51 | from IPython.core.fakemodule import FakeModule |
|
51 | from IPython.core.fakemodule import FakeModule | |
52 | from IPython.core.profiledir import ProfileDir |
|
52 | from IPython.core.profiledir import ProfileDir | |
53 | from IPython.core.macro import Macro |
|
53 | from IPython.core.macro import Macro | |
54 | from IPython.core import magic_arguments, page |
|
54 | from IPython.core import magic_arguments, page | |
55 | from IPython.core.prefilter import ESC_MAGIC |
|
55 | from IPython.core.prefilter import ESC_MAGIC | |
56 | from IPython.core.pylabtools import mpl_runner |
|
56 | from IPython.core.pylabtools import mpl_runner | |
57 | from IPython.testing.skipdoctest import skip_doctest |
|
57 | from IPython.testing.skipdoctest import skip_doctest | |
58 | from IPython.utils import py3compat |
|
58 | from IPython.utils import py3compat | |
59 | from IPython.utils import openpy |
|
59 | from IPython.utils import openpy | |
60 |
from IPython.utils.encoding import |
|
60 | from IPython.utils.encoding import DEFAULT_ENCODING | |
61 | from IPython.utils.io import file_read, nlprint |
|
61 | from IPython.utils.io import file_read, nlprint | |
62 | from IPython.utils.module_paths import find_mod |
|
62 | from IPython.utils.module_paths import find_mod | |
63 | from IPython.utils.path import get_py_filename, unquote_filename |
|
63 | from IPython.utils.path import get_py_filename, unquote_filename | |
64 | from IPython.utils.process import arg_split, abbrev_cwd |
|
64 | from IPython.utils.process import arg_split, abbrev_cwd | |
65 | from IPython.utils.terminal import set_term_title |
|
65 | from IPython.utils.terminal import set_term_title | |
66 | from IPython.utils.text import LSString, SList, format_screen |
|
66 | from IPython.utils.text import LSString, SList, format_screen | |
67 | from IPython.utils.timing import clock, clock2 |
|
67 | from IPython.utils.timing import clock, clock2 | |
68 | from IPython.utils.warn import warn, error |
|
68 | from IPython.utils.warn import warn, error | |
69 | from IPython.utils.ipstruct import Struct |
|
69 | from IPython.utils.ipstruct import Struct | |
70 | from IPython.config.application import Application |
|
70 | from IPython.config.application import Application | |
71 |
|
71 | |||
72 | #----------------------------------------------------------------------------- |
|
72 | #----------------------------------------------------------------------------- | |
73 | # Utility functions |
|
73 | # Utility functions | |
74 | #----------------------------------------------------------------------------- |
|
74 | #----------------------------------------------------------------------------- | |
75 |
|
75 | |||
76 | def on_off(tag): |
|
76 | def on_off(tag): | |
77 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
77 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
78 | return ['OFF','ON'][tag] |
|
78 | return ['OFF','ON'][tag] | |
79 |
|
79 | |||
80 | class Bunch: pass |
|
80 | class Bunch: pass | |
81 |
|
81 | |||
82 | def compress_dhist(dh): |
|
82 | def compress_dhist(dh): | |
83 | head, tail = dh[:-10], dh[-10:] |
|
83 | head, tail = dh[:-10], dh[-10:] | |
84 |
|
84 | |||
85 | newhead = [] |
|
85 | newhead = [] | |
86 | done = set() |
|
86 | done = set() | |
87 | for h in head: |
|
87 | for h in head: | |
88 | if h in done: |
|
88 | if h in done: | |
89 | continue |
|
89 | continue | |
90 | newhead.append(h) |
|
90 | newhead.append(h) | |
91 | done.add(h) |
|
91 | done.add(h) | |
92 |
|
92 | |||
93 | return newhead + tail |
|
93 | return newhead + tail | |
94 |
|
94 | |||
95 | def needs_local_scope(func): |
|
95 | def needs_local_scope(func): | |
96 | """Decorator to mark magic functions which need to local scope to run.""" |
|
96 | """Decorator to mark magic functions which need to local scope to run.""" | |
97 | func.needs_local_scope = True |
|
97 | func.needs_local_scope = True | |
98 | return func |
|
98 | return func | |
99 |
|
99 | |||
100 |
|
100 | |||
101 | # Used for exception handling in magic_edit |
|
101 | # Used for exception handling in magic_edit | |
102 | class MacroToEdit(ValueError): pass |
|
102 | class MacroToEdit(ValueError): pass | |
103 |
|
103 | |||
104 | #*************************************************************************** |
|
104 | #*************************************************************************** | |
105 | # Main class implementing Magic functionality |
|
105 | # Main class implementing Magic functionality | |
106 |
|
106 | |||
107 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors |
|
107 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors | |
108 | # on construction of the main InteractiveShell object. Something odd is going |
|
108 | # on construction of the main InteractiveShell object. Something odd is going | |
109 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but |
|
109 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but | |
110 | # eventually this needs to be clarified. |
|
110 | # eventually this needs to be clarified. | |
111 | # BG: This is because InteractiveShell inherits from this, but is itself a |
|
111 | # BG: This is because InteractiveShell inherits from this, but is itself a | |
112 | # Configurable. This messes up the MRO in some way. The fix is that we need to |
|
112 | # Configurable. This messes up the MRO in some way. The fix is that we need to | |
113 | # make Magic a configurable that InteractiveShell does not subclass. |
|
113 | # make Magic a configurable that InteractiveShell does not subclass. | |
114 |
|
114 | |||
115 | class Magic: |
|
115 | class Magic: | |
116 | """Magic functions for InteractiveShell. |
|
116 | """Magic functions for InteractiveShell. | |
117 |
|
117 | |||
118 | Shell functions which can be reached as %function_name. All magic |
|
118 | Shell functions which can be reached as %function_name. All magic | |
119 | functions should accept a string, which they can parse for their own |
|
119 | functions should accept a string, which they can parse for their own | |
120 | needs. This can make some functions easier to type, eg `%cd ../` |
|
120 | needs. This can make some functions easier to type, eg `%cd ../` | |
121 | vs. `%cd("../")` |
|
121 | vs. `%cd("../")` | |
122 |
|
122 | |||
123 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
123 | ALL definitions MUST begin with the prefix magic_. The user won't need it | |
124 | at the command line, but it is is needed in the definition. """ |
|
124 | at the command line, but it is is needed in the definition. """ | |
125 |
|
125 | |||
126 | # class globals |
|
126 | # class globals | |
127 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
127 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', | |
128 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
128 | 'Automagic is ON, % prefix NOT needed for magic functions.'] | |
129 |
|
129 | |||
130 |
|
130 | |||
131 | configurables = None |
|
131 | configurables = None | |
132 | #...................................................................... |
|
132 | #...................................................................... | |
133 | # some utility functions |
|
133 | # some utility functions | |
134 |
|
134 | |||
135 | def __init__(self,shell): |
|
135 | def __init__(self,shell): | |
136 |
|
136 | |||
137 | self.options_table = {} |
|
137 | self.options_table = {} | |
138 | if profile is None: |
|
138 | if profile is None: | |
139 | self.magic_prun = self.profile_missing_notice |
|
139 | self.magic_prun = self.profile_missing_notice | |
140 | self.shell = shell |
|
140 | self.shell = shell | |
141 | if self.configurables is None: |
|
141 | if self.configurables is None: | |
142 | self.configurables = [] |
|
142 | self.configurables = [] | |
143 |
|
143 | |||
144 | # namespace for holding state we may need |
|
144 | # namespace for holding state we may need | |
145 | self._magic_state = Bunch() |
|
145 | self._magic_state = Bunch() | |
146 |
|
146 | |||
147 | def profile_missing_notice(self, *args, **kwargs): |
|
147 | def profile_missing_notice(self, *args, **kwargs): | |
148 | error("""\ |
|
148 | error("""\ | |
149 | The profile module could not be found. It has been removed from the standard |
|
149 | The profile module could not be found. It has been removed from the standard | |
150 | python packages because of its non-free license. To use profiling, install the |
|
150 | python packages because of its non-free license. To use profiling, install the | |
151 | python-profiler package from non-free.""") |
|
151 | python-profiler package from non-free.""") | |
152 |
|
152 | |||
153 | def default_option(self,fn,optstr): |
|
153 | def default_option(self,fn,optstr): | |
154 | """Make an entry in the options_table for fn, with value optstr""" |
|
154 | """Make an entry in the options_table for fn, with value optstr""" | |
155 |
|
155 | |||
156 | if fn not in self.lsmagic(): |
|
156 | if fn not in self.lsmagic(): | |
157 | error("%s is not a magic function" % fn) |
|
157 | error("%s is not a magic function" % fn) | |
158 | self.options_table[fn] = optstr |
|
158 | self.options_table[fn] = optstr | |
159 |
|
159 | |||
160 | def lsmagic(self): |
|
160 | def lsmagic(self): | |
161 | """Return a list of currently available magic functions. |
|
161 | """Return a list of currently available magic functions. | |
162 |
|
162 | |||
163 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
163 | Gives a list of the bare names after mangling (['ls','cd', ...], not | |
164 | ['magic_ls','magic_cd',...]""" |
|
164 | ['magic_ls','magic_cd',...]""" | |
165 |
|
165 | |||
166 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
166 | # FIXME. This needs a cleanup, in the way the magics list is built. | |
167 |
|
167 | |||
168 | # magics in class definition |
|
168 | # magics in class definition | |
169 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
169 | class_magic = lambda fn: fn.startswith('magic_') and \ | |
170 | callable(Magic.__dict__[fn]) |
|
170 | callable(Magic.__dict__[fn]) | |
171 | # in instance namespace (run-time user additions) |
|
171 | # in instance namespace (run-time user additions) | |
172 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
172 | inst_magic = lambda fn: fn.startswith('magic_') and \ | |
173 | callable(self.__dict__[fn]) |
|
173 | callable(self.__dict__[fn]) | |
174 | # and bound magics by user (so they can access self): |
|
174 | # and bound magics by user (so they can access self): | |
175 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
175 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ | |
176 | callable(self.__class__.__dict__[fn]) |
|
176 | callable(self.__class__.__dict__[fn]) | |
177 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
177 | magics = filter(class_magic,Magic.__dict__.keys()) + \ | |
178 | filter(inst_magic,self.__dict__.keys()) + \ |
|
178 | filter(inst_magic,self.__dict__.keys()) + \ | |
179 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
179 | filter(inst_bound_magic,self.__class__.__dict__.keys()) | |
180 | out = [] |
|
180 | out = [] | |
181 | for fn in set(magics): |
|
181 | for fn in set(magics): | |
182 | out.append(fn.replace('magic_','',1)) |
|
182 | out.append(fn.replace('magic_','',1)) | |
183 | out.sort() |
|
183 | out.sort() | |
184 | return out |
|
184 | return out | |
185 |
|
185 | |||
186 | def extract_input_lines(self, range_str, raw=False): |
|
186 | def extract_input_lines(self, range_str, raw=False): | |
187 | """Return as a string a set of input history slices. |
|
187 | """Return as a string a set of input history slices. | |
188 |
|
188 | |||
189 | Parameters |
|
189 | Parameters | |
190 | ---------- |
|
190 | ---------- | |
191 | range_str : string |
|
191 | range_str : string | |
192 | The set of slices is given as a string, like "~5/6-~4/2 4:8 9", |
|
192 | The set of slices is given as a string, like "~5/6-~4/2 4:8 9", | |
193 | since this function is for use by magic functions which get their |
|
193 | since this function is for use by magic functions which get their | |
194 | arguments as strings. The number before the / is the session |
|
194 | arguments as strings. The number before the / is the session | |
195 | number: ~n goes n back from the current session. |
|
195 | number: ~n goes n back from the current session. | |
196 |
|
196 | |||
197 | Optional Parameters: |
|
197 | Optional Parameters: | |
198 | - raw(False): by default, the processed input is used. If this is |
|
198 | - raw(False): by default, the processed input is used. If this is | |
199 | true, the raw input history is used instead. |
|
199 | true, the raw input history is used instead. | |
200 |
|
200 | |||
201 | Note that slices can be called with two notations: |
|
201 | Note that slices can be called with two notations: | |
202 |
|
202 | |||
203 | N:M -> standard python form, means including items N...(M-1). |
|
203 | N:M -> standard python form, means including items N...(M-1). | |
204 |
|
204 | |||
205 | N-M -> include items N..M (closed endpoint).""" |
|
205 | N-M -> include items N..M (closed endpoint).""" | |
206 | lines = self.shell.history_manager.\ |
|
206 | lines = self.shell.history_manager.\ | |
207 | get_range_by_str(range_str, raw=raw) |
|
207 | get_range_by_str(range_str, raw=raw) | |
208 | return "\n".join(x for _, _, x in lines) |
|
208 | return "\n".join(x for _, _, x in lines) | |
209 |
|
209 | |||
210 | def arg_err(self,func): |
|
210 | def arg_err(self,func): | |
211 | """Print docstring if incorrect arguments were passed""" |
|
211 | """Print docstring if incorrect arguments were passed""" | |
212 | print 'Error in arguments:' |
|
212 | print 'Error in arguments:' | |
213 | print oinspect.getdoc(func) |
|
213 | print oinspect.getdoc(func) | |
214 |
|
214 | |||
215 | def format_latex(self,strng): |
|
215 | def format_latex(self,strng): | |
216 | """Format a string for latex inclusion.""" |
|
216 | """Format a string for latex inclusion.""" | |
217 |
|
217 | |||
218 | # Characters that need to be escaped for latex: |
|
218 | # Characters that need to be escaped for latex: | |
219 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
219 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) | |
220 | # Magic command names as headers: |
|
220 | # Magic command names as headers: | |
221 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
221 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, | |
222 | re.MULTILINE) |
|
222 | re.MULTILINE) | |
223 | # Magic commands |
|
223 | # Magic commands | |
224 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
224 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, | |
225 | re.MULTILINE) |
|
225 | re.MULTILINE) | |
226 | # Paragraph continue |
|
226 | # Paragraph continue | |
227 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
227 | par_re = re.compile(r'\\$',re.MULTILINE) | |
228 |
|
228 | |||
229 | # The "\n" symbol |
|
229 | # The "\n" symbol | |
230 | newline_re = re.compile(r'\\n') |
|
230 | newline_re = re.compile(r'\\n') | |
231 |
|
231 | |||
232 | # Now build the string for output: |
|
232 | # Now build the string for output: | |
233 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
233 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) | |
234 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
234 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', | |
235 | strng) |
|
235 | strng) | |
236 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
236 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) | |
237 | strng = par_re.sub(r'\\\\',strng) |
|
237 | strng = par_re.sub(r'\\\\',strng) | |
238 | strng = escape_re.sub(r'\\\1',strng) |
|
238 | strng = escape_re.sub(r'\\\1',strng) | |
239 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
239 | strng = newline_re.sub(r'\\textbackslash{}n',strng) | |
240 | return strng |
|
240 | return strng | |
241 |
|
241 | |||
242 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
242 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): | |
243 | """Parse options passed to an argument string. |
|
243 | """Parse options passed to an argument string. | |
244 |
|
244 | |||
245 | The interface is similar to that of getopt(), but it returns back a |
|
245 | The interface is similar to that of getopt(), but it returns back a | |
246 | Struct with the options as keys and the stripped argument string still |
|
246 | Struct with the options as keys and the stripped argument string still | |
247 | as a string. |
|
247 | as a string. | |
248 |
|
248 | |||
249 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
249 | arg_str is quoted as a true sys.argv vector by using shlex.split. | |
250 | This allows us to easily expand variables, glob files, quote |
|
250 | This allows us to easily expand variables, glob files, quote | |
251 | arguments, etc. |
|
251 | arguments, etc. | |
252 |
|
252 | |||
253 | Options: |
|
253 | Options: | |
254 | -mode: default 'string'. If given as 'list', the argument string is |
|
254 | -mode: default 'string'. If given as 'list', the argument string is | |
255 | returned as a list (split on whitespace) instead of a string. |
|
255 | returned as a list (split on whitespace) instead of a string. | |
256 |
|
256 | |||
257 | -list_all: put all option values in lists. Normally only options |
|
257 | -list_all: put all option values in lists. Normally only options | |
258 | appearing more than once are put in a list. |
|
258 | appearing more than once are put in a list. | |
259 |
|
259 | |||
260 | -posix (True): whether to split the input line in POSIX mode or not, |
|
260 | -posix (True): whether to split the input line in POSIX mode or not, | |
261 | as per the conventions outlined in the shlex module from the |
|
261 | as per the conventions outlined in the shlex module from the | |
262 | standard library.""" |
|
262 | standard library.""" | |
263 |
|
263 | |||
264 | # inject default options at the beginning of the input line |
|
264 | # inject default options at the beginning of the input line | |
265 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
265 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') | |
266 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
266 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
267 |
|
267 | |||
268 | mode = kw.get('mode','string') |
|
268 | mode = kw.get('mode','string') | |
269 | if mode not in ['string','list']: |
|
269 | if mode not in ['string','list']: | |
270 | raise ValueError,'incorrect mode given: %s' % mode |
|
270 | raise ValueError,'incorrect mode given: %s' % mode | |
271 | # Get options |
|
271 | # Get options | |
272 | list_all = kw.get('list_all',0) |
|
272 | list_all = kw.get('list_all',0) | |
273 | posix = kw.get('posix', os.name == 'posix') |
|
273 | posix = kw.get('posix', os.name == 'posix') | |
274 | strict = kw.get('strict', True) |
|
274 | strict = kw.get('strict', True) | |
275 |
|
275 | |||
276 | # Check if we have more than one argument to warrant extra processing: |
|
276 | # Check if we have more than one argument to warrant extra processing: | |
277 | odict = {} # Dictionary with options |
|
277 | odict = {} # Dictionary with options | |
278 | args = arg_str.split() |
|
278 | args = arg_str.split() | |
279 | if len(args) >= 1: |
|
279 | if len(args) >= 1: | |
280 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
280 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
281 | # need to look for options |
|
281 | # need to look for options | |
282 | argv = arg_split(arg_str, posix, strict) |
|
282 | argv = arg_split(arg_str, posix, strict) | |
283 | # Do regular option processing |
|
283 | # Do regular option processing | |
284 | try: |
|
284 | try: | |
285 | opts,args = getopt(argv,opt_str,*long_opts) |
|
285 | opts,args = getopt(argv,opt_str,*long_opts) | |
286 | except GetoptError,e: |
|
286 | except GetoptError,e: | |
287 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
287 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, | |
288 | " ".join(long_opts))) |
|
288 | " ".join(long_opts))) | |
289 | for o,a in opts: |
|
289 | for o,a in opts: | |
290 | if o.startswith('--'): |
|
290 | if o.startswith('--'): | |
291 | o = o[2:] |
|
291 | o = o[2:] | |
292 | else: |
|
292 | else: | |
293 | o = o[1:] |
|
293 | o = o[1:] | |
294 | try: |
|
294 | try: | |
295 | odict[o].append(a) |
|
295 | odict[o].append(a) | |
296 | except AttributeError: |
|
296 | except AttributeError: | |
297 | odict[o] = [odict[o],a] |
|
297 | odict[o] = [odict[o],a] | |
298 | except KeyError: |
|
298 | except KeyError: | |
299 | if list_all: |
|
299 | if list_all: | |
300 | odict[o] = [a] |
|
300 | odict[o] = [a] | |
301 | else: |
|
301 | else: | |
302 | odict[o] = a |
|
302 | odict[o] = a | |
303 |
|
303 | |||
304 | # Prepare opts,args for return |
|
304 | # Prepare opts,args for return | |
305 | opts = Struct(odict) |
|
305 | opts = Struct(odict) | |
306 | if mode == 'string': |
|
306 | if mode == 'string': | |
307 | args = ' '.join(args) |
|
307 | args = ' '.join(args) | |
308 |
|
308 | |||
309 | return opts,args |
|
309 | return opts,args | |
310 |
|
310 | |||
311 | #...................................................................... |
|
311 | #...................................................................... | |
312 | # And now the actual magic functions |
|
312 | # And now the actual magic functions | |
313 |
|
313 | |||
314 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
314 | # Functions for IPython shell work (vars,funcs, config, etc) | |
315 | def magic_lsmagic(self, parameter_s = ''): |
|
315 | def magic_lsmagic(self, parameter_s = ''): | |
316 | """List currently available magic functions.""" |
|
316 | """List currently available magic functions.""" | |
317 | mesc = ESC_MAGIC |
|
317 | mesc = ESC_MAGIC | |
318 | print 'Available magic functions:\n'+mesc+\ |
|
318 | print 'Available magic functions:\n'+mesc+\ | |
319 | (' '+mesc).join(self.lsmagic()) |
|
319 | (' '+mesc).join(self.lsmagic()) | |
320 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
320 | print '\n' + Magic.auto_status[self.shell.automagic] | |
321 | return None |
|
321 | return None | |
322 |
|
322 | |||
323 | def magic_magic(self, parameter_s = ''): |
|
323 | def magic_magic(self, parameter_s = ''): | |
324 | """Print information about the magic function system. |
|
324 | """Print information about the magic function system. | |
325 |
|
325 | |||
326 | Supported formats: -latex, -brief, -rest |
|
326 | Supported formats: -latex, -brief, -rest | |
327 | """ |
|
327 | """ | |
328 |
|
328 | |||
329 | mode = '' |
|
329 | mode = '' | |
330 | try: |
|
330 | try: | |
331 | if parameter_s.split()[0] == '-latex': |
|
331 | if parameter_s.split()[0] == '-latex': | |
332 | mode = 'latex' |
|
332 | mode = 'latex' | |
333 | if parameter_s.split()[0] == '-brief': |
|
333 | if parameter_s.split()[0] == '-brief': | |
334 | mode = 'brief' |
|
334 | mode = 'brief' | |
335 | if parameter_s.split()[0] == '-rest': |
|
335 | if parameter_s.split()[0] == '-rest': | |
336 | mode = 'rest' |
|
336 | mode = 'rest' | |
337 | rest_docs = [] |
|
337 | rest_docs = [] | |
338 | except: |
|
338 | except: | |
339 | pass |
|
339 | pass | |
340 |
|
340 | |||
341 | magic_docs = [] |
|
341 | magic_docs = [] | |
342 | for fname in self.lsmagic(): |
|
342 | for fname in self.lsmagic(): | |
343 | mname = 'magic_' + fname |
|
343 | mname = 'magic_' + fname | |
344 | for space in (Magic,self,self.__class__): |
|
344 | for space in (Magic,self,self.__class__): | |
345 | try: |
|
345 | try: | |
346 | fn = space.__dict__[mname] |
|
346 | fn = space.__dict__[mname] | |
347 | except KeyError: |
|
347 | except KeyError: | |
348 | pass |
|
348 | pass | |
349 | else: |
|
349 | else: | |
350 | break |
|
350 | break | |
351 | if mode == 'brief': |
|
351 | if mode == 'brief': | |
352 | # only first line |
|
352 | # only first line | |
353 | if fn.__doc__: |
|
353 | if fn.__doc__: | |
354 | fndoc = fn.__doc__.split('\n',1)[0] |
|
354 | fndoc = fn.__doc__.split('\n',1)[0] | |
355 | else: |
|
355 | else: | |
356 | fndoc = 'No documentation' |
|
356 | fndoc = 'No documentation' | |
357 | else: |
|
357 | else: | |
358 | if fn.__doc__: |
|
358 | if fn.__doc__: | |
359 | fndoc = fn.__doc__.rstrip() |
|
359 | fndoc = fn.__doc__.rstrip() | |
360 | else: |
|
360 | else: | |
361 | fndoc = 'No documentation' |
|
361 | fndoc = 'No documentation' | |
362 |
|
362 | |||
363 |
|
363 | |||
364 | if mode == 'rest': |
|
364 | if mode == 'rest': | |
365 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, |
|
365 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, | |
366 | fname,fndoc)) |
|
366 | fname,fndoc)) | |
367 |
|
367 | |||
368 | else: |
|
368 | else: | |
369 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, |
|
369 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, | |
370 | fname,fndoc)) |
|
370 | fname,fndoc)) | |
371 |
|
371 | |||
372 | magic_docs = ''.join(magic_docs) |
|
372 | magic_docs = ''.join(magic_docs) | |
373 |
|
373 | |||
374 | if mode == 'rest': |
|
374 | if mode == 'rest': | |
375 | return "".join(rest_docs) |
|
375 | return "".join(rest_docs) | |
376 |
|
376 | |||
377 | if mode == 'latex': |
|
377 | if mode == 'latex': | |
378 | print self.format_latex(magic_docs) |
|
378 | print self.format_latex(magic_docs) | |
379 | return |
|
379 | return | |
380 | else: |
|
380 | else: | |
381 | magic_docs = format_screen(magic_docs) |
|
381 | magic_docs = format_screen(magic_docs) | |
382 | if mode == 'brief': |
|
382 | if mode == 'brief': | |
383 | return magic_docs |
|
383 | return magic_docs | |
384 |
|
384 | |||
385 | outmsg = """ |
|
385 | outmsg = """ | |
386 | IPython's 'magic' functions |
|
386 | IPython's 'magic' functions | |
387 | =========================== |
|
387 | =========================== | |
388 |
|
388 | |||
389 | The magic function system provides a series of functions which allow you to |
|
389 | The magic function system provides a series of functions which allow you to | |
390 | control the behavior of IPython itself, plus a lot of system-type |
|
390 | control the behavior of IPython itself, plus a lot of system-type | |
391 | features. All these functions are prefixed with a % character, but parameters |
|
391 | features. All these functions are prefixed with a % character, but parameters | |
392 | are given without parentheses or quotes. |
|
392 | are given without parentheses or quotes. | |
393 |
|
393 | |||
394 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
394 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
395 | %automagic function), you don't need to type in the % explicitly. By default, |
|
395 | %automagic function), you don't need to type in the % explicitly. By default, | |
396 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
396 | IPython ships with automagic on, so you should only rarely need the % escape. | |
397 |
|
397 | |||
398 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
398 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
399 | to 'mydir', if it exists. |
|
399 | to 'mydir', if it exists. | |
400 |
|
400 | |||
401 | For a list of the available magic functions, use %lsmagic. For a description |
|
401 | For a list of the available magic functions, use %lsmagic. For a description | |
402 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
402 | of any of them, type %magic_name?, e.g. '%cd?'. | |
403 |
|
403 | |||
404 | Currently the magic system has the following functions:\n""" |
|
404 | Currently the magic system has the following functions:\n""" | |
405 |
|
405 | |||
406 | mesc = ESC_MAGIC |
|
406 | mesc = ESC_MAGIC | |
407 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
407 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" | |
408 | "\n\n%s%s\n\n%s" % (outmsg, |
|
408 | "\n\n%s%s\n\n%s" % (outmsg, | |
409 | magic_docs,mesc,mesc, |
|
409 | magic_docs,mesc,mesc, | |
410 | (' '+mesc).join(self.lsmagic()), |
|
410 | (' '+mesc).join(self.lsmagic()), | |
411 | Magic.auto_status[self.shell.automagic] ) ) |
|
411 | Magic.auto_status[self.shell.automagic] ) ) | |
412 | page.page(outmsg) |
|
412 | page.page(outmsg) | |
413 |
|
413 | |||
414 | def magic_automagic(self, parameter_s = ''): |
|
414 | def magic_automagic(self, parameter_s = ''): | |
415 | """Make magic functions callable without having to type the initial %. |
|
415 | """Make magic functions callable without having to type the initial %. | |
416 |
|
416 | |||
417 | Without argumentsl toggles on/off (when off, you must call it as |
|
417 | Without argumentsl toggles on/off (when off, you must call it as | |
418 | %automagic, of course). With arguments it sets the value, and you can |
|
418 | %automagic, of course). With arguments it sets the value, and you can | |
419 | use any of (case insensitive): |
|
419 | use any of (case insensitive): | |
420 |
|
420 | |||
421 | - on,1,True: to activate |
|
421 | - on,1,True: to activate | |
422 |
|
422 | |||
423 | - off,0,False: to deactivate. |
|
423 | - off,0,False: to deactivate. | |
424 |
|
424 | |||
425 | Note that magic functions have lowest priority, so if there's a |
|
425 | Note that magic functions have lowest priority, so if there's a | |
426 | variable whose name collides with that of a magic fn, automagic won't |
|
426 | variable whose name collides with that of a magic fn, automagic won't | |
427 | work for that function (you get the variable instead). However, if you |
|
427 | work for that function (you get the variable instead). However, if you | |
428 | delete the variable (del var), the previously shadowed magic function |
|
428 | delete the variable (del var), the previously shadowed magic function | |
429 | becomes visible to automagic again.""" |
|
429 | becomes visible to automagic again.""" | |
430 |
|
430 | |||
431 | arg = parameter_s.lower() |
|
431 | arg = parameter_s.lower() | |
432 | if parameter_s in ('on','1','true'): |
|
432 | if parameter_s in ('on','1','true'): | |
433 | self.shell.automagic = True |
|
433 | self.shell.automagic = True | |
434 | elif parameter_s in ('off','0','false'): |
|
434 | elif parameter_s in ('off','0','false'): | |
435 | self.shell.automagic = False |
|
435 | self.shell.automagic = False | |
436 | else: |
|
436 | else: | |
437 | self.shell.automagic = not self.shell.automagic |
|
437 | self.shell.automagic = not self.shell.automagic | |
438 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
438 | print '\n' + Magic.auto_status[self.shell.automagic] | |
439 |
|
439 | |||
440 | @skip_doctest |
|
440 | @skip_doctest | |
441 | def magic_autocall(self, parameter_s = ''): |
|
441 | def magic_autocall(self, parameter_s = ''): | |
442 | """Make functions callable without having to type parentheses. |
|
442 | """Make functions callable without having to type parentheses. | |
443 |
|
443 | |||
444 | Usage: |
|
444 | Usage: | |
445 |
|
445 | |||
446 | %autocall [mode] |
|
446 | %autocall [mode] | |
447 |
|
447 | |||
448 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
448 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the | |
449 | value is toggled on and off (remembering the previous state). |
|
449 | value is toggled on and off (remembering the previous state). | |
450 |
|
450 | |||
451 | In more detail, these values mean: |
|
451 | In more detail, these values mean: | |
452 |
|
452 | |||
453 | 0 -> fully disabled |
|
453 | 0 -> fully disabled | |
454 |
|
454 | |||
455 | 1 -> active, but do not apply if there are no arguments on the line. |
|
455 | 1 -> active, but do not apply if there are no arguments on the line. | |
456 |
|
456 | |||
457 | In this mode, you get:: |
|
457 | In this mode, you get:: | |
458 |
|
458 | |||
459 | In [1]: callable |
|
459 | In [1]: callable | |
460 | Out[1]: <built-in function callable> |
|
460 | Out[1]: <built-in function callable> | |
461 |
|
461 | |||
462 | In [2]: callable 'hello' |
|
462 | In [2]: callable 'hello' | |
463 | ------> callable('hello') |
|
463 | ------> callable('hello') | |
464 | Out[2]: False |
|
464 | Out[2]: False | |
465 |
|
465 | |||
466 | 2 -> Active always. Even if no arguments are present, the callable |
|
466 | 2 -> Active always. Even if no arguments are present, the callable | |
467 | object is called:: |
|
467 | object is called:: | |
468 |
|
468 | |||
469 | In [2]: float |
|
469 | In [2]: float | |
470 | ------> float() |
|
470 | ------> float() | |
471 | Out[2]: 0.0 |
|
471 | Out[2]: 0.0 | |
472 |
|
472 | |||
473 | Note that even with autocall off, you can still use '/' at the start of |
|
473 | Note that even with autocall off, you can still use '/' at the start of | |
474 | a line to treat the first argument on the command line as a function |
|
474 | a line to treat the first argument on the command line as a function | |
475 | and add parentheses to it:: |
|
475 | and add parentheses to it:: | |
476 |
|
476 | |||
477 | In [8]: /str 43 |
|
477 | In [8]: /str 43 | |
478 | ------> str(43) |
|
478 | ------> str(43) | |
479 | Out[8]: '43' |
|
479 | Out[8]: '43' | |
480 |
|
480 | |||
481 | # all-random (note for auto-testing) |
|
481 | # all-random (note for auto-testing) | |
482 | """ |
|
482 | """ | |
483 |
|
483 | |||
484 | if parameter_s: |
|
484 | if parameter_s: | |
485 | arg = int(parameter_s) |
|
485 | arg = int(parameter_s) | |
486 | else: |
|
486 | else: | |
487 | arg = 'toggle' |
|
487 | arg = 'toggle' | |
488 |
|
488 | |||
489 | if not arg in (0,1,2,'toggle'): |
|
489 | if not arg in (0,1,2,'toggle'): | |
490 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
490 | error('Valid modes: (0->Off, 1->Smart, 2->Full') | |
491 | return |
|
491 | return | |
492 |
|
492 | |||
493 | if arg in (0,1,2): |
|
493 | if arg in (0,1,2): | |
494 | self.shell.autocall = arg |
|
494 | self.shell.autocall = arg | |
495 | else: # toggle |
|
495 | else: # toggle | |
496 | if self.shell.autocall: |
|
496 | if self.shell.autocall: | |
497 | self._magic_state.autocall_save = self.shell.autocall |
|
497 | self._magic_state.autocall_save = self.shell.autocall | |
498 | self.shell.autocall = 0 |
|
498 | self.shell.autocall = 0 | |
499 | else: |
|
499 | else: | |
500 | try: |
|
500 | try: | |
501 | self.shell.autocall = self._magic_state.autocall_save |
|
501 | self.shell.autocall = self._magic_state.autocall_save | |
502 | except AttributeError: |
|
502 | except AttributeError: | |
503 | self.shell.autocall = self._magic_state.autocall_save = 1 |
|
503 | self.shell.autocall = self._magic_state.autocall_save = 1 | |
504 |
|
504 | |||
505 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] |
|
505 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] | |
506 |
|
506 | |||
507 |
|
507 | |||
508 | def magic_page(self, parameter_s=''): |
|
508 | def magic_page(self, parameter_s=''): | |
509 | """Pretty print the object and display it through a pager. |
|
509 | """Pretty print the object and display it through a pager. | |
510 |
|
510 | |||
511 | %page [options] OBJECT |
|
511 | %page [options] OBJECT | |
512 |
|
512 | |||
513 | If no object is given, use _ (last output). |
|
513 | If no object is given, use _ (last output). | |
514 |
|
514 | |||
515 | Options: |
|
515 | Options: | |
516 |
|
516 | |||
517 | -r: page str(object), don't pretty-print it.""" |
|
517 | -r: page str(object), don't pretty-print it.""" | |
518 |
|
518 | |||
519 | # After a function contributed by Olivier Aubert, slightly modified. |
|
519 | # After a function contributed by Olivier Aubert, slightly modified. | |
520 |
|
520 | |||
521 | # Process options/args |
|
521 | # Process options/args | |
522 | opts,args = self.parse_options(parameter_s,'r') |
|
522 | opts,args = self.parse_options(parameter_s,'r') | |
523 | raw = 'r' in opts |
|
523 | raw = 'r' in opts | |
524 |
|
524 | |||
525 | oname = args and args or '_' |
|
525 | oname = args and args or '_' | |
526 | info = self._ofind(oname) |
|
526 | info = self._ofind(oname) | |
527 | if info['found']: |
|
527 | if info['found']: | |
528 | txt = (raw and str or pformat)( info['obj'] ) |
|
528 | txt = (raw and str or pformat)( info['obj'] ) | |
529 | page.page(txt) |
|
529 | page.page(txt) | |
530 | else: |
|
530 | else: | |
531 | print 'Object `%s` not found' % oname |
|
531 | print 'Object `%s` not found' % oname | |
532 |
|
532 | |||
533 | def magic_profile(self, parameter_s=''): |
|
533 | def magic_profile(self, parameter_s=''): | |
534 | """Print your currently active IPython profile.""" |
|
534 | """Print your currently active IPython profile.""" | |
535 | from IPython.core.application import BaseIPythonApplication |
|
535 | from IPython.core.application import BaseIPythonApplication | |
536 | if BaseIPythonApplication.initialized(): |
|
536 | if BaseIPythonApplication.initialized(): | |
537 | print BaseIPythonApplication.instance().profile |
|
537 | print BaseIPythonApplication.instance().profile | |
538 | else: |
|
538 | else: | |
539 | error("profile is an application-level value, but you don't appear to be in an IPython application") |
|
539 | error("profile is an application-level value, but you don't appear to be in an IPython application") | |
540 |
|
540 | |||
541 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
541 | def magic_pinfo(self, parameter_s='', namespaces=None): | |
542 | """Provide detailed information about an object. |
|
542 | """Provide detailed information about an object. | |
543 |
|
543 | |||
544 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
544 | '%pinfo object' is just a synonym for object? or ?object.""" | |
545 |
|
545 | |||
546 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
546 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
547 |
|
547 | |||
548 |
|
548 | |||
549 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
549 | # detail_level: 0 -> obj? , 1 -> obj?? | |
550 | detail_level = 0 |
|
550 | detail_level = 0 | |
551 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
551 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
552 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
552 | # happen if the user types 'pinfo foo?' at the cmd line. | |
553 | pinfo,qmark1,oname,qmark2 = \ |
|
553 | pinfo,qmark1,oname,qmark2 = \ | |
554 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
554 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
555 | if pinfo or qmark1 or qmark2: |
|
555 | if pinfo or qmark1 or qmark2: | |
556 | detail_level = 1 |
|
556 | detail_level = 1 | |
557 | if "*" in oname: |
|
557 | if "*" in oname: | |
558 | self.magic_psearch(oname) |
|
558 | self.magic_psearch(oname) | |
559 | else: |
|
559 | else: | |
560 | self.shell._inspect('pinfo', oname, detail_level=detail_level, |
|
560 | self.shell._inspect('pinfo', oname, detail_level=detail_level, | |
561 | namespaces=namespaces) |
|
561 | namespaces=namespaces) | |
562 |
|
562 | |||
563 | def magic_pinfo2(self, parameter_s='', namespaces=None): |
|
563 | def magic_pinfo2(self, parameter_s='', namespaces=None): | |
564 | """Provide extra detailed information about an object. |
|
564 | """Provide extra detailed information about an object. | |
565 |
|
565 | |||
566 | '%pinfo2 object' is just a synonym for object?? or ??object.""" |
|
566 | '%pinfo2 object' is just a synonym for object?? or ??object.""" | |
567 | self.shell._inspect('pinfo', parameter_s, detail_level=1, |
|
567 | self.shell._inspect('pinfo', parameter_s, detail_level=1, | |
568 | namespaces=namespaces) |
|
568 | namespaces=namespaces) | |
569 |
|
569 | |||
570 | @skip_doctest |
|
570 | @skip_doctest | |
571 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
571 | def magic_pdef(self, parameter_s='', namespaces=None): | |
572 | """Print the definition header for any callable object. |
|
572 | """Print the definition header for any callable object. | |
573 |
|
573 | |||
574 | If the object is a class, print the constructor information. |
|
574 | If the object is a class, print the constructor information. | |
575 |
|
575 | |||
576 | Examples |
|
576 | Examples | |
577 | -------- |
|
577 | -------- | |
578 | :: |
|
578 | :: | |
579 |
|
579 | |||
580 | In [3]: %pdef urllib.urlopen |
|
580 | In [3]: %pdef urllib.urlopen | |
581 | urllib.urlopen(url, data=None, proxies=None) |
|
581 | urllib.urlopen(url, data=None, proxies=None) | |
582 | """ |
|
582 | """ | |
583 | self._inspect('pdef',parameter_s, namespaces) |
|
583 | self._inspect('pdef',parameter_s, namespaces) | |
584 |
|
584 | |||
585 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
585 | def magic_pdoc(self, parameter_s='', namespaces=None): | |
586 | """Print the docstring for an object. |
|
586 | """Print the docstring for an object. | |
587 |
|
587 | |||
588 | If the given object is a class, it will print both the class and the |
|
588 | If the given object is a class, it will print both the class and the | |
589 | constructor docstrings.""" |
|
589 | constructor docstrings.""" | |
590 | self._inspect('pdoc',parameter_s, namespaces) |
|
590 | self._inspect('pdoc',parameter_s, namespaces) | |
591 |
|
591 | |||
592 | def magic_psource(self, parameter_s='', namespaces=None): |
|
592 | def magic_psource(self, parameter_s='', namespaces=None): | |
593 | """Print (or run through pager) the source code for an object.""" |
|
593 | """Print (or run through pager) the source code for an object.""" | |
594 | self._inspect('psource',parameter_s, namespaces) |
|
594 | self._inspect('psource',parameter_s, namespaces) | |
595 |
|
595 | |||
596 | def magic_pfile(self, parameter_s=''): |
|
596 | def magic_pfile(self, parameter_s=''): | |
597 | """Print (or run through pager) the file where an object is defined. |
|
597 | """Print (or run through pager) the file where an object is defined. | |
598 |
|
598 | |||
599 | The file opens at the line where the object definition begins. IPython |
|
599 | The file opens at the line where the object definition begins. IPython | |
600 | will honor the environment variable PAGER if set, and otherwise will |
|
600 | will honor the environment variable PAGER if set, and otherwise will | |
601 | do its best to print the file in a convenient form. |
|
601 | do its best to print the file in a convenient form. | |
602 |
|
602 | |||
603 | If the given argument is not an object currently defined, IPython will |
|
603 | If the given argument is not an object currently defined, IPython will | |
604 | try to interpret it as a filename (automatically adding a .py extension |
|
604 | try to interpret it as a filename (automatically adding a .py extension | |
605 | if needed). You can thus use %pfile as a syntax highlighting code |
|
605 | if needed). You can thus use %pfile as a syntax highlighting code | |
606 | viewer.""" |
|
606 | viewer.""" | |
607 |
|
607 | |||
608 | # first interpret argument as an object name |
|
608 | # first interpret argument as an object name | |
609 | out = self._inspect('pfile',parameter_s) |
|
609 | out = self._inspect('pfile',parameter_s) | |
610 | # if not, try the input as a filename |
|
610 | # if not, try the input as a filename | |
611 | if out == 'not found': |
|
611 | if out == 'not found': | |
612 | try: |
|
612 | try: | |
613 | filename = get_py_filename(parameter_s) |
|
613 | filename = get_py_filename(parameter_s) | |
614 | except IOError,msg: |
|
614 | except IOError,msg: | |
615 | print msg |
|
615 | print msg | |
616 | return |
|
616 | return | |
617 | page.page(self.shell.inspector.format(open(filename).read())) |
|
617 | page.page(self.shell.inspector.format(open(filename).read())) | |
618 |
|
618 | |||
619 | def magic_psearch(self, parameter_s=''): |
|
619 | def magic_psearch(self, parameter_s=''): | |
620 | """Search for object in namespaces by wildcard. |
|
620 | """Search for object in namespaces by wildcard. | |
621 |
|
621 | |||
622 | %psearch [options] PATTERN [OBJECT TYPE] |
|
622 | %psearch [options] PATTERN [OBJECT TYPE] | |
623 |
|
623 | |||
624 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
624 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
625 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
625 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
626 | rest of the command line must be unchanged (options come first), so |
|
626 | rest of the command line must be unchanged (options come first), so | |
627 | for example the following forms are equivalent |
|
627 | for example the following forms are equivalent | |
628 |
|
628 | |||
629 | %psearch -i a* function |
|
629 | %psearch -i a* function | |
630 | -i a* function? |
|
630 | -i a* function? | |
631 | ?-i a* function |
|
631 | ?-i a* function | |
632 |
|
632 | |||
633 | Arguments: |
|
633 | Arguments: | |
634 |
|
634 | |||
635 | PATTERN |
|
635 | PATTERN | |
636 |
|
636 | |||
637 | where PATTERN is a string containing * as a wildcard similar to its |
|
637 | where PATTERN is a string containing * as a wildcard similar to its | |
638 | use in a shell. The pattern is matched in all namespaces on the |
|
638 | use in a shell. The pattern is matched in all namespaces on the | |
639 | search path. By default objects starting with a single _ are not |
|
639 | search path. By default objects starting with a single _ are not | |
640 | matched, many IPython generated objects have a single |
|
640 | matched, many IPython generated objects have a single | |
641 | underscore. The default is case insensitive matching. Matching is |
|
641 | underscore. The default is case insensitive matching. Matching is | |
642 | also done on the attributes of objects and not only on the objects |
|
642 | also done on the attributes of objects and not only on the objects | |
643 | in a module. |
|
643 | in a module. | |
644 |
|
644 | |||
645 | [OBJECT TYPE] |
|
645 | [OBJECT TYPE] | |
646 |
|
646 | |||
647 | Is the name of a python type from the types module. The name is |
|
647 | Is the name of a python type from the types module. The name is | |
648 | given in lowercase without the ending type, ex. StringType is |
|
648 | given in lowercase without the ending type, ex. StringType is | |
649 | written string. By adding a type here only objects matching the |
|
649 | written string. By adding a type here only objects matching the | |
650 | given type are matched. Using all here makes the pattern match all |
|
650 | given type are matched. Using all here makes the pattern match all | |
651 | types (this is the default). |
|
651 | types (this is the default). | |
652 |
|
652 | |||
653 | Options: |
|
653 | Options: | |
654 |
|
654 | |||
655 | -a: makes the pattern match even objects whose names start with a |
|
655 | -a: makes the pattern match even objects whose names start with a | |
656 | single underscore. These names are normally omitted from the |
|
656 | single underscore. These names are normally omitted from the | |
657 | search. |
|
657 | search. | |
658 |
|
658 | |||
659 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
659 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
660 | these options are given, the default is read from your configuration |
|
660 | these options are given, the default is read from your configuration | |
661 | file, with the option ``InteractiveShell.wildcards_case_sensitive``. |
|
661 | file, with the option ``InteractiveShell.wildcards_case_sensitive``. | |
662 | If this option is not specified in your configuration file, IPython's |
|
662 | If this option is not specified in your configuration file, IPython's | |
663 | internal default is to do a case sensitive search. |
|
663 | internal default is to do a case sensitive search. | |
664 |
|
664 | |||
665 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
665 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
666 | specify can be searched in any of the following namespaces: |
|
666 | specify can be searched in any of the following namespaces: | |
667 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
667 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
668 | 'builtin' and 'user' are the search defaults. Note that you should |
|
668 | 'builtin' and 'user' are the search defaults. Note that you should | |
669 | not use quotes when specifying namespaces. |
|
669 | not use quotes when specifying namespaces. | |
670 |
|
670 | |||
671 | 'Builtin' contains the python module builtin, 'user' contains all |
|
671 | 'Builtin' contains the python module builtin, 'user' contains all | |
672 | user data, 'alias' only contain the shell aliases and no python |
|
672 | user data, 'alias' only contain the shell aliases and no python | |
673 | objects, 'internal' contains objects used by IPython. The |
|
673 | objects, 'internal' contains objects used by IPython. The | |
674 | 'user_global' namespace is only used by embedded IPython instances, |
|
674 | 'user_global' namespace is only used by embedded IPython instances, | |
675 | and it contains module-level globals. You can add namespaces to the |
|
675 | and it contains module-level globals. You can add namespaces to the | |
676 | search with -s or exclude them with -e (these options can be given |
|
676 | search with -s or exclude them with -e (these options can be given | |
677 | more than once). |
|
677 | more than once). | |
678 |
|
678 | |||
679 | Examples |
|
679 | Examples | |
680 | -------- |
|
680 | -------- | |
681 | :: |
|
681 | :: | |
682 |
|
682 | |||
683 | %psearch a* -> objects beginning with an a |
|
683 | %psearch a* -> objects beginning with an a | |
684 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
684 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
685 | %psearch a* function -> all functions beginning with an a |
|
685 | %psearch a* function -> all functions beginning with an a | |
686 | %psearch re.e* -> objects beginning with an e in module re |
|
686 | %psearch re.e* -> objects beginning with an e in module re | |
687 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
687 | %psearch r*.e* -> objects that start with e in modules starting in r | |
688 | %psearch r*.* string -> all strings in modules beginning with r |
|
688 | %psearch r*.* string -> all strings in modules beginning with r | |
689 |
|
689 | |||
690 | Case sensitive search:: |
|
690 | Case sensitive search:: | |
691 |
|
691 | |||
692 | %psearch -c a* list all object beginning with lower case a |
|
692 | %psearch -c a* list all object beginning with lower case a | |
693 |
|
693 | |||
694 | Show objects beginning with a single _:: |
|
694 | Show objects beginning with a single _:: | |
695 |
|
695 | |||
696 | %psearch -a _* list objects beginning with a single underscore""" |
|
696 | %psearch -a _* list objects beginning with a single underscore""" | |
697 | try: |
|
697 | try: | |
698 | parameter_s.encode('ascii') |
|
698 | parameter_s.encode('ascii') | |
699 | except UnicodeEncodeError: |
|
699 | except UnicodeEncodeError: | |
700 | print 'Python identifiers can only contain ascii characters.' |
|
700 | print 'Python identifiers can only contain ascii characters.' | |
701 | return |
|
701 | return | |
702 |
|
702 | |||
703 | # default namespaces to be searched |
|
703 | # default namespaces to be searched | |
704 | def_search = ['user_local', 'user_global', 'builtin'] |
|
704 | def_search = ['user_local', 'user_global', 'builtin'] | |
705 |
|
705 | |||
706 | # Process options/args |
|
706 | # Process options/args | |
707 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
707 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
708 | opt = opts.get |
|
708 | opt = opts.get | |
709 | shell = self.shell |
|
709 | shell = self.shell | |
710 | psearch = shell.inspector.psearch |
|
710 | psearch = shell.inspector.psearch | |
711 |
|
711 | |||
712 | # select case options |
|
712 | # select case options | |
713 | if opts.has_key('i'): |
|
713 | if opts.has_key('i'): | |
714 | ignore_case = True |
|
714 | ignore_case = True | |
715 | elif opts.has_key('c'): |
|
715 | elif opts.has_key('c'): | |
716 | ignore_case = False |
|
716 | ignore_case = False | |
717 | else: |
|
717 | else: | |
718 | ignore_case = not shell.wildcards_case_sensitive |
|
718 | ignore_case = not shell.wildcards_case_sensitive | |
719 |
|
719 | |||
720 | # Build list of namespaces to search from user options |
|
720 | # Build list of namespaces to search from user options | |
721 | def_search.extend(opt('s',[])) |
|
721 | def_search.extend(opt('s',[])) | |
722 | ns_exclude = ns_exclude=opt('e',[]) |
|
722 | ns_exclude = ns_exclude=opt('e',[]) | |
723 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
723 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
724 |
|
724 | |||
725 | # Call the actual search |
|
725 | # Call the actual search | |
726 | try: |
|
726 | try: | |
727 | psearch(args,shell.ns_table,ns_search, |
|
727 | psearch(args,shell.ns_table,ns_search, | |
728 | show_all=opt('a'),ignore_case=ignore_case) |
|
728 | show_all=opt('a'),ignore_case=ignore_case) | |
729 | except: |
|
729 | except: | |
730 | shell.showtraceback() |
|
730 | shell.showtraceback() | |
731 |
|
731 | |||
732 | @skip_doctest |
|
732 | @skip_doctest | |
733 | def magic_who_ls(self, parameter_s=''): |
|
733 | def magic_who_ls(self, parameter_s=''): | |
734 | """Return a sorted list of all interactive variables. |
|
734 | """Return a sorted list of all interactive variables. | |
735 |
|
735 | |||
736 | If arguments are given, only variables of types matching these |
|
736 | If arguments are given, only variables of types matching these | |
737 | arguments are returned. |
|
737 | arguments are returned. | |
738 |
|
738 | |||
739 | Examples |
|
739 | Examples | |
740 | -------- |
|
740 | -------- | |
741 |
|
741 | |||
742 | Define two variables and list them with who_ls:: |
|
742 | Define two variables and list them with who_ls:: | |
743 |
|
743 | |||
744 | In [1]: alpha = 123 |
|
744 | In [1]: alpha = 123 | |
745 |
|
745 | |||
746 | In [2]: beta = 'test' |
|
746 | In [2]: beta = 'test' | |
747 |
|
747 | |||
748 | In [3]: %who_ls |
|
748 | In [3]: %who_ls | |
749 | Out[3]: ['alpha', 'beta'] |
|
749 | Out[3]: ['alpha', 'beta'] | |
750 |
|
750 | |||
751 | In [4]: %who_ls int |
|
751 | In [4]: %who_ls int | |
752 | Out[4]: ['alpha'] |
|
752 | Out[4]: ['alpha'] | |
753 |
|
753 | |||
754 | In [5]: %who_ls str |
|
754 | In [5]: %who_ls str | |
755 | Out[5]: ['beta'] |
|
755 | Out[5]: ['beta'] | |
756 | """ |
|
756 | """ | |
757 |
|
757 | |||
758 | user_ns = self.shell.user_ns |
|
758 | user_ns = self.shell.user_ns | |
759 | user_ns_hidden = self.shell.user_ns_hidden |
|
759 | user_ns_hidden = self.shell.user_ns_hidden | |
760 | out = [ i for i in user_ns |
|
760 | out = [ i for i in user_ns | |
761 | if not i.startswith('_') \ |
|
761 | if not i.startswith('_') \ | |
762 | and not i in user_ns_hidden ] |
|
762 | and not i in user_ns_hidden ] | |
763 |
|
763 | |||
764 | typelist = parameter_s.split() |
|
764 | typelist = parameter_s.split() | |
765 | if typelist: |
|
765 | if typelist: | |
766 | typeset = set(typelist) |
|
766 | typeset = set(typelist) | |
767 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] |
|
767 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] | |
768 |
|
768 | |||
769 | out.sort() |
|
769 | out.sort() | |
770 | return out |
|
770 | return out | |
771 |
|
771 | |||
772 | @skip_doctest |
|
772 | @skip_doctest | |
773 | def magic_who(self, parameter_s=''): |
|
773 | def magic_who(self, parameter_s=''): | |
774 | """Print all interactive variables, with some minimal formatting. |
|
774 | """Print all interactive variables, with some minimal formatting. | |
775 |
|
775 | |||
776 | If any arguments are given, only variables whose type matches one of |
|
776 | If any arguments are given, only variables whose type matches one of | |
777 | these are printed. For example:: |
|
777 | these are printed. For example:: | |
778 |
|
778 | |||
779 | %who function str |
|
779 | %who function str | |
780 |
|
780 | |||
781 | will only list functions and strings, excluding all other types of |
|
781 | will only list functions and strings, excluding all other types of | |
782 | variables. To find the proper type names, simply use type(var) at a |
|
782 | variables. To find the proper type names, simply use type(var) at a | |
783 | command line to see how python prints type names. For example: |
|
783 | command line to see how python prints type names. For example: | |
784 |
|
784 | |||
785 | :: |
|
785 | :: | |
786 |
|
786 | |||
787 | In [1]: type('hello')\\ |
|
787 | In [1]: type('hello')\\ | |
788 | Out[1]: <type 'str'> |
|
788 | Out[1]: <type 'str'> | |
789 |
|
789 | |||
790 | indicates that the type name for strings is 'str'. |
|
790 | indicates that the type name for strings is 'str'. | |
791 |
|
791 | |||
792 | ``%who`` always excludes executed names loaded through your configuration |
|
792 | ``%who`` always excludes executed names loaded through your configuration | |
793 | file and things which are internal to IPython. |
|
793 | file and things which are internal to IPython. | |
794 |
|
794 | |||
795 | This is deliberate, as typically you may load many modules and the |
|
795 | This is deliberate, as typically you may load many modules and the | |
796 | purpose of %who is to show you only what you've manually defined. |
|
796 | purpose of %who is to show you only what you've manually defined. | |
797 |
|
797 | |||
798 | Examples |
|
798 | Examples | |
799 | -------- |
|
799 | -------- | |
800 |
|
800 | |||
801 | Define two variables and list them with who:: |
|
801 | Define two variables and list them with who:: | |
802 |
|
802 | |||
803 | In [1]: alpha = 123 |
|
803 | In [1]: alpha = 123 | |
804 |
|
804 | |||
805 | In [2]: beta = 'test' |
|
805 | In [2]: beta = 'test' | |
806 |
|
806 | |||
807 | In [3]: %who |
|
807 | In [3]: %who | |
808 | alpha beta |
|
808 | alpha beta | |
809 |
|
809 | |||
810 | In [4]: %who int |
|
810 | In [4]: %who int | |
811 | alpha |
|
811 | alpha | |
812 |
|
812 | |||
813 | In [5]: %who str |
|
813 | In [5]: %who str | |
814 | beta |
|
814 | beta | |
815 | """ |
|
815 | """ | |
816 |
|
816 | |||
817 | varlist = self.magic_who_ls(parameter_s) |
|
817 | varlist = self.magic_who_ls(parameter_s) | |
818 | if not varlist: |
|
818 | if not varlist: | |
819 | if parameter_s: |
|
819 | if parameter_s: | |
820 | print 'No variables match your requested type.' |
|
820 | print 'No variables match your requested type.' | |
821 | else: |
|
821 | else: | |
822 | print 'Interactive namespace is empty.' |
|
822 | print 'Interactive namespace is empty.' | |
823 | return |
|
823 | return | |
824 |
|
824 | |||
825 | # if we have variables, move on... |
|
825 | # if we have variables, move on... | |
826 | count = 0 |
|
826 | count = 0 | |
827 | for i in varlist: |
|
827 | for i in varlist: | |
828 | print i+'\t', |
|
828 | print i+'\t', | |
829 | count += 1 |
|
829 | count += 1 | |
830 | if count > 8: |
|
830 | if count > 8: | |
831 | count = 0 |
|
831 | count = 0 | |
832 |
|
832 | |||
833 |
|
833 | |||
834 |
|
834 | |||
835 | @skip_doctest |
|
835 | @skip_doctest | |
836 | def magic_whos(self, parameter_s=''): |
|
836 | def magic_whos(self, parameter_s=''): | |
837 | """Like %who, but gives some extra information about each variable. |
|
837 | """Like %who, but gives some extra information about each variable. | |
838 |
|
838 | |||
839 | The same type filtering of %who can be applied here. |
|
839 | The same type filtering of %who can be applied here. | |
840 |
|
840 | |||
841 | For all variables, the type is printed. Additionally it prints: |
|
841 | For all variables, the type is printed. Additionally it prints: | |
842 |
|
842 | |||
843 | - For {},[],(): their length. |
|
843 | - For {},[],(): their length. | |
844 |
|
844 | |||
845 | - For numpy arrays, a summary with shape, number of |
|
845 | - For numpy arrays, a summary with shape, number of | |
846 | elements, typecode and size in memory. |
|
846 | elements, typecode and size in memory. | |
847 |
|
847 | |||
848 | - Everything else: a string representation, snipping their middle if |
|
848 | - Everything else: a string representation, snipping their middle if | |
849 | too long. |
|
849 | too long. | |
850 |
|
850 | |||
851 | Examples |
|
851 | Examples | |
852 | -------- |
|
852 | -------- | |
853 |
|
853 | |||
854 | Define two variables and list them with whos:: |
|
854 | Define two variables and list them with whos:: | |
855 |
|
855 | |||
856 | In [1]: alpha = 123 |
|
856 | In [1]: alpha = 123 | |
857 |
|
857 | |||
858 | In [2]: beta = 'test' |
|
858 | In [2]: beta = 'test' | |
859 |
|
859 | |||
860 | In [3]: %whos |
|
860 | In [3]: %whos | |
861 | Variable Type Data/Info |
|
861 | Variable Type Data/Info | |
862 | -------------------------------- |
|
862 | -------------------------------- | |
863 | alpha int 123 |
|
863 | alpha int 123 | |
864 | beta str test |
|
864 | beta str test | |
865 | """ |
|
865 | """ | |
866 |
|
866 | |||
867 | varnames = self.magic_who_ls(parameter_s) |
|
867 | varnames = self.magic_who_ls(parameter_s) | |
868 | if not varnames: |
|
868 | if not varnames: | |
869 | if parameter_s: |
|
869 | if parameter_s: | |
870 | print 'No variables match your requested type.' |
|
870 | print 'No variables match your requested type.' | |
871 | else: |
|
871 | else: | |
872 | print 'Interactive namespace is empty.' |
|
872 | print 'Interactive namespace is empty.' | |
873 | return |
|
873 | return | |
874 |
|
874 | |||
875 | # if we have variables, move on... |
|
875 | # if we have variables, move on... | |
876 |
|
876 | |||
877 | # for these types, show len() instead of data: |
|
877 | # for these types, show len() instead of data: | |
878 | seq_types = ['dict', 'list', 'tuple'] |
|
878 | seq_types = ['dict', 'list', 'tuple'] | |
879 |
|
879 | |||
880 | # for numpy arrays, display summary info |
|
880 | # for numpy arrays, display summary info | |
881 | ndarray_type = None |
|
881 | ndarray_type = None | |
882 | if 'numpy' in sys.modules: |
|
882 | if 'numpy' in sys.modules: | |
883 | try: |
|
883 | try: | |
884 | from numpy import ndarray |
|
884 | from numpy import ndarray | |
885 | except ImportError: |
|
885 | except ImportError: | |
886 | pass |
|
886 | pass | |
887 | else: |
|
887 | else: | |
888 | ndarray_type = ndarray.__name__ |
|
888 | ndarray_type = ndarray.__name__ | |
889 |
|
889 | |||
890 | # Find all variable names and types so we can figure out column sizes |
|
890 | # Find all variable names and types so we can figure out column sizes | |
891 | def get_vars(i): |
|
891 | def get_vars(i): | |
892 | return self.shell.user_ns[i] |
|
892 | return self.shell.user_ns[i] | |
893 |
|
893 | |||
894 | # some types are well known and can be shorter |
|
894 | # some types are well known and can be shorter | |
895 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
895 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} | |
896 | def type_name(v): |
|
896 | def type_name(v): | |
897 | tn = type(v).__name__ |
|
897 | tn = type(v).__name__ | |
898 | return abbrevs.get(tn,tn) |
|
898 | return abbrevs.get(tn,tn) | |
899 |
|
899 | |||
900 | varlist = map(get_vars,varnames) |
|
900 | varlist = map(get_vars,varnames) | |
901 |
|
901 | |||
902 | typelist = [] |
|
902 | typelist = [] | |
903 | for vv in varlist: |
|
903 | for vv in varlist: | |
904 | tt = type_name(vv) |
|
904 | tt = type_name(vv) | |
905 |
|
905 | |||
906 | if tt=='instance': |
|
906 | if tt=='instance': | |
907 | typelist.append( abbrevs.get(str(vv.__class__), |
|
907 | typelist.append( abbrevs.get(str(vv.__class__), | |
908 | str(vv.__class__))) |
|
908 | str(vv.__class__))) | |
909 | else: |
|
909 | else: | |
910 | typelist.append(tt) |
|
910 | typelist.append(tt) | |
911 |
|
911 | |||
912 | # column labels and # of spaces as separator |
|
912 | # column labels and # of spaces as separator | |
913 | varlabel = 'Variable' |
|
913 | varlabel = 'Variable' | |
914 | typelabel = 'Type' |
|
914 | typelabel = 'Type' | |
915 | datalabel = 'Data/Info' |
|
915 | datalabel = 'Data/Info' | |
916 | colsep = 3 |
|
916 | colsep = 3 | |
917 | # variable format strings |
|
917 | # variable format strings | |
918 | vformat = "{0:<{varwidth}}{1:<{typewidth}}" |
|
918 | vformat = "{0:<{varwidth}}{1:<{typewidth}}" | |
919 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
919 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
920 | # find the size of the columns to format the output nicely |
|
920 | # find the size of the columns to format the output nicely | |
921 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
921 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
922 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
922 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
923 | # table header |
|
923 | # table header | |
924 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
924 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
925 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
925 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
926 | # and the table itself |
|
926 | # and the table itself | |
927 | kb = 1024 |
|
927 | kb = 1024 | |
928 | Mb = 1048576 # kb**2 |
|
928 | Mb = 1048576 # kb**2 | |
929 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
929 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
930 | print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), |
|
930 | print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), | |
931 | if vtype in seq_types: |
|
931 | if vtype in seq_types: | |
932 | print "n="+str(len(var)) |
|
932 | print "n="+str(len(var)) | |
933 | elif vtype == ndarray_type: |
|
933 | elif vtype == ndarray_type: | |
934 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
934 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
935 | if vtype==ndarray_type: |
|
935 | if vtype==ndarray_type: | |
936 | # numpy |
|
936 | # numpy | |
937 | vsize = var.size |
|
937 | vsize = var.size | |
938 | vbytes = vsize*var.itemsize |
|
938 | vbytes = vsize*var.itemsize | |
939 | vdtype = var.dtype |
|
939 | vdtype = var.dtype | |
940 |
|
940 | |||
941 | if vbytes < 100000: |
|
941 | if vbytes < 100000: | |
942 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
942 | print aformat % (vshape,vsize,vdtype,vbytes) | |
943 | else: |
|
943 | else: | |
944 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
944 | print aformat % (vshape,vsize,vdtype,vbytes), | |
945 | if vbytes < Mb: |
|
945 | if vbytes < Mb: | |
946 | print '(%s kb)' % (vbytes/kb,) |
|
946 | print '(%s kb)' % (vbytes/kb,) | |
947 | else: |
|
947 | else: | |
948 | print '(%s Mb)' % (vbytes/Mb,) |
|
948 | print '(%s Mb)' % (vbytes/Mb,) | |
949 | else: |
|
949 | else: | |
950 | try: |
|
950 | try: | |
951 | vstr = str(var) |
|
951 | vstr = str(var) | |
952 | except UnicodeEncodeError: |
|
952 | except UnicodeEncodeError: | |
953 |
vstr = unicode(var).encode( |
|
953 | vstr = unicode(var).encode(DEFAULT_ENCODING, | |
954 | 'backslashreplace') |
|
954 | 'backslashreplace') | |
955 | vstr = vstr.replace('\n','\\n') |
|
955 | vstr = vstr.replace('\n','\\n') | |
956 | if len(vstr) < 50: |
|
956 | if len(vstr) < 50: | |
957 | print vstr |
|
957 | print vstr | |
958 | else: |
|
958 | else: | |
959 | print vstr[:25] + "<...>" + vstr[-25:] |
|
959 | print vstr[:25] + "<...>" + vstr[-25:] | |
960 |
|
960 | |||
961 | def magic_reset(self, parameter_s=''): |
|
961 | def magic_reset(self, parameter_s=''): | |
962 | """Resets the namespace by removing all names defined by the user, if |
|
962 | """Resets the namespace by removing all names defined by the user, if | |
963 | called without arguments, or by removing some types of objects, such |
|
963 | called without arguments, or by removing some types of objects, such | |
964 | as everything currently in IPython's In[] and Out[] containers (see |
|
964 | as everything currently in IPython's In[] and Out[] containers (see | |
965 | the parameters for details). |
|
965 | the parameters for details). | |
966 |
|
966 | |||
967 | Parameters |
|
967 | Parameters | |
968 | ---------- |
|
968 | ---------- | |
969 | -f : force reset without asking for confirmation. |
|
969 | -f : force reset without asking for confirmation. | |
970 |
|
970 | |||
971 | -s : 'Soft' reset: Only clears your namespace, leaving history intact. |
|
971 | -s : 'Soft' reset: Only clears your namespace, leaving history intact. | |
972 | References to objects may be kept. By default (without this option), |
|
972 | References to objects may be kept. By default (without this option), | |
973 | we do a 'hard' reset, giving you a new session and removing all |
|
973 | we do a 'hard' reset, giving you a new session and removing all | |
974 | references to objects from the current session. |
|
974 | references to objects from the current session. | |
975 |
|
975 | |||
976 | in : reset input history |
|
976 | in : reset input history | |
977 |
|
977 | |||
978 | out : reset output history |
|
978 | out : reset output history | |
979 |
|
979 | |||
980 | dhist : reset directory history |
|
980 | dhist : reset directory history | |
981 |
|
981 | |||
982 | array : reset only variables that are NumPy arrays |
|
982 | array : reset only variables that are NumPy arrays | |
983 |
|
983 | |||
984 | See Also |
|
984 | See Also | |
985 | -------- |
|
985 | -------- | |
986 | magic_reset_selective : invoked as ``%reset_selective`` |
|
986 | magic_reset_selective : invoked as ``%reset_selective`` | |
987 |
|
987 | |||
988 | Examples |
|
988 | Examples | |
989 | -------- |
|
989 | -------- | |
990 | :: |
|
990 | :: | |
991 |
|
991 | |||
992 | In [6]: a = 1 |
|
992 | In [6]: a = 1 | |
993 |
|
993 | |||
994 | In [7]: a |
|
994 | In [7]: a | |
995 | Out[7]: 1 |
|
995 | Out[7]: 1 | |
996 |
|
996 | |||
997 | In [8]: 'a' in _ip.user_ns |
|
997 | In [8]: 'a' in _ip.user_ns | |
998 | Out[8]: True |
|
998 | Out[8]: True | |
999 |
|
999 | |||
1000 | In [9]: %reset -f |
|
1000 | In [9]: %reset -f | |
1001 |
|
1001 | |||
1002 | In [1]: 'a' in _ip.user_ns |
|
1002 | In [1]: 'a' in _ip.user_ns | |
1003 | Out[1]: False |
|
1003 | Out[1]: False | |
1004 |
|
1004 | |||
1005 | In [2]: %reset -f in |
|
1005 | In [2]: %reset -f in | |
1006 | Flushing input history |
|
1006 | Flushing input history | |
1007 |
|
1007 | |||
1008 | In [3]: %reset -f dhist in |
|
1008 | In [3]: %reset -f dhist in | |
1009 | Flushing directory history |
|
1009 | Flushing directory history | |
1010 | Flushing input history |
|
1010 | Flushing input history | |
1011 |
|
1011 | |||
1012 | Notes |
|
1012 | Notes | |
1013 | ----- |
|
1013 | ----- | |
1014 | Calling this magic from clients that do not implement standard input, |
|
1014 | Calling this magic from clients that do not implement standard input, | |
1015 | such as the ipython notebook interface, will reset the namespace |
|
1015 | such as the ipython notebook interface, will reset the namespace | |
1016 | without confirmation. |
|
1016 | without confirmation. | |
1017 | """ |
|
1017 | """ | |
1018 | opts, args = self.parse_options(parameter_s,'sf', mode='list') |
|
1018 | opts, args = self.parse_options(parameter_s,'sf', mode='list') | |
1019 | if 'f' in opts: |
|
1019 | if 'f' in opts: | |
1020 | ans = True |
|
1020 | ans = True | |
1021 | else: |
|
1021 | else: | |
1022 | try: |
|
1022 | try: | |
1023 | ans = self.shell.ask_yes_no( |
|
1023 | ans = self.shell.ask_yes_no( | |
1024 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", default='n') |
|
1024 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", default='n') | |
1025 | except StdinNotImplementedError: |
|
1025 | except StdinNotImplementedError: | |
1026 | ans = True |
|
1026 | ans = True | |
1027 | if not ans: |
|
1027 | if not ans: | |
1028 | print 'Nothing done.' |
|
1028 | print 'Nothing done.' | |
1029 | return |
|
1029 | return | |
1030 |
|
1030 | |||
1031 | if 's' in opts: # Soft reset |
|
1031 | if 's' in opts: # Soft reset | |
1032 | user_ns = self.shell.user_ns |
|
1032 | user_ns = self.shell.user_ns | |
1033 | for i in self.magic_who_ls(): |
|
1033 | for i in self.magic_who_ls(): | |
1034 | del(user_ns[i]) |
|
1034 | del(user_ns[i]) | |
1035 | elif len(args) == 0: # Hard reset |
|
1035 | elif len(args) == 0: # Hard reset | |
1036 | self.shell.reset(new_session = False) |
|
1036 | self.shell.reset(new_session = False) | |
1037 |
|
1037 | |||
1038 | # reset in/out/dhist/array: previously extensinions/clearcmd.py |
|
1038 | # reset in/out/dhist/array: previously extensinions/clearcmd.py | |
1039 | ip = self.shell |
|
1039 | ip = self.shell | |
1040 | user_ns = self.user_ns # local lookup, heavily used |
|
1040 | user_ns = self.user_ns # local lookup, heavily used | |
1041 |
|
1041 | |||
1042 | for target in args: |
|
1042 | for target in args: | |
1043 | target = target.lower() # make matches case insensitive |
|
1043 | target = target.lower() # make matches case insensitive | |
1044 | if target == 'out': |
|
1044 | if target == 'out': | |
1045 | print "Flushing output cache (%d entries)" % len(user_ns['_oh']) |
|
1045 | print "Flushing output cache (%d entries)" % len(user_ns['_oh']) | |
1046 | self.displayhook.flush() |
|
1046 | self.displayhook.flush() | |
1047 |
|
1047 | |||
1048 | elif target == 'in': |
|
1048 | elif target == 'in': | |
1049 | print "Flushing input history" |
|
1049 | print "Flushing input history" | |
1050 | pc = self.displayhook.prompt_count + 1 |
|
1050 | pc = self.displayhook.prompt_count + 1 | |
1051 | for n in range(1, pc): |
|
1051 | for n in range(1, pc): | |
1052 | key = '_i'+repr(n) |
|
1052 | key = '_i'+repr(n) | |
1053 | user_ns.pop(key,None) |
|
1053 | user_ns.pop(key,None) | |
1054 | user_ns.update(dict(_i=u'',_ii=u'',_iii=u'')) |
|
1054 | user_ns.update(dict(_i=u'',_ii=u'',_iii=u'')) | |
1055 | hm = ip.history_manager |
|
1055 | hm = ip.history_manager | |
1056 | # don't delete these, as %save and %macro depending on the length |
|
1056 | # don't delete these, as %save and %macro depending on the length | |
1057 | # of these lists to be preserved |
|
1057 | # of these lists to be preserved | |
1058 | hm.input_hist_parsed[:] = [''] * pc |
|
1058 | hm.input_hist_parsed[:] = [''] * pc | |
1059 | hm.input_hist_raw[:] = [''] * pc |
|
1059 | hm.input_hist_raw[:] = [''] * pc | |
1060 | # hm has internal machinery for _i,_ii,_iii, clear it out |
|
1060 | # hm has internal machinery for _i,_ii,_iii, clear it out | |
1061 | hm._i = hm._ii = hm._iii = hm._i00 = u'' |
|
1061 | hm._i = hm._ii = hm._iii = hm._i00 = u'' | |
1062 |
|
1062 | |||
1063 | elif target == 'array': |
|
1063 | elif target == 'array': | |
1064 | # Support cleaning up numpy arrays |
|
1064 | # Support cleaning up numpy arrays | |
1065 | try: |
|
1065 | try: | |
1066 | from numpy import ndarray |
|
1066 | from numpy import ndarray | |
1067 | # This must be done with items and not iteritems because we're |
|
1067 | # This must be done with items and not iteritems because we're | |
1068 | # going to modify the dict in-place. |
|
1068 | # going to modify the dict in-place. | |
1069 | for x,val in user_ns.items(): |
|
1069 | for x,val in user_ns.items(): | |
1070 | if isinstance(val,ndarray): |
|
1070 | if isinstance(val,ndarray): | |
1071 | del user_ns[x] |
|
1071 | del user_ns[x] | |
1072 | except ImportError: |
|
1072 | except ImportError: | |
1073 | print "reset array only works if Numpy is available." |
|
1073 | print "reset array only works if Numpy is available." | |
1074 |
|
1074 | |||
1075 | elif target == 'dhist': |
|
1075 | elif target == 'dhist': | |
1076 | print "Flushing directory history" |
|
1076 | print "Flushing directory history" | |
1077 | del user_ns['_dh'][:] |
|
1077 | del user_ns['_dh'][:] | |
1078 |
|
1078 | |||
1079 | else: |
|
1079 | else: | |
1080 | print "Don't know how to reset ", |
|
1080 | print "Don't know how to reset ", | |
1081 | print target + ", please run `%reset?` for details" |
|
1081 | print target + ", please run `%reset?` for details" | |
1082 |
|
1082 | |||
1083 | gc.collect() |
|
1083 | gc.collect() | |
1084 |
|
1084 | |||
1085 | def magic_reset_selective(self, parameter_s=''): |
|
1085 | def magic_reset_selective(self, parameter_s=''): | |
1086 | """Resets the namespace by removing names defined by the user. |
|
1086 | """Resets the namespace by removing names defined by the user. | |
1087 |
|
1087 | |||
1088 | Input/Output history are left around in case you need them. |
|
1088 | Input/Output history are left around in case you need them. | |
1089 |
|
1089 | |||
1090 | %reset_selective [-f] regex |
|
1090 | %reset_selective [-f] regex | |
1091 |
|
1091 | |||
1092 | No action is taken if regex is not included |
|
1092 | No action is taken if regex is not included | |
1093 |
|
1093 | |||
1094 | Options |
|
1094 | Options | |
1095 | -f : force reset without asking for confirmation. |
|
1095 | -f : force reset without asking for confirmation. | |
1096 |
|
1096 | |||
1097 | See Also |
|
1097 | See Also | |
1098 | -------- |
|
1098 | -------- | |
1099 | magic_reset : invoked as ``%reset`` |
|
1099 | magic_reset : invoked as ``%reset`` | |
1100 |
|
1100 | |||
1101 | Examples |
|
1101 | Examples | |
1102 | -------- |
|
1102 | -------- | |
1103 |
|
1103 | |||
1104 | We first fully reset the namespace so your output looks identical to |
|
1104 | We first fully reset the namespace so your output looks identical to | |
1105 | this example for pedagogical reasons; in practice you do not need a |
|
1105 | this example for pedagogical reasons; in practice you do not need a | |
1106 | full reset:: |
|
1106 | full reset:: | |
1107 |
|
1107 | |||
1108 | In [1]: %reset -f |
|
1108 | In [1]: %reset -f | |
1109 |
|
1109 | |||
1110 | Now, with a clean namespace we can make a few variables and use |
|
1110 | Now, with a clean namespace we can make a few variables and use | |
1111 | ``%reset_selective`` to only delete names that match our regexp:: |
|
1111 | ``%reset_selective`` to only delete names that match our regexp:: | |
1112 |
|
1112 | |||
1113 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 |
|
1113 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 | |
1114 |
|
1114 | |||
1115 | In [3]: who_ls |
|
1115 | In [3]: who_ls | |
1116 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] |
|
1116 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] | |
1117 |
|
1117 | |||
1118 | In [4]: %reset_selective -f b[2-3]m |
|
1118 | In [4]: %reset_selective -f b[2-3]m | |
1119 |
|
1119 | |||
1120 | In [5]: who_ls |
|
1120 | In [5]: who_ls | |
1121 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
1121 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
1122 |
|
1122 | |||
1123 | In [6]: %reset_selective -f d |
|
1123 | In [6]: %reset_selective -f d | |
1124 |
|
1124 | |||
1125 | In [7]: who_ls |
|
1125 | In [7]: who_ls | |
1126 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
1126 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
1127 |
|
1127 | |||
1128 | In [8]: %reset_selective -f c |
|
1128 | In [8]: %reset_selective -f c | |
1129 |
|
1129 | |||
1130 | In [9]: who_ls |
|
1130 | In [9]: who_ls | |
1131 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] |
|
1131 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] | |
1132 |
|
1132 | |||
1133 | In [10]: %reset_selective -f b |
|
1133 | In [10]: %reset_selective -f b | |
1134 |
|
1134 | |||
1135 | In [11]: who_ls |
|
1135 | In [11]: who_ls | |
1136 | Out[11]: ['a'] |
|
1136 | Out[11]: ['a'] | |
1137 |
|
1137 | |||
1138 | Notes |
|
1138 | Notes | |
1139 | ----- |
|
1139 | ----- | |
1140 | Calling this magic from clients that do not implement standard input, |
|
1140 | Calling this magic from clients that do not implement standard input, | |
1141 | such as the ipython notebook interface, will reset the namespace |
|
1141 | such as the ipython notebook interface, will reset the namespace | |
1142 | without confirmation. |
|
1142 | without confirmation. | |
1143 | """ |
|
1143 | """ | |
1144 |
|
1144 | |||
1145 | opts, regex = self.parse_options(parameter_s,'f') |
|
1145 | opts, regex = self.parse_options(parameter_s,'f') | |
1146 |
|
1146 | |||
1147 | if opts.has_key('f'): |
|
1147 | if opts.has_key('f'): | |
1148 | ans = True |
|
1148 | ans = True | |
1149 | else: |
|
1149 | else: | |
1150 | try: |
|
1150 | try: | |
1151 | ans = self.shell.ask_yes_no( |
|
1151 | ans = self.shell.ask_yes_no( | |
1152 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", |
|
1152 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", | |
1153 | default='n') |
|
1153 | default='n') | |
1154 | except StdinNotImplementedError: |
|
1154 | except StdinNotImplementedError: | |
1155 | ans = True |
|
1155 | ans = True | |
1156 | if not ans: |
|
1156 | if not ans: | |
1157 | print 'Nothing done.' |
|
1157 | print 'Nothing done.' | |
1158 | return |
|
1158 | return | |
1159 | user_ns = self.shell.user_ns |
|
1159 | user_ns = self.shell.user_ns | |
1160 | if not regex: |
|
1160 | if not regex: | |
1161 | print 'No regex pattern specified. Nothing done.' |
|
1161 | print 'No regex pattern specified. Nothing done.' | |
1162 | return |
|
1162 | return | |
1163 | else: |
|
1163 | else: | |
1164 | try: |
|
1164 | try: | |
1165 | m = re.compile(regex) |
|
1165 | m = re.compile(regex) | |
1166 | except TypeError: |
|
1166 | except TypeError: | |
1167 | raise TypeError('regex must be a string or compiled pattern') |
|
1167 | raise TypeError('regex must be a string or compiled pattern') | |
1168 | for i in self.magic_who_ls(): |
|
1168 | for i in self.magic_who_ls(): | |
1169 | if m.search(i): |
|
1169 | if m.search(i): | |
1170 | del(user_ns[i]) |
|
1170 | del(user_ns[i]) | |
1171 |
|
1171 | |||
1172 | def magic_xdel(self, parameter_s=''): |
|
1172 | def magic_xdel(self, parameter_s=''): | |
1173 | """Delete a variable, trying to clear it from anywhere that |
|
1173 | """Delete a variable, trying to clear it from anywhere that | |
1174 | IPython's machinery has references to it. By default, this uses |
|
1174 | IPython's machinery has references to it. By default, this uses | |
1175 | the identity of the named object in the user namespace to remove |
|
1175 | the identity of the named object in the user namespace to remove | |
1176 | references held under other names. The object is also removed |
|
1176 | references held under other names. The object is also removed | |
1177 | from the output history. |
|
1177 | from the output history. | |
1178 |
|
1178 | |||
1179 | Options |
|
1179 | Options | |
1180 | -n : Delete the specified name from all namespaces, without |
|
1180 | -n : Delete the specified name from all namespaces, without | |
1181 | checking their identity. |
|
1181 | checking their identity. | |
1182 | """ |
|
1182 | """ | |
1183 | opts, varname = self.parse_options(parameter_s,'n') |
|
1183 | opts, varname = self.parse_options(parameter_s,'n') | |
1184 | try: |
|
1184 | try: | |
1185 | self.shell.del_var(varname, ('n' in opts)) |
|
1185 | self.shell.del_var(varname, ('n' in opts)) | |
1186 | except (NameError, ValueError) as e: |
|
1186 | except (NameError, ValueError) as e: | |
1187 | print type(e).__name__ +": "+ str(e) |
|
1187 | print type(e).__name__ +": "+ str(e) | |
1188 |
|
1188 | |||
1189 | def magic_logstart(self,parameter_s=''): |
|
1189 | def magic_logstart(self,parameter_s=''): | |
1190 | """Start logging anywhere in a session. |
|
1190 | """Start logging anywhere in a session. | |
1191 |
|
1191 | |||
1192 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1192 | %logstart [-o|-r|-t] [log_name [log_mode]] | |
1193 |
|
1193 | |||
1194 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1194 | If no name is given, it defaults to a file named 'ipython_log.py' in your | |
1195 | current directory, in 'rotate' mode (see below). |
|
1195 | current directory, in 'rotate' mode (see below). | |
1196 |
|
1196 | |||
1197 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1197 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
1198 | history up to that point and then continues logging. |
|
1198 | history up to that point and then continues logging. | |
1199 |
|
1199 | |||
1200 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1200 | %logstart takes a second optional parameter: logging mode. This can be one | |
1201 | of (note that the modes are given unquoted):\\ |
|
1201 | of (note that the modes are given unquoted):\\ | |
1202 | append: well, that says it.\\ |
|
1202 | append: well, that says it.\\ | |
1203 | backup: rename (if exists) to name~ and start name.\\ |
|
1203 | backup: rename (if exists) to name~ and start name.\\ | |
1204 | global: single logfile in your home dir, appended to.\\ |
|
1204 | global: single logfile in your home dir, appended to.\\ | |
1205 | over : overwrite existing log.\\ |
|
1205 | over : overwrite existing log.\\ | |
1206 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1206 | rotate: create rotating logs name.1~, name.2~, etc. | |
1207 |
|
1207 | |||
1208 | Options: |
|
1208 | Options: | |
1209 |
|
1209 | |||
1210 | -o: log also IPython's output. In this mode, all commands which |
|
1210 | -o: log also IPython's output. In this mode, all commands which | |
1211 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1211 | generate an Out[NN] prompt are recorded to the logfile, right after | |
1212 | their corresponding input line. The output lines are always |
|
1212 | their corresponding input line. The output lines are always | |
1213 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1213 | prepended with a '#[Out]# ' marker, so that the log remains valid | |
1214 | Python code. |
|
1214 | Python code. | |
1215 |
|
1215 | |||
1216 | Since this marker is always the same, filtering only the output from |
|
1216 | Since this marker is always the same, filtering only the output from | |
1217 | a log is very easy, using for example a simple awk call:: |
|
1217 | a log is very easy, using for example a simple awk call:: | |
1218 |
|
1218 | |||
1219 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1219 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py | |
1220 |
|
1220 | |||
1221 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1221 | -r: log 'raw' input. Normally, IPython's logs contain the processed | |
1222 | input, so that user lines are logged in their final form, converted |
|
1222 | input, so that user lines are logged in their final form, converted | |
1223 | into valid Python. For example, %Exit is logged as |
|
1223 | into valid Python. For example, %Exit is logged as | |
1224 | _ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1224 | _ip.magic("Exit"). If the -r flag is given, all input is logged | |
1225 | exactly as typed, with no transformations applied. |
|
1225 | exactly as typed, with no transformations applied. | |
1226 |
|
1226 | |||
1227 | -t: put timestamps before each input line logged (these are put in |
|
1227 | -t: put timestamps before each input line logged (these are put in | |
1228 | comments).""" |
|
1228 | comments).""" | |
1229 |
|
1229 | |||
1230 | opts,par = self.parse_options(parameter_s,'ort') |
|
1230 | opts,par = self.parse_options(parameter_s,'ort') | |
1231 | log_output = 'o' in opts |
|
1231 | log_output = 'o' in opts | |
1232 | log_raw_input = 'r' in opts |
|
1232 | log_raw_input = 'r' in opts | |
1233 | timestamp = 't' in opts |
|
1233 | timestamp = 't' in opts | |
1234 |
|
1234 | |||
1235 | logger = self.shell.logger |
|
1235 | logger = self.shell.logger | |
1236 |
|
1236 | |||
1237 | # if no args are given, the defaults set in the logger constructor by |
|
1237 | # if no args are given, the defaults set in the logger constructor by | |
1238 | # ipython remain valid |
|
1238 | # ipython remain valid | |
1239 | if par: |
|
1239 | if par: | |
1240 | try: |
|
1240 | try: | |
1241 | logfname,logmode = par.split() |
|
1241 | logfname,logmode = par.split() | |
1242 | except: |
|
1242 | except: | |
1243 | logfname = par |
|
1243 | logfname = par | |
1244 | logmode = 'backup' |
|
1244 | logmode = 'backup' | |
1245 | else: |
|
1245 | else: | |
1246 | logfname = logger.logfname |
|
1246 | logfname = logger.logfname | |
1247 | logmode = logger.logmode |
|
1247 | logmode = logger.logmode | |
1248 | # put logfname into rc struct as if it had been called on the command |
|
1248 | # put logfname into rc struct as if it had been called on the command | |
1249 | # line, so it ends up saved in the log header Save it in case we need |
|
1249 | # line, so it ends up saved in the log header Save it in case we need | |
1250 | # to restore it... |
|
1250 | # to restore it... | |
1251 | old_logfile = self.shell.logfile |
|
1251 | old_logfile = self.shell.logfile | |
1252 | if logfname: |
|
1252 | if logfname: | |
1253 | logfname = os.path.expanduser(logfname) |
|
1253 | logfname = os.path.expanduser(logfname) | |
1254 | self.shell.logfile = logfname |
|
1254 | self.shell.logfile = logfname | |
1255 |
|
1255 | |||
1256 | loghead = '# IPython log file\n\n' |
|
1256 | loghead = '# IPython log file\n\n' | |
1257 | try: |
|
1257 | try: | |
1258 | started = logger.logstart(logfname,loghead,logmode, |
|
1258 | started = logger.logstart(logfname,loghead,logmode, | |
1259 | log_output,timestamp,log_raw_input) |
|
1259 | log_output,timestamp,log_raw_input) | |
1260 | except: |
|
1260 | except: | |
1261 | self.shell.logfile = old_logfile |
|
1261 | self.shell.logfile = old_logfile | |
1262 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1262 | warn("Couldn't start log: %s" % sys.exc_info()[1]) | |
1263 | else: |
|
1263 | else: | |
1264 | # log input history up to this point, optionally interleaving |
|
1264 | # log input history up to this point, optionally interleaving | |
1265 | # output if requested |
|
1265 | # output if requested | |
1266 |
|
1266 | |||
1267 | if timestamp: |
|
1267 | if timestamp: | |
1268 | # disable timestamping for the previous history, since we've |
|
1268 | # disable timestamping for the previous history, since we've | |
1269 | # lost those already (no time machine here). |
|
1269 | # lost those already (no time machine here). | |
1270 | logger.timestamp = False |
|
1270 | logger.timestamp = False | |
1271 |
|
1271 | |||
1272 | if log_raw_input: |
|
1272 | if log_raw_input: | |
1273 | input_hist = self.shell.history_manager.input_hist_raw |
|
1273 | input_hist = self.shell.history_manager.input_hist_raw | |
1274 | else: |
|
1274 | else: | |
1275 | input_hist = self.shell.history_manager.input_hist_parsed |
|
1275 | input_hist = self.shell.history_manager.input_hist_parsed | |
1276 |
|
1276 | |||
1277 | if log_output: |
|
1277 | if log_output: | |
1278 | log_write = logger.log_write |
|
1278 | log_write = logger.log_write | |
1279 | output_hist = self.shell.history_manager.output_hist |
|
1279 | output_hist = self.shell.history_manager.output_hist | |
1280 | for n in range(1,len(input_hist)-1): |
|
1280 | for n in range(1,len(input_hist)-1): | |
1281 | log_write(input_hist[n].rstrip() + '\n') |
|
1281 | log_write(input_hist[n].rstrip() + '\n') | |
1282 | if n in output_hist: |
|
1282 | if n in output_hist: | |
1283 | log_write(repr(output_hist[n]),'output') |
|
1283 | log_write(repr(output_hist[n]),'output') | |
1284 | else: |
|
1284 | else: | |
1285 | logger.log_write('\n'.join(input_hist[1:])) |
|
1285 | logger.log_write('\n'.join(input_hist[1:])) | |
1286 | logger.log_write('\n') |
|
1286 | logger.log_write('\n') | |
1287 | if timestamp: |
|
1287 | if timestamp: | |
1288 | # re-enable timestamping |
|
1288 | # re-enable timestamping | |
1289 | logger.timestamp = True |
|
1289 | logger.timestamp = True | |
1290 |
|
1290 | |||
1291 | print ('Activating auto-logging. ' |
|
1291 | print ('Activating auto-logging. ' | |
1292 | 'Current session state plus future input saved.') |
|
1292 | 'Current session state plus future input saved.') | |
1293 | logger.logstate() |
|
1293 | logger.logstate() | |
1294 |
|
1294 | |||
1295 | def magic_logstop(self,parameter_s=''): |
|
1295 | def magic_logstop(self,parameter_s=''): | |
1296 | """Fully stop logging and close log file. |
|
1296 | """Fully stop logging and close log file. | |
1297 |
|
1297 | |||
1298 | In order to start logging again, a new %logstart call needs to be made, |
|
1298 | In order to start logging again, a new %logstart call needs to be made, | |
1299 | possibly (though not necessarily) with a new filename, mode and other |
|
1299 | possibly (though not necessarily) with a new filename, mode and other | |
1300 | options.""" |
|
1300 | options.""" | |
1301 | self.logger.logstop() |
|
1301 | self.logger.logstop() | |
1302 |
|
1302 | |||
1303 | def magic_logoff(self,parameter_s=''): |
|
1303 | def magic_logoff(self,parameter_s=''): | |
1304 | """Temporarily stop logging. |
|
1304 | """Temporarily stop logging. | |
1305 |
|
1305 | |||
1306 | You must have previously started logging.""" |
|
1306 | You must have previously started logging.""" | |
1307 | self.shell.logger.switch_log(0) |
|
1307 | self.shell.logger.switch_log(0) | |
1308 |
|
1308 | |||
1309 | def magic_logon(self,parameter_s=''): |
|
1309 | def magic_logon(self,parameter_s=''): | |
1310 | """Restart logging. |
|
1310 | """Restart logging. | |
1311 |
|
1311 | |||
1312 | This function is for restarting logging which you've temporarily |
|
1312 | This function is for restarting logging which you've temporarily | |
1313 | stopped with %logoff. For starting logging for the first time, you |
|
1313 | stopped with %logoff. For starting logging for the first time, you | |
1314 | must use the %logstart function, which allows you to specify an |
|
1314 | must use the %logstart function, which allows you to specify an | |
1315 | optional log filename.""" |
|
1315 | optional log filename.""" | |
1316 |
|
1316 | |||
1317 | self.shell.logger.switch_log(1) |
|
1317 | self.shell.logger.switch_log(1) | |
1318 |
|
1318 | |||
1319 | def magic_logstate(self,parameter_s=''): |
|
1319 | def magic_logstate(self,parameter_s=''): | |
1320 | """Print the status of the logging system.""" |
|
1320 | """Print the status of the logging system.""" | |
1321 |
|
1321 | |||
1322 | self.shell.logger.logstate() |
|
1322 | self.shell.logger.logstate() | |
1323 |
|
1323 | |||
1324 | def magic_pdb(self, parameter_s=''): |
|
1324 | def magic_pdb(self, parameter_s=''): | |
1325 | """Control the automatic calling of the pdb interactive debugger. |
|
1325 | """Control the automatic calling of the pdb interactive debugger. | |
1326 |
|
1326 | |||
1327 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1327 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
1328 | argument it works as a toggle. |
|
1328 | argument it works as a toggle. | |
1329 |
|
1329 | |||
1330 | When an exception is triggered, IPython can optionally call the |
|
1330 | When an exception is triggered, IPython can optionally call the | |
1331 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1331 | interactive pdb debugger after the traceback printout. %pdb toggles | |
1332 | this feature on and off. |
|
1332 | this feature on and off. | |
1333 |
|
1333 | |||
1334 | The initial state of this feature is set in your configuration |
|
1334 | The initial state of this feature is set in your configuration | |
1335 | file (the option is ``InteractiveShell.pdb``). |
|
1335 | file (the option is ``InteractiveShell.pdb``). | |
1336 |
|
1336 | |||
1337 | If you want to just activate the debugger AFTER an exception has fired, |
|
1337 | If you want to just activate the debugger AFTER an exception has fired, | |
1338 | without having to type '%pdb on' and rerunning your code, you can use |
|
1338 | without having to type '%pdb on' and rerunning your code, you can use | |
1339 | the %debug magic.""" |
|
1339 | the %debug magic.""" | |
1340 |
|
1340 | |||
1341 | par = parameter_s.strip().lower() |
|
1341 | par = parameter_s.strip().lower() | |
1342 |
|
1342 | |||
1343 | if par: |
|
1343 | if par: | |
1344 | try: |
|
1344 | try: | |
1345 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1345 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
1346 | except KeyError: |
|
1346 | except KeyError: | |
1347 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1347 | print ('Incorrect argument. Use on/1, off/0, ' | |
1348 | 'or nothing for a toggle.') |
|
1348 | 'or nothing for a toggle.') | |
1349 | return |
|
1349 | return | |
1350 | else: |
|
1350 | else: | |
1351 | # toggle |
|
1351 | # toggle | |
1352 | new_pdb = not self.shell.call_pdb |
|
1352 | new_pdb = not self.shell.call_pdb | |
1353 |
|
1353 | |||
1354 | # set on the shell |
|
1354 | # set on the shell | |
1355 | self.shell.call_pdb = new_pdb |
|
1355 | self.shell.call_pdb = new_pdb | |
1356 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1356 | print 'Automatic pdb calling has been turned',on_off(new_pdb) | |
1357 |
|
1357 | |||
1358 | def magic_debug(self, parameter_s=''): |
|
1358 | def magic_debug(self, parameter_s=''): | |
1359 | """Activate the interactive debugger in post-mortem mode. |
|
1359 | """Activate the interactive debugger in post-mortem mode. | |
1360 |
|
1360 | |||
1361 | If an exception has just occurred, this lets you inspect its stack |
|
1361 | If an exception has just occurred, this lets you inspect its stack | |
1362 | frames interactively. Note that this will always work only on the last |
|
1362 | frames interactively. Note that this will always work only on the last | |
1363 | traceback that occurred, so you must call this quickly after an |
|
1363 | traceback that occurred, so you must call this quickly after an | |
1364 | exception that you wish to inspect has fired, because if another one |
|
1364 | exception that you wish to inspect has fired, because if another one | |
1365 | occurs, it clobbers the previous one. |
|
1365 | occurs, it clobbers the previous one. | |
1366 |
|
1366 | |||
1367 | If you want IPython to automatically do this on every exception, see |
|
1367 | If you want IPython to automatically do this on every exception, see | |
1368 | the %pdb magic for more details. |
|
1368 | the %pdb magic for more details. | |
1369 | """ |
|
1369 | """ | |
1370 | self.shell.debugger(force=True) |
|
1370 | self.shell.debugger(force=True) | |
1371 |
|
1371 | |||
1372 | @skip_doctest |
|
1372 | @skip_doctest | |
1373 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1373 | def magic_prun(self, parameter_s ='',user_mode=1, | |
1374 | opts=None,arg_lst=None,prog_ns=None): |
|
1374 | opts=None,arg_lst=None,prog_ns=None): | |
1375 |
|
1375 | |||
1376 | """Run a statement through the python code profiler. |
|
1376 | """Run a statement through the python code profiler. | |
1377 |
|
1377 | |||
1378 | Usage: |
|
1378 | Usage: | |
1379 | %prun [options] statement |
|
1379 | %prun [options] statement | |
1380 |
|
1380 | |||
1381 | The given statement (which doesn't require quote marks) is run via the |
|
1381 | The given statement (which doesn't require quote marks) is run via the | |
1382 | python profiler in a manner similar to the profile.run() function. |
|
1382 | python profiler in a manner similar to the profile.run() function. | |
1383 | Namespaces are internally managed to work correctly; profile.run |
|
1383 | Namespaces are internally managed to work correctly; profile.run | |
1384 | cannot be used in IPython because it makes certain assumptions about |
|
1384 | cannot be used in IPython because it makes certain assumptions about | |
1385 | namespaces which do not hold under IPython. |
|
1385 | namespaces which do not hold under IPython. | |
1386 |
|
1386 | |||
1387 | Options: |
|
1387 | Options: | |
1388 |
|
1388 | |||
1389 | -l <limit>: you can place restrictions on what or how much of the |
|
1389 | -l <limit>: you can place restrictions on what or how much of the | |
1390 | profile gets printed. The limit value can be: |
|
1390 | profile gets printed. The limit value can be: | |
1391 |
|
1391 | |||
1392 | * A string: only information for function names containing this string |
|
1392 | * A string: only information for function names containing this string | |
1393 | is printed. |
|
1393 | is printed. | |
1394 |
|
1394 | |||
1395 | * An integer: only these many lines are printed. |
|
1395 | * An integer: only these many lines are printed. | |
1396 |
|
1396 | |||
1397 | * A float (between 0 and 1): this fraction of the report is printed |
|
1397 | * A float (between 0 and 1): this fraction of the report is printed | |
1398 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1398 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
1399 |
|
1399 | |||
1400 | You can combine several limits with repeated use of the option. For |
|
1400 | You can combine several limits with repeated use of the option. For | |
1401 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1401 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
1402 | information about class constructors. |
|
1402 | information about class constructors. | |
1403 |
|
1403 | |||
1404 | -r: return the pstats.Stats object generated by the profiling. This |
|
1404 | -r: return the pstats.Stats object generated by the profiling. This | |
1405 | object has all the information about the profile in it, and you can |
|
1405 | object has all the information about the profile in it, and you can | |
1406 | later use it for further analysis or in other functions. |
|
1406 | later use it for further analysis or in other functions. | |
1407 |
|
1407 | |||
1408 | -s <key>: sort profile by given key. You can provide more than one key |
|
1408 | -s <key>: sort profile by given key. You can provide more than one key | |
1409 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1409 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1410 | default sorting key is 'time'. |
|
1410 | default sorting key is 'time'. | |
1411 |
|
1411 | |||
1412 | The following is copied verbatim from the profile documentation |
|
1412 | The following is copied verbatim from the profile documentation | |
1413 | referenced below: |
|
1413 | referenced below: | |
1414 |
|
1414 | |||
1415 | When more than one key is provided, additional keys are used as |
|
1415 | When more than one key is provided, additional keys are used as | |
1416 | secondary criteria when the there is equality in all keys selected |
|
1416 | secondary criteria when the there is equality in all keys selected | |
1417 | before them. |
|
1417 | before them. | |
1418 |
|
1418 | |||
1419 | Abbreviations can be used for any key names, as long as the |
|
1419 | Abbreviations can be used for any key names, as long as the | |
1420 | abbreviation is unambiguous. The following are the keys currently |
|
1420 | abbreviation is unambiguous. The following are the keys currently | |
1421 | defined: |
|
1421 | defined: | |
1422 |
|
1422 | |||
1423 | Valid Arg Meaning |
|
1423 | Valid Arg Meaning | |
1424 | "calls" call count |
|
1424 | "calls" call count | |
1425 | "cumulative" cumulative time |
|
1425 | "cumulative" cumulative time | |
1426 | "file" file name |
|
1426 | "file" file name | |
1427 | "module" file name |
|
1427 | "module" file name | |
1428 | "pcalls" primitive call count |
|
1428 | "pcalls" primitive call count | |
1429 | "line" line number |
|
1429 | "line" line number | |
1430 | "name" function name |
|
1430 | "name" function name | |
1431 | "nfl" name/file/line |
|
1431 | "nfl" name/file/line | |
1432 | "stdname" standard name |
|
1432 | "stdname" standard name | |
1433 | "time" internal time |
|
1433 | "time" internal time | |
1434 |
|
1434 | |||
1435 | Note that all sorts on statistics are in descending order (placing |
|
1435 | Note that all sorts on statistics are in descending order (placing | |
1436 | most time consuming items first), where as name, file, and line number |
|
1436 | most time consuming items first), where as name, file, and line number | |
1437 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1437 | searches are in ascending order (i.e., alphabetical). The subtle | |
1438 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1438 | distinction between "nfl" and "stdname" is that the standard name is a | |
1439 | sort of the name as printed, which means that the embedded line |
|
1439 | sort of the name as printed, which means that the embedded line | |
1440 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1440 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1441 | would (if the file names were the same) appear in the string order |
|
1441 | would (if the file names were the same) appear in the string order | |
1442 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1442 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1443 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1443 | line numbers. In fact, sort_stats("nfl") is the same as | |
1444 | sort_stats("name", "file", "line"). |
|
1444 | sort_stats("name", "file", "line"). | |
1445 |
|
1445 | |||
1446 | -T <filename>: save profile results as shown on screen to a text |
|
1446 | -T <filename>: save profile results as shown on screen to a text | |
1447 | file. The profile is still shown on screen. |
|
1447 | file. The profile is still shown on screen. | |
1448 |
|
1448 | |||
1449 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1449 | -D <filename>: save (via dump_stats) profile statistics to given | |
1450 | filename. This data is in a format understood by the pstats module, and |
|
1450 | filename. This data is in a format understood by the pstats module, and | |
1451 | is generated by a call to the dump_stats() method of profile |
|
1451 | is generated by a call to the dump_stats() method of profile | |
1452 | objects. The profile is still shown on screen. |
|
1452 | objects. The profile is still shown on screen. | |
1453 |
|
1453 | |||
1454 | -q: suppress output to the pager. Best used with -T and/or -D above. |
|
1454 | -q: suppress output to the pager. Best used with -T and/or -D above. | |
1455 |
|
1455 | |||
1456 | If you want to run complete programs under the profiler's control, use |
|
1456 | If you want to run complete programs under the profiler's control, use | |
1457 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1457 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1458 | contains profiler specific options as described here. |
|
1458 | contains profiler specific options as described here. | |
1459 |
|
1459 | |||
1460 | You can read the complete documentation for the profile module with:: |
|
1460 | You can read the complete documentation for the profile module with:: | |
1461 |
|
1461 | |||
1462 | In [1]: import profile; profile.help() |
|
1462 | In [1]: import profile; profile.help() | |
1463 | """ |
|
1463 | """ | |
1464 |
|
1464 | |||
1465 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1465 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1466 |
|
1466 | |||
1467 | if user_mode: # regular user call |
|
1467 | if user_mode: # regular user call | |
1468 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q', |
|
1468 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q', | |
1469 | list_all=1, posix=False) |
|
1469 | list_all=1, posix=False) | |
1470 | namespace = self.shell.user_ns |
|
1470 | namespace = self.shell.user_ns | |
1471 | else: # called to run a program by %run -p |
|
1471 | else: # called to run a program by %run -p | |
1472 | try: |
|
1472 | try: | |
1473 | filename = get_py_filename(arg_lst[0]) |
|
1473 | filename = get_py_filename(arg_lst[0]) | |
1474 | except IOError as e: |
|
1474 | except IOError as e: | |
1475 | try: |
|
1475 | try: | |
1476 | msg = str(e) |
|
1476 | msg = str(e) | |
1477 | except UnicodeError: |
|
1477 | except UnicodeError: | |
1478 | msg = e.message |
|
1478 | msg = e.message | |
1479 | error(msg) |
|
1479 | error(msg) | |
1480 | return |
|
1480 | return | |
1481 |
|
1481 | |||
1482 | arg_str = 'execfile(filename,prog_ns)' |
|
1482 | arg_str = 'execfile(filename,prog_ns)' | |
1483 | namespace = { |
|
1483 | namespace = { | |
1484 | 'execfile': self.shell.safe_execfile, |
|
1484 | 'execfile': self.shell.safe_execfile, | |
1485 | 'prog_ns': prog_ns, |
|
1485 | 'prog_ns': prog_ns, | |
1486 | 'filename': filename |
|
1486 | 'filename': filename | |
1487 | } |
|
1487 | } | |
1488 |
|
1488 | |||
1489 | opts.merge(opts_def) |
|
1489 | opts.merge(opts_def) | |
1490 |
|
1490 | |||
1491 | prof = profile.Profile() |
|
1491 | prof = profile.Profile() | |
1492 | try: |
|
1492 | try: | |
1493 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1493 | prof = prof.runctx(arg_str,namespace,namespace) | |
1494 | sys_exit = '' |
|
1494 | sys_exit = '' | |
1495 | except SystemExit: |
|
1495 | except SystemExit: | |
1496 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1496 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1497 |
|
1497 | |||
1498 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1498 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1499 |
|
1499 | |||
1500 | lims = opts.l |
|
1500 | lims = opts.l | |
1501 | if lims: |
|
1501 | if lims: | |
1502 | lims = [] # rebuild lims with ints/floats/strings |
|
1502 | lims = [] # rebuild lims with ints/floats/strings | |
1503 | for lim in opts.l: |
|
1503 | for lim in opts.l: | |
1504 | try: |
|
1504 | try: | |
1505 | lims.append(int(lim)) |
|
1505 | lims.append(int(lim)) | |
1506 | except ValueError: |
|
1506 | except ValueError: | |
1507 | try: |
|
1507 | try: | |
1508 | lims.append(float(lim)) |
|
1508 | lims.append(float(lim)) | |
1509 | except ValueError: |
|
1509 | except ValueError: | |
1510 | lims.append(lim) |
|
1510 | lims.append(lim) | |
1511 |
|
1511 | |||
1512 | # Trap output. |
|
1512 | # Trap output. | |
1513 | stdout_trap = StringIO() |
|
1513 | stdout_trap = StringIO() | |
1514 |
|
1514 | |||
1515 | if hasattr(stats,'stream'): |
|
1515 | if hasattr(stats,'stream'): | |
1516 | # In newer versions of python, the stats object has a 'stream' |
|
1516 | # In newer versions of python, the stats object has a 'stream' | |
1517 | # attribute to write into. |
|
1517 | # attribute to write into. | |
1518 | stats.stream = stdout_trap |
|
1518 | stats.stream = stdout_trap | |
1519 | stats.print_stats(*lims) |
|
1519 | stats.print_stats(*lims) | |
1520 | else: |
|
1520 | else: | |
1521 | # For older versions, we manually redirect stdout during printing |
|
1521 | # For older versions, we manually redirect stdout during printing | |
1522 | sys_stdout = sys.stdout |
|
1522 | sys_stdout = sys.stdout | |
1523 | try: |
|
1523 | try: | |
1524 | sys.stdout = stdout_trap |
|
1524 | sys.stdout = stdout_trap | |
1525 | stats.print_stats(*lims) |
|
1525 | stats.print_stats(*lims) | |
1526 | finally: |
|
1526 | finally: | |
1527 | sys.stdout = sys_stdout |
|
1527 | sys.stdout = sys_stdout | |
1528 |
|
1528 | |||
1529 | output = stdout_trap.getvalue() |
|
1529 | output = stdout_trap.getvalue() | |
1530 | output = output.rstrip() |
|
1530 | output = output.rstrip() | |
1531 |
|
1531 | |||
1532 | if 'q' not in opts: |
|
1532 | if 'q' not in opts: | |
1533 | page.page(output) |
|
1533 | page.page(output) | |
1534 | print sys_exit, |
|
1534 | print sys_exit, | |
1535 |
|
1535 | |||
1536 | dump_file = opts.D[0] |
|
1536 | dump_file = opts.D[0] | |
1537 | text_file = opts.T[0] |
|
1537 | text_file = opts.T[0] | |
1538 | if dump_file: |
|
1538 | if dump_file: | |
1539 | dump_file = unquote_filename(dump_file) |
|
1539 | dump_file = unquote_filename(dump_file) | |
1540 | prof.dump_stats(dump_file) |
|
1540 | prof.dump_stats(dump_file) | |
1541 | print '\n*** Profile stats marshalled to file',\ |
|
1541 | print '\n*** Profile stats marshalled to file',\ | |
1542 | `dump_file`+'.',sys_exit |
|
1542 | `dump_file`+'.',sys_exit | |
1543 | if text_file: |
|
1543 | if text_file: | |
1544 | text_file = unquote_filename(text_file) |
|
1544 | text_file = unquote_filename(text_file) | |
1545 | pfile = open(text_file,'w') |
|
1545 | pfile = open(text_file,'w') | |
1546 | pfile.write(output) |
|
1546 | pfile.write(output) | |
1547 | pfile.close() |
|
1547 | pfile.close() | |
1548 | print '\n*** Profile printout saved to text file',\ |
|
1548 | print '\n*** Profile printout saved to text file',\ | |
1549 | `text_file`+'.',sys_exit |
|
1549 | `text_file`+'.',sys_exit | |
1550 |
|
1550 | |||
1551 | if opts.has_key('r'): |
|
1551 | if opts.has_key('r'): | |
1552 | return stats |
|
1552 | return stats | |
1553 | else: |
|
1553 | else: | |
1554 | return None |
|
1554 | return None | |
1555 |
|
1555 | |||
1556 | @skip_doctest |
|
1556 | @skip_doctest | |
1557 | def magic_run(self, parameter_s ='', runner=None, |
|
1557 | def magic_run(self, parameter_s ='', runner=None, | |
1558 | file_finder=get_py_filename): |
|
1558 | file_finder=get_py_filename): | |
1559 | """Run the named file inside IPython as a program. |
|
1559 | """Run the named file inside IPython as a program. | |
1560 |
|
1560 | |||
1561 | Usage:\\ |
|
1561 | Usage:\\ | |
1562 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1562 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
1563 |
|
1563 | |||
1564 | Parameters after the filename are passed as command-line arguments to |
|
1564 | Parameters after the filename are passed as command-line arguments to | |
1565 | the program (put in sys.argv). Then, control returns to IPython's |
|
1565 | the program (put in sys.argv). Then, control returns to IPython's | |
1566 | prompt. |
|
1566 | prompt. | |
1567 |
|
1567 | |||
1568 | This is similar to running at a system prompt:\\ |
|
1568 | This is similar to running at a system prompt:\\ | |
1569 | $ python file args\\ |
|
1569 | $ python file args\\ | |
1570 | but with the advantage of giving you IPython's tracebacks, and of |
|
1570 | but with the advantage of giving you IPython's tracebacks, and of | |
1571 | loading all variables into your interactive namespace for further use |
|
1571 | loading all variables into your interactive namespace for further use | |
1572 | (unless -p is used, see below). |
|
1572 | (unless -p is used, see below). | |
1573 |
|
1573 | |||
1574 | The file is executed in a namespace initially consisting only of |
|
1574 | The file is executed in a namespace initially consisting only of | |
1575 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1575 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
1576 | sees its environment as if it were being run as a stand-alone program |
|
1576 | sees its environment as if it were being run as a stand-alone program | |
1577 | (except for sharing global objects such as previously imported |
|
1577 | (except for sharing global objects such as previously imported | |
1578 | modules). But after execution, the IPython interactive namespace gets |
|
1578 | modules). But after execution, the IPython interactive namespace gets | |
1579 | updated with all variables defined in the program (except for __name__ |
|
1579 | updated with all variables defined in the program (except for __name__ | |
1580 | and sys.argv). This allows for very convenient loading of code for |
|
1580 | and sys.argv). This allows for very convenient loading of code for | |
1581 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1581 | interactive work, while giving each program a 'clean sheet' to run in. | |
1582 |
|
1582 | |||
1583 | Options: |
|
1583 | Options: | |
1584 |
|
1584 | |||
1585 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1585 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
1586 | without extension (as python does under import). This allows running |
|
1586 | without extension (as python does under import). This allows running | |
1587 | scripts and reloading the definitions in them without calling code |
|
1587 | scripts and reloading the definitions in them without calling code | |
1588 | protected by an ' if __name__ == "__main__" ' clause. |
|
1588 | protected by an ' if __name__ == "__main__" ' clause. | |
1589 |
|
1589 | |||
1590 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1590 | -i: run the file in IPython's namespace instead of an empty one. This | |
1591 | is useful if you are experimenting with code written in a text editor |
|
1591 | is useful if you are experimenting with code written in a text editor | |
1592 | which depends on variables defined interactively. |
|
1592 | which depends on variables defined interactively. | |
1593 |
|
1593 | |||
1594 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1594 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
1595 | being run. This is particularly useful if IPython is being used to |
|
1595 | being run. This is particularly useful if IPython is being used to | |
1596 | run unittests, which always exit with a sys.exit() call. In such |
|
1596 | run unittests, which always exit with a sys.exit() call. In such | |
1597 | cases you are interested in the output of the test results, not in |
|
1597 | cases you are interested in the output of the test results, not in | |
1598 | seeing a traceback of the unittest module. |
|
1598 | seeing a traceback of the unittest module. | |
1599 |
|
1599 | |||
1600 | -t: print timing information at the end of the run. IPython will give |
|
1600 | -t: print timing information at the end of the run. IPython will give | |
1601 | you an estimated CPU time consumption for your script, which under |
|
1601 | you an estimated CPU time consumption for your script, which under | |
1602 | Unix uses the resource module to avoid the wraparound problems of |
|
1602 | Unix uses the resource module to avoid the wraparound problems of | |
1603 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1603 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
1604 | is also given (for Windows platforms this is reported as 0.0). |
|
1604 | is also given (for Windows platforms this is reported as 0.0). | |
1605 |
|
1605 | |||
1606 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1606 | If -t is given, an additional -N<N> option can be given, where <N> | |
1607 | must be an integer indicating how many times you want the script to |
|
1607 | must be an integer indicating how many times you want the script to | |
1608 | run. The final timing report will include total and per run results. |
|
1608 | run. The final timing report will include total and per run results. | |
1609 |
|
1609 | |||
1610 | For example (testing the script uniq_stable.py):: |
|
1610 | For example (testing the script uniq_stable.py):: | |
1611 |
|
1611 | |||
1612 | In [1]: run -t uniq_stable |
|
1612 | In [1]: run -t uniq_stable | |
1613 |
|
1613 | |||
1614 | IPython CPU timings (estimated):\\ |
|
1614 | IPython CPU timings (estimated):\\ | |
1615 | User : 0.19597 s.\\ |
|
1615 | User : 0.19597 s.\\ | |
1616 | System: 0.0 s.\\ |
|
1616 | System: 0.0 s.\\ | |
1617 |
|
1617 | |||
1618 | In [2]: run -t -N5 uniq_stable |
|
1618 | In [2]: run -t -N5 uniq_stable | |
1619 |
|
1619 | |||
1620 | IPython CPU timings (estimated):\\ |
|
1620 | IPython CPU timings (estimated):\\ | |
1621 | Total runs performed: 5\\ |
|
1621 | Total runs performed: 5\\ | |
1622 | Times : Total Per run\\ |
|
1622 | Times : Total Per run\\ | |
1623 | User : 0.910862 s, 0.1821724 s.\\ |
|
1623 | User : 0.910862 s, 0.1821724 s.\\ | |
1624 | System: 0.0 s, 0.0 s. |
|
1624 | System: 0.0 s, 0.0 s. | |
1625 |
|
1625 | |||
1626 | -d: run your program under the control of pdb, the Python debugger. |
|
1626 | -d: run your program under the control of pdb, the Python debugger. | |
1627 | This allows you to execute your program step by step, watch variables, |
|
1627 | This allows you to execute your program step by step, watch variables, | |
1628 | etc. Internally, what IPython does is similar to calling: |
|
1628 | etc. Internally, what IPython does is similar to calling: | |
1629 |
|
1629 | |||
1630 | pdb.run('execfile("YOURFILENAME")') |
|
1630 | pdb.run('execfile("YOURFILENAME")') | |
1631 |
|
1631 | |||
1632 | with a breakpoint set on line 1 of your file. You can change the line |
|
1632 | with a breakpoint set on line 1 of your file. You can change the line | |
1633 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1633 | number for this automatic breakpoint to be <N> by using the -bN option | |
1634 | (where N must be an integer). For example:: |
|
1634 | (where N must be an integer). For example:: | |
1635 |
|
1635 | |||
1636 | %run -d -b40 myscript |
|
1636 | %run -d -b40 myscript | |
1637 |
|
1637 | |||
1638 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1638 | will set the first breakpoint at line 40 in myscript.py. Note that | |
1639 | the first breakpoint must be set on a line which actually does |
|
1639 | the first breakpoint must be set on a line which actually does | |
1640 | something (not a comment or docstring) for it to stop execution. |
|
1640 | something (not a comment or docstring) for it to stop execution. | |
1641 |
|
1641 | |||
1642 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1642 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
1643 | first enter 'c' (without quotes) to start execution up to the first |
|
1643 | first enter 'c' (without quotes) to start execution up to the first | |
1644 | breakpoint. |
|
1644 | breakpoint. | |
1645 |
|
1645 | |||
1646 | Entering 'help' gives information about the use of the debugger. You |
|
1646 | Entering 'help' gives information about the use of the debugger. You | |
1647 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1647 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
1648 | at a prompt. |
|
1648 | at a prompt. | |
1649 |
|
1649 | |||
1650 | -p: run program under the control of the Python profiler module (which |
|
1650 | -p: run program under the control of the Python profiler module (which | |
1651 | prints a detailed report of execution times, function calls, etc). |
|
1651 | prints a detailed report of execution times, function calls, etc). | |
1652 |
|
1652 | |||
1653 | You can pass other options after -p which affect the behavior of the |
|
1653 | You can pass other options after -p which affect the behavior of the | |
1654 | profiler itself. See the docs for %prun for details. |
|
1654 | profiler itself. See the docs for %prun for details. | |
1655 |
|
1655 | |||
1656 | In this mode, the program's variables do NOT propagate back to the |
|
1656 | In this mode, the program's variables do NOT propagate back to the | |
1657 | IPython interactive namespace (because they remain in the namespace |
|
1657 | IPython interactive namespace (because they remain in the namespace | |
1658 | where the profiler executes them). |
|
1658 | where the profiler executes them). | |
1659 |
|
1659 | |||
1660 | Internally this triggers a call to %prun, see its documentation for |
|
1660 | Internally this triggers a call to %prun, see its documentation for | |
1661 | details on the options available specifically for profiling. |
|
1661 | details on the options available specifically for profiling. | |
1662 |
|
1662 | |||
1663 | There is one special usage for which the text above doesn't apply: |
|
1663 | There is one special usage for which the text above doesn't apply: | |
1664 | if the filename ends with .ipy, the file is run as ipython script, |
|
1664 | if the filename ends with .ipy, the file is run as ipython script, | |
1665 | just as if the commands were written on IPython prompt. |
|
1665 | just as if the commands were written on IPython prompt. | |
1666 |
|
1666 | |||
1667 | -m: specify module name to load instead of script path. Similar to |
|
1667 | -m: specify module name to load instead of script path. Similar to | |
1668 | the -m option for the python interpreter. Use this option last if you |
|
1668 | the -m option for the python interpreter. Use this option last if you | |
1669 | want to combine with other %run options. Unlike the python interpreter |
|
1669 | want to combine with other %run options. Unlike the python interpreter | |
1670 | only source modules are allowed no .pyc or .pyo files. |
|
1670 | only source modules are allowed no .pyc or .pyo files. | |
1671 | For example:: |
|
1671 | For example:: | |
1672 |
|
1672 | |||
1673 | %run -m example |
|
1673 | %run -m example | |
1674 |
|
1674 | |||
1675 | will run the example module. |
|
1675 | will run the example module. | |
1676 |
|
1676 | |||
1677 | """ |
|
1677 | """ | |
1678 |
|
1678 | |||
1679 | # get arguments and set sys.argv for program to be run. |
|
1679 | # get arguments and set sys.argv for program to be run. | |
1680 | opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:', |
|
1680 | opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:', | |
1681 | mode='list', list_all=1) |
|
1681 | mode='list', list_all=1) | |
1682 | if "m" in opts: |
|
1682 | if "m" in opts: | |
1683 | modulename = opts["m"][0] |
|
1683 | modulename = opts["m"][0] | |
1684 | modpath = find_mod(modulename) |
|
1684 | modpath = find_mod(modulename) | |
1685 | if modpath is None: |
|
1685 | if modpath is None: | |
1686 | warn('%r is not a valid modulename on sys.path'%modulename) |
|
1686 | warn('%r is not a valid modulename on sys.path'%modulename) | |
1687 | return |
|
1687 | return | |
1688 | arg_lst = [modpath] + arg_lst |
|
1688 | arg_lst = [modpath] + arg_lst | |
1689 | try: |
|
1689 | try: | |
1690 | filename = file_finder(arg_lst[0]) |
|
1690 | filename = file_finder(arg_lst[0]) | |
1691 | except IndexError: |
|
1691 | except IndexError: | |
1692 | warn('you must provide at least a filename.') |
|
1692 | warn('you must provide at least a filename.') | |
1693 | print '\n%run:\n', oinspect.getdoc(self.magic_run) |
|
1693 | print '\n%run:\n', oinspect.getdoc(self.magic_run) | |
1694 | return |
|
1694 | return | |
1695 | except IOError as e: |
|
1695 | except IOError as e: | |
1696 | try: |
|
1696 | try: | |
1697 | msg = str(e) |
|
1697 | msg = str(e) | |
1698 | except UnicodeError: |
|
1698 | except UnicodeError: | |
1699 | msg = e.message |
|
1699 | msg = e.message | |
1700 | error(msg) |
|
1700 | error(msg) | |
1701 | return |
|
1701 | return | |
1702 |
|
1702 | |||
1703 | if filename.lower().endswith('.ipy'): |
|
1703 | if filename.lower().endswith('.ipy'): | |
1704 | self.shell.safe_execfile_ipy(filename) |
|
1704 | self.shell.safe_execfile_ipy(filename) | |
1705 | return |
|
1705 | return | |
1706 |
|
1706 | |||
1707 | # Control the response to exit() calls made by the script being run |
|
1707 | # Control the response to exit() calls made by the script being run | |
1708 | exit_ignore = 'e' in opts |
|
1708 | exit_ignore = 'e' in opts | |
1709 |
|
1709 | |||
1710 | # Make sure that the running script gets a proper sys.argv as if it |
|
1710 | # Make sure that the running script gets a proper sys.argv as if it | |
1711 | # were run from a system shell. |
|
1711 | # were run from a system shell. | |
1712 | save_argv = sys.argv # save it for later restoring |
|
1712 | save_argv = sys.argv # save it for later restoring | |
1713 |
|
1713 | |||
1714 | # simulate shell expansion on arguments, at least tilde expansion |
|
1714 | # simulate shell expansion on arguments, at least tilde expansion | |
1715 | args = [ os.path.expanduser(a) for a in arg_lst[1:] ] |
|
1715 | args = [ os.path.expanduser(a) for a in arg_lst[1:] ] | |
1716 |
|
1716 | |||
1717 | sys.argv = [filename] + args # put in the proper filename |
|
1717 | sys.argv = [filename] + args # put in the proper filename | |
1718 | # protect sys.argv from potential unicode strings on Python 2: |
|
1718 | # protect sys.argv from potential unicode strings on Python 2: | |
1719 | if not py3compat.PY3: |
|
1719 | if not py3compat.PY3: | |
1720 | sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ] |
|
1720 | sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ] | |
1721 |
|
1721 | |||
1722 | if 'i' in opts: |
|
1722 | if 'i' in opts: | |
1723 | # Run in user's interactive namespace |
|
1723 | # Run in user's interactive namespace | |
1724 | prog_ns = self.shell.user_ns |
|
1724 | prog_ns = self.shell.user_ns | |
1725 | __name__save = self.shell.user_ns['__name__'] |
|
1725 | __name__save = self.shell.user_ns['__name__'] | |
1726 | prog_ns['__name__'] = '__main__' |
|
1726 | prog_ns['__name__'] = '__main__' | |
1727 | main_mod = self.shell.new_main_mod(prog_ns) |
|
1727 | main_mod = self.shell.new_main_mod(prog_ns) | |
1728 | else: |
|
1728 | else: | |
1729 | # Run in a fresh, empty namespace |
|
1729 | # Run in a fresh, empty namespace | |
1730 | if 'n' in opts: |
|
1730 | if 'n' in opts: | |
1731 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1731 | name = os.path.splitext(os.path.basename(filename))[0] | |
1732 | else: |
|
1732 | else: | |
1733 | name = '__main__' |
|
1733 | name = '__main__' | |
1734 |
|
1734 | |||
1735 | main_mod = self.shell.new_main_mod() |
|
1735 | main_mod = self.shell.new_main_mod() | |
1736 | prog_ns = main_mod.__dict__ |
|
1736 | prog_ns = main_mod.__dict__ | |
1737 | prog_ns['__name__'] = name |
|
1737 | prog_ns['__name__'] = name | |
1738 |
|
1738 | |||
1739 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1739 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must | |
1740 | # set the __file__ global in the script's namespace |
|
1740 | # set the __file__ global in the script's namespace | |
1741 | prog_ns['__file__'] = filename |
|
1741 | prog_ns['__file__'] = filename | |
1742 |
|
1742 | |||
1743 | # pickle fix. See interactiveshell for an explanation. But we need to make sure |
|
1743 | # pickle fix. See interactiveshell for an explanation. But we need to make sure | |
1744 | # that, if we overwrite __main__, we replace it at the end |
|
1744 | # that, if we overwrite __main__, we replace it at the end | |
1745 | main_mod_name = prog_ns['__name__'] |
|
1745 | main_mod_name = prog_ns['__name__'] | |
1746 |
|
1746 | |||
1747 | if main_mod_name == '__main__': |
|
1747 | if main_mod_name == '__main__': | |
1748 | restore_main = sys.modules['__main__'] |
|
1748 | restore_main = sys.modules['__main__'] | |
1749 | else: |
|
1749 | else: | |
1750 | restore_main = False |
|
1750 | restore_main = False | |
1751 |
|
1751 | |||
1752 | # This needs to be undone at the end to prevent holding references to |
|
1752 | # This needs to be undone at the end to prevent holding references to | |
1753 | # every single object ever created. |
|
1753 | # every single object ever created. | |
1754 | sys.modules[main_mod_name] = main_mod |
|
1754 | sys.modules[main_mod_name] = main_mod | |
1755 |
|
1755 | |||
1756 | try: |
|
1756 | try: | |
1757 | stats = None |
|
1757 | stats = None | |
1758 | with self.readline_no_record: |
|
1758 | with self.readline_no_record: | |
1759 | if 'p' in opts: |
|
1759 | if 'p' in opts: | |
1760 | stats = self.magic_prun('', 0, opts, arg_lst, prog_ns) |
|
1760 | stats = self.magic_prun('', 0, opts, arg_lst, prog_ns) | |
1761 | else: |
|
1761 | else: | |
1762 | if 'd' in opts: |
|
1762 | if 'd' in opts: | |
1763 | deb = debugger.Pdb(self.shell.colors) |
|
1763 | deb = debugger.Pdb(self.shell.colors) | |
1764 | # reset Breakpoint state, which is moronically kept |
|
1764 | # reset Breakpoint state, which is moronically kept | |
1765 | # in a class |
|
1765 | # in a class | |
1766 | bdb.Breakpoint.next = 1 |
|
1766 | bdb.Breakpoint.next = 1 | |
1767 | bdb.Breakpoint.bplist = {} |
|
1767 | bdb.Breakpoint.bplist = {} | |
1768 | bdb.Breakpoint.bpbynumber = [None] |
|
1768 | bdb.Breakpoint.bpbynumber = [None] | |
1769 | # Set an initial breakpoint to stop execution |
|
1769 | # Set an initial breakpoint to stop execution | |
1770 | maxtries = 10 |
|
1770 | maxtries = 10 | |
1771 | bp = int(opts.get('b', [1])[0]) |
|
1771 | bp = int(opts.get('b', [1])[0]) | |
1772 | checkline = deb.checkline(filename, bp) |
|
1772 | checkline = deb.checkline(filename, bp) | |
1773 | if not checkline: |
|
1773 | if not checkline: | |
1774 | for bp in range(bp + 1, bp + maxtries + 1): |
|
1774 | for bp in range(bp + 1, bp + maxtries + 1): | |
1775 | if deb.checkline(filename, bp): |
|
1775 | if deb.checkline(filename, bp): | |
1776 | break |
|
1776 | break | |
1777 | else: |
|
1777 | else: | |
1778 | msg = ("\nI failed to find a valid line to set " |
|
1778 | msg = ("\nI failed to find a valid line to set " | |
1779 | "a breakpoint\n" |
|
1779 | "a breakpoint\n" | |
1780 | "after trying up to line: %s.\n" |
|
1780 | "after trying up to line: %s.\n" | |
1781 | "Please set a valid breakpoint manually " |
|
1781 | "Please set a valid breakpoint manually " | |
1782 | "with the -b option." % bp) |
|
1782 | "with the -b option." % bp) | |
1783 | error(msg) |
|
1783 | error(msg) | |
1784 | return |
|
1784 | return | |
1785 | # if we find a good linenumber, set the breakpoint |
|
1785 | # if we find a good linenumber, set the breakpoint | |
1786 | deb.do_break('%s:%s' % (filename, bp)) |
|
1786 | deb.do_break('%s:%s' % (filename, bp)) | |
1787 | # Start file run |
|
1787 | # Start file run | |
1788 | print "NOTE: Enter 'c' at the", |
|
1788 | print "NOTE: Enter 'c' at the", | |
1789 | print "%s prompt to start your script." % deb.prompt |
|
1789 | print "%s prompt to start your script." % deb.prompt | |
1790 | ns = {'execfile': py3compat.execfile, 'prog_ns': prog_ns} |
|
1790 | ns = {'execfile': py3compat.execfile, 'prog_ns': prog_ns} | |
1791 | try: |
|
1791 | try: | |
1792 | deb.run('execfile("%s", prog_ns)' % filename, ns) |
|
1792 | deb.run('execfile("%s", prog_ns)' % filename, ns) | |
1793 |
|
1793 | |||
1794 | except: |
|
1794 | except: | |
1795 | etype, value, tb = sys.exc_info() |
|
1795 | etype, value, tb = sys.exc_info() | |
1796 | # Skip three frames in the traceback: the %run one, |
|
1796 | # Skip three frames in the traceback: the %run one, | |
1797 | # one inside bdb.py, and the command-line typed by the |
|
1797 | # one inside bdb.py, and the command-line typed by the | |
1798 | # user (run by exec in pdb itself). |
|
1798 | # user (run by exec in pdb itself). | |
1799 | self.shell.InteractiveTB(etype, value, tb, tb_offset=3) |
|
1799 | self.shell.InteractiveTB(etype, value, tb, tb_offset=3) | |
1800 | else: |
|
1800 | else: | |
1801 | if runner is None: |
|
1801 | if runner is None: | |
1802 | runner = self.shell.safe_execfile |
|
1802 | runner = self.shell.safe_execfile | |
1803 | if 't' in opts: |
|
1803 | if 't' in opts: | |
1804 | # timed execution |
|
1804 | # timed execution | |
1805 | try: |
|
1805 | try: | |
1806 | nruns = int(opts['N'][0]) |
|
1806 | nruns = int(opts['N'][0]) | |
1807 | if nruns < 1: |
|
1807 | if nruns < 1: | |
1808 | error('Number of runs must be >=1') |
|
1808 | error('Number of runs must be >=1') | |
1809 | return |
|
1809 | return | |
1810 | except (KeyError): |
|
1810 | except (KeyError): | |
1811 | nruns = 1 |
|
1811 | nruns = 1 | |
1812 | twall0 = time.time() |
|
1812 | twall0 = time.time() | |
1813 | if nruns == 1: |
|
1813 | if nruns == 1: | |
1814 | t0 = clock2() |
|
1814 | t0 = clock2() | |
1815 | runner(filename, prog_ns, prog_ns, |
|
1815 | runner(filename, prog_ns, prog_ns, | |
1816 | exit_ignore=exit_ignore) |
|
1816 | exit_ignore=exit_ignore) | |
1817 | t1 = clock2() |
|
1817 | t1 = clock2() | |
1818 | t_usr = t1[0] - t0[0] |
|
1818 | t_usr = t1[0] - t0[0] | |
1819 | t_sys = t1[1] - t0[1] |
|
1819 | t_sys = t1[1] - t0[1] | |
1820 | print "\nIPython CPU timings (estimated):" |
|
1820 | print "\nIPython CPU timings (estimated):" | |
1821 | print " User : %10.2f s." % t_usr |
|
1821 | print " User : %10.2f s." % t_usr | |
1822 | print " System : %10.2f s." % t_sys |
|
1822 | print " System : %10.2f s." % t_sys | |
1823 | else: |
|
1823 | else: | |
1824 | runs = range(nruns) |
|
1824 | runs = range(nruns) | |
1825 | t0 = clock2() |
|
1825 | t0 = clock2() | |
1826 | for nr in runs: |
|
1826 | for nr in runs: | |
1827 | runner(filename, prog_ns, prog_ns, |
|
1827 | runner(filename, prog_ns, prog_ns, | |
1828 | exit_ignore=exit_ignore) |
|
1828 | exit_ignore=exit_ignore) | |
1829 | t1 = clock2() |
|
1829 | t1 = clock2() | |
1830 | t_usr = t1[0] - t0[0] |
|
1830 | t_usr = t1[0] - t0[0] | |
1831 | t_sys = t1[1] - t0[1] |
|
1831 | t_sys = t1[1] - t0[1] | |
1832 | print "\nIPython CPU timings (estimated):" |
|
1832 | print "\nIPython CPU timings (estimated):" | |
1833 | print "Total runs performed:", nruns |
|
1833 | print "Total runs performed:", nruns | |
1834 | print " Times : %10.2f %10.2f" % ('Total', 'Per run') |
|
1834 | print " Times : %10.2f %10.2f" % ('Total', 'Per run') | |
1835 | print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns) |
|
1835 | print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns) | |
1836 | print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns) |
|
1836 | print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns) | |
1837 | twall1 = time.time() |
|
1837 | twall1 = time.time() | |
1838 | print "Wall time: %10.2f s." % (twall1 - twall0) |
|
1838 | print "Wall time: %10.2f s." % (twall1 - twall0) | |
1839 |
|
1839 | |||
1840 | else: |
|
1840 | else: | |
1841 | # regular execution |
|
1841 | # regular execution | |
1842 | runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore) |
|
1842 | runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore) | |
1843 |
|
1843 | |||
1844 | if 'i' in opts: |
|
1844 | if 'i' in opts: | |
1845 | self.shell.user_ns['__name__'] = __name__save |
|
1845 | self.shell.user_ns['__name__'] = __name__save | |
1846 | else: |
|
1846 | else: | |
1847 | # The shell MUST hold a reference to prog_ns so after %run |
|
1847 | # The shell MUST hold a reference to prog_ns so after %run | |
1848 | # exits, the python deletion mechanism doesn't zero it out |
|
1848 | # exits, the python deletion mechanism doesn't zero it out | |
1849 | # (leaving dangling references). |
|
1849 | # (leaving dangling references). | |
1850 | self.shell.cache_main_mod(prog_ns, filename) |
|
1850 | self.shell.cache_main_mod(prog_ns, filename) | |
1851 | # update IPython interactive namespace |
|
1851 | # update IPython interactive namespace | |
1852 |
|
1852 | |||
1853 | # Some forms of read errors on the file may mean the |
|
1853 | # Some forms of read errors on the file may mean the | |
1854 | # __name__ key was never set; using pop we don't have to |
|
1854 | # __name__ key was never set; using pop we don't have to | |
1855 | # worry about a possible KeyError. |
|
1855 | # worry about a possible KeyError. | |
1856 | prog_ns.pop('__name__', None) |
|
1856 | prog_ns.pop('__name__', None) | |
1857 |
|
1857 | |||
1858 | self.shell.user_ns.update(prog_ns) |
|
1858 | self.shell.user_ns.update(prog_ns) | |
1859 | finally: |
|
1859 | finally: | |
1860 | # It's a bit of a mystery why, but __builtins__ can change from |
|
1860 | # It's a bit of a mystery why, but __builtins__ can change from | |
1861 | # being a module to becoming a dict missing some key data after |
|
1861 | # being a module to becoming a dict missing some key data after | |
1862 | # %run. As best I can see, this is NOT something IPython is doing |
|
1862 | # %run. As best I can see, this is NOT something IPython is doing | |
1863 | # at all, and similar problems have been reported before: |
|
1863 | # at all, and similar problems have been reported before: | |
1864 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
1864 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html | |
1865 | # Since this seems to be done by the interpreter itself, the best |
|
1865 | # Since this seems to be done by the interpreter itself, the best | |
1866 | # we can do is to at least restore __builtins__ for the user on |
|
1866 | # we can do is to at least restore __builtins__ for the user on | |
1867 | # exit. |
|
1867 | # exit. | |
1868 | self.shell.user_ns['__builtins__'] = builtin_mod |
|
1868 | self.shell.user_ns['__builtins__'] = builtin_mod | |
1869 |
|
1869 | |||
1870 | # Ensure key global structures are restored |
|
1870 | # Ensure key global structures are restored | |
1871 | sys.argv = save_argv |
|
1871 | sys.argv = save_argv | |
1872 | if restore_main: |
|
1872 | if restore_main: | |
1873 | sys.modules['__main__'] = restore_main |
|
1873 | sys.modules['__main__'] = restore_main | |
1874 | else: |
|
1874 | else: | |
1875 | # Remove from sys.modules the reference to main_mod we'd |
|
1875 | # Remove from sys.modules the reference to main_mod we'd | |
1876 | # added. Otherwise it will trap references to objects |
|
1876 | # added. Otherwise it will trap references to objects | |
1877 | # contained therein. |
|
1877 | # contained therein. | |
1878 | del sys.modules[main_mod_name] |
|
1878 | del sys.modules[main_mod_name] | |
1879 |
|
1879 | |||
1880 | return stats |
|
1880 | return stats | |
1881 |
|
1881 | |||
1882 | @skip_doctest |
|
1882 | @skip_doctest | |
1883 | def magic_timeit(self, parameter_s =''): |
|
1883 | def magic_timeit(self, parameter_s =''): | |
1884 | """Time execution of a Python statement or expression |
|
1884 | """Time execution of a Python statement or expression | |
1885 |
|
1885 | |||
1886 | Usage:\\ |
|
1886 | Usage:\\ | |
1887 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1887 | %timeit [-n<N> -r<R> [-t|-c]] statement | |
1888 |
|
1888 | |||
1889 | Time execution of a Python statement or expression using the timeit |
|
1889 | Time execution of a Python statement or expression using the timeit | |
1890 | module. |
|
1890 | module. | |
1891 |
|
1891 | |||
1892 | Options: |
|
1892 | Options: | |
1893 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1893 | -n<N>: execute the given statement <N> times in a loop. If this value | |
1894 | is not given, a fitting value is chosen. |
|
1894 | is not given, a fitting value is chosen. | |
1895 |
|
1895 | |||
1896 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1896 | -r<R>: repeat the loop iteration <R> times and take the best result. | |
1897 | Default: 3 |
|
1897 | Default: 3 | |
1898 |
|
1898 | |||
1899 | -t: use time.time to measure the time, which is the default on Unix. |
|
1899 | -t: use time.time to measure the time, which is the default on Unix. | |
1900 | This function measures wall time. |
|
1900 | This function measures wall time. | |
1901 |
|
1901 | |||
1902 | -c: use time.clock to measure the time, which is the default on |
|
1902 | -c: use time.clock to measure the time, which is the default on | |
1903 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1903 | Windows and measures wall time. On Unix, resource.getrusage is used | |
1904 | instead and returns the CPU user time. |
|
1904 | instead and returns the CPU user time. | |
1905 |
|
1905 | |||
1906 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1906 | -p<P>: use a precision of <P> digits to display the timing result. | |
1907 | Default: 3 |
|
1907 | Default: 3 | |
1908 |
|
1908 | |||
1909 |
|
1909 | |||
1910 | Examples |
|
1910 | Examples | |
1911 | -------- |
|
1911 | -------- | |
1912 | :: |
|
1912 | :: | |
1913 |
|
1913 | |||
1914 | In [1]: %timeit pass |
|
1914 | In [1]: %timeit pass | |
1915 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1915 | 10000000 loops, best of 3: 53.3 ns per loop | |
1916 |
|
1916 | |||
1917 | In [2]: u = None |
|
1917 | In [2]: u = None | |
1918 |
|
1918 | |||
1919 | In [3]: %timeit u is None |
|
1919 | In [3]: %timeit u is None | |
1920 | 10000000 loops, best of 3: 184 ns per loop |
|
1920 | 10000000 loops, best of 3: 184 ns per loop | |
1921 |
|
1921 | |||
1922 | In [4]: %timeit -r 4 u == None |
|
1922 | In [4]: %timeit -r 4 u == None | |
1923 | 1000000 loops, best of 4: 242 ns per loop |
|
1923 | 1000000 loops, best of 4: 242 ns per loop | |
1924 |
|
1924 | |||
1925 | In [5]: import time |
|
1925 | In [5]: import time | |
1926 |
|
1926 | |||
1927 | In [6]: %timeit -n1 time.sleep(2) |
|
1927 | In [6]: %timeit -n1 time.sleep(2) | |
1928 | 1 loops, best of 3: 2 s per loop |
|
1928 | 1 loops, best of 3: 2 s per loop | |
1929 |
|
1929 | |||
1930 |
|
1930 | |||
1931 | The times reported by %timeit will be slightly higher than those |
|
1931 | The times reported by %timeit will be slightly higher than those | |
1932 | reported by the timeit.py script when variables are accessed. This is |
|
1932 | reported by the timeit.py script when variables are accessed. This is | |
1933 | due to the fact that %timeit executes the statement in the namespace |
|
1933 | due to the fact that %timeit executes the statement in the namespace | |
1934 | of the shell, compared with timeit.py, which uses a single setup |
|
1934 | of the shell, compared with timeit.py, which uses a single setup | |
1935 | statement to import function or create variables. Generally, the bias |
|
1935 | statement to import function or create variables. Generally, the bias | |
1936 | does not matter as long as results from timeit.py are not mixed with |
|
1936 | does not matter as long as results from timeit.py are not mixed with | |
1937 | those from %timeit.""" |
|
1937 | those from %timeit.""" | |
1938 |
|
1938 | |||
1939 | import timeit |
|
1939 | import timeit | |
1940 | import math |
|
1940 | import math | |
1941 |
|
1941 | |||
1942 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in |
|
1942 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in | |
1943 | # certain terminals. Until we figure out a robust way of |
|
1943 | # certain terminals. Until we figure out a robust way of | |
1944 | # auto-detecting if the terminal can deal with it, use plain 'us' for |
|
1944 | # auto-detecting if the terminal can deal with it, use plain 'us' for | |
1945 | # microseconds. I am really NOT happy about disabling the proper |
|
1945 | # microseconds. I am really NOT happy about disabling the proper | |
1946 | # 'micro' prefix, but crashing is worse... If anyone knows what the |
|
1946 | # 'micro' prefix, but crashing is worse... If anyone knows what the | |
1947 | # right solution for this is, I'm all ears... |
|
1947 | # right solution for this is, I'm all ears... | |
1948 | # |
|
1948 | # | |
1949 | # Note: using |
|
1949 | # Note: using | |
1950 | # |
|
1950 | # | |
1951 | # s = u'\xb5' |
|
1951 | # s = u'\xb5' | |
1952 | # s.encode(sys.getdefaultencoding()) |
|
1952 | # s.encode(sys.getdefaultencoding()) | |
1953 | # |
|
1953 | # | |
1954 | # is not sufficient, as I've seen terminals where that fails but |
|
1954 | # is not sufficient, as I've seen terminals where that fails but | |
1955 | # print s |
|
1955 | # print s | |
1956 | # |
|
1956 | # | |
1957 | # succeeds |
|
1957 | # succeeds | |
1958 | # |
|
1958 | # | |
1959 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1959 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 | |
1960 |
|
1960 | |||
1961 | #units = [u"s", u"ms",u'\xb5',"ns"] |
|
1961 | #units = [u"s", u"ms",u'\xb5',"ns"] | |
1962 | units = [u"s", u"ms",u'us',"ns"] |
|
1962 | units = [u"s", u"ms",u'us',"ns"] | |
1963 |
|
1963 | |||
1964 | scaling = [1, 1e3, 1e6, 1e9] |
|
1964 | scaling = [1, 1e3, 1e6, 1e9] | |
1965 |
|
1965 | |||
1966 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1966 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', | |
1967 | posix=False, strict=False) |
|
1967 | posix=False, strict=False) | |
1968 | if stmt == "": |
|
1968 | if stmt == "": | |
1969 | return |
|
1969 | return | |
1970 | timefunc = timeit.default_timer |
|
1970 | timefunc = timeit.default_timer | |
1971 | number = int(getattr(opts, "n", 0)) |
|
1971 | number = int(getattr(opts, "n", 0)) | |
1972 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1972 | repeat = int(getattr(opts, "r", timeit.default_repeat)) | |
1973 | precision = int(getattr(opts, "p", 3)) |
|
1973 | precision = int(getattr(opts, "p", 3)) | |
1974 | if hasattr(opts, "t"): |
|
1974 | if hasattr(opts, "t"): | |
1975 | timefunc = time.time |
|
1975 | timefunc = time.time | |
1976 | if hasattr(opts, "c"): |
|
1976 | if hasattr(opts, "c"): | |
1977 | timefunc = clock |
|
1977 | timefunc = clock | |
1978 |
|
1978 | |||
1979 | timer = timeit.Timer(timer=timefunc) |
|
1979 | timer = timeit.Timer(timer=timefunc) | |
1980 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1980 | # this code has tight coupling to the inner workings of timeit.Timer, | |
1981 | # but is there a better way to achieve that the code stmt has access |
|
1981 | # but is there a better way to achieve that the code stmt has access | |
1982 | # to the shell namespace? |
|
1982 | # to the shell namespace? | |
1983 |
|
1983 | |||
1984 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1984 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), | |
1985 | 'setup': "pass"} |
|
1985 | 'setup': "pass"} | |
1986 | # Track compilation time so it can be reported if too long |
|
1986 | # Track compilation time so it can be reported if too long | |
1987 | # Minimum time above which compilation time will be reported |
|
1987 | # Minimum time above which compilation time will be reported | |
1988 | tc_min = 0.1 |
|
1988 | tc_min = 0.1 | |
1989 |
|
1989 | |||
1990 | t0 = clock() |
|
1990 | t0 = clock() | |
1991 | code = compile(src, "<magic-timeit>", "exec") |
|
1991 | code = compile(src, "<magic-timeit>", "exec") | |
1992 | tc = clock()-t0 |
|
1992 | tc = clock()-t0 | |
1993 |
|
1993 | |||
1994 | ns = {} |
|
1994 | ns = {} | |
1995 | exec code in self.shell.user_ns, ns |
|
1995 | exec code in self.shell.user_ns, ns | |
1996 | timer.inner = ns["inner"] |
|
1996 | timer.inner = ns["inner"] | |
1997 |
|
1997 | |||
1998 | if number == 0: |
|
1998 | if number == 0: | |
1999 | # determine number so that 0.2 <= total time < 2.0 |
|
1999 | # determine number so that 0.2 <= total time < 2.0 | |
2000 | number = 1 |
|
2000 | number = 1 | |
2001 | for i in range(1, 10): |
|
2001 | for i in range(1, 10): | |
2002 | if timer.timeit(number) >= 0.2: |
|
2002 | if timer.timeit(number) >= 0.2: | |
2003 | break |
|
2003 | break | |
2004 | number *= 10 |
|
2004 | number *= 10 | |
2005 |
|
2005 | |||
2006 | best = min(timer.repeat(repeat, number)) / number |
|
2006 | best = min(timer.repeat(repeat, number)) / number | |
2007 |
|
2007 | |||
2008 | if best > 0.0 and best < 1000.0: |
|
2008 | if best > 0.0 and best < 1000.0: | |
2009 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
2009 | order = min(-int(math.floor(math.log10(best)) // 3), 3) | |
2010 | elif best >= 1000.0: |
|
2010 | elif best >= 1000.0: | |
2011 | order = 0 |
|
2011 | order = 0 | |
2012 | else: |
|
2012 | else: | |
2013 | order = 3 |
|
2013 | order = 3 | |
2014 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
2014 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, | |
2015 | precision, |
|
2015 | precision, | |
2016 | best * scaling[order], |
|
2016 | best * scaling[order], | |
2017 | units[order]) |
|
2017 | units[order]) | |
2018 | if tc > tc_min: |
|
2018 | if tc > tc_min: | |
2019 | print "Compiler time: %.2f s" % tc |
|
2019 | print "Compiler time: %.2f s" % tc | |
2020 |
|
2020 | |||
2021 | @skip_doctest |
|
2021 | @skip_doctest | |
2022 | @needs_local_scope |
|
2022 | @needs_local_scope | |
2023 | def magic_time(self,parameter_s = ''): |
|
2023 | def magic_time(self,parameter_s = ''): | |
2024 | """Time execution of a Python statement or expression. |
|
2024 | """Time execution of a Python statement or expression. | |
2025 |
|
2025 | |||
2026 | The CPU and wall clock times are printed, and the value of the |
|
2026 | The CPU and wall clock times are printed, and the value of the | |
2027 | expression (if any) is returned. Note that under Win32, system time |
|
2027 | expression (if any) is returned. Note that under Win32, system time | |
2028 | is always reported as 0, since it can not be measured. |
|
2028 | is always reported as 0, since it can not be measured. | |
2029 |
|
2029 | |||
2030 | This function provides very basic timing functionality. In Python |
|
2030 | This function provides very basic timing functionality. In Python | |
2031 | 2.3, the timeit module offers more control and sophistication, so this |
|
2031 | 2.3, the timeit module offers more control and sophistication, so this | |
2032 | could be rewritten to use it (patches welcome). |
|
2032 | could be rewritten to use it (patches welcome). | |
2033 |
|
2033 | |||
2034 | Examples |
|
2034 | Examples | |
2035 | -------- |
|
2035 | -------- | |
2036 | :: |
|
2036 | :: | |
2037 |
|
2037 | |||
2038 | In [1]: time 2**128 |
|
2038 | In [1]: time 2**128 | |
2039 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
2039 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
2040 | Wall time: 0.00 |
|
2040 | Wall time: 0.00 | |
2041 | Out[1]: 340282366920938463463374607431768211456L |
|
2041 | Out[1]: 340282366920938463463374607431768211456L | |
2042 |
|
2042 | |||
2043 | In [2]: n = 1000000 |
|
2043 | In [2]: n = 1000000 | |
2044 |
|
2044 | |||
2045 | In [3]: time sum(range(n)) |
|
2045 | In [3]: time sum(range(n)) | |
2046 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
2046 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
2047 | Wall time: 1.37 |
|
2047 | Wall time: 1.37 | |
2048 | Out[3]: 499999500000L |
|
2048 | Out[3]: 499999500000L | |
2049 |
|
2049 | |||
2050 | In [4]: time print 'hello world' |
|
2050 | In [4]: time print 'hello world' | |
2051 | hello world |
|
2051 | hello world | |
2052 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
2052 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
2053 | Wall time: 0.00 |
|
2053 | Wall time: 0.00 | |
2054 |
|
2054 | |||
2055 | Note that the time needed by Python to compile the given expression |
|
2055 | Note that the time needed by Python to compile the given expression | |
2056 | will be reported if it is more than 0.1s. In this example, the |
|
2056 | will be reported if it is more than 0.1s. In this example, the | |
2057 | actual exponentiation is done by Python at compilation time, so while |
|
2057 | actual exponentiation is done by Python at compilation time, so while | |
2058 | the expression can take a noticeable amount of time to compute, that |
|
2058 | the expression can take a noticeable amount of time to compute, that | |
2059 | time is purely due to the compilation: |
|
2059 | time is purely due to the compilation: | |
2060 |
|
2060 | |||
2061 | In [5]: time 3**9999; |
|
2061 | In [5]: time 3**9999; | |
2062 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
2062 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
2063 | Wall time: 0.00 s |
|
2063 | Wall time: 0.00 s | |
2064 |
|
2064 | |||
2065 | In [6]: time 3**999999; |
|
2065 | In [6]: time 3**999999; | |
2066 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
2066 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
2067 | Wall time: 0.00 s |
|
2067 | Wall time: 0.00 s | |
2068 | Compiler : 0.78 s |
|
2068 | Compiler : 0.78 s | |
2069 | """ |
|
2069 | """ | |
2070 |
|
2070 | |||
2071 | # fail immediately if the given expression can't be compiled |
|
2071 | # fail immediately if the given expression can't be compiled | |
2072 |
|
2072 | |||
2073 | expr = self.shell.prefilter(parameter_s,False) |
|
2073 | expr = self.shell.prefilter(parameter_s,False) | |
2074 |
|
2074 | |||
2075 | # Minimum time above which compilation time will be reported |
|
2075 | # Minimum time above which compilation time will be reported | |
2076 | tc_min = 0.1 |
|
2076 | tc_min = 0.1 | |
2077 |
|
2077 | |||
2078 | try: |
|
2078 | try: | |
2079 | mode = 'eval' |
|
2079 | mode = 'eval' | |
2080 | t0 = clock() |
|
2080 | t0 = clock() | |
2081 | code = compile(expr,'<timed eval>',mode) |
|
2081 | code = compile(expr,'<timed eval>',mode) | |
2082 | tc = clock()-t0 |
|
2082 | tc = clock()-t0 | |
2083 | except SyntaxError: |
|
2083 | except SyntaxError: | |
2084 | mode = 'exec' |
|
2084 | mode = 'exec' | |
2085 | t0 = clock() |
|
2085 | t0 = clock() | |
2086 | code = compile(expr,'<timed exec>',mode) |
|
2086 | code = compile(expr,'<timed exec>',mode) | |
2087 | tc = clock()-t0 |
|
2087 | tc = clock()-t0 | |
2088 | # skew measurement as little as possible |
|
2088 | # skew measurement as little as possible | |
2089 | glob = self.shell.user_ns |
|
2089 | glob = self.shell.user_ns | |
2090 | locs = self._magic_locals |
|
2090 | locs = self._magic_locals | |
2091 | clk = clock2 |
|
2091 | clk = clock2 | |
2092 | wtime = time.time |
|
2092 | wtime = time.time | |
2093 | # time execution |
|
2093 | # time execution | |
2094 | wall_st = wtime() |
|
2094 | wall_st = wtime() | |
2095 | if mode=='eval': |
|
2095 | if mode=='eval': | |
2096 | st = clk() |
|
2096 | st = clk() | |
2097 | out = eval(code, glob, locs) |
|
2097 | out = eval(code, glob, locs) | |
2098 | end = clk() |
|
2098 | end = clk() | |
2099 | else: |
|
2099 | else: | |
2100 | st = clk() |
|
2100 | st = clk() | |
2101 | exec code in glob, locs |
|
2101 | exec code in glob, locs | |
2102 | end = clk() |
|
2102 | end = clk() | |
2103 | out = None |
|
2103 | out = None | |
2104 | wall_end = wtime() |
|
2104 | wall_end = wtime() | |
2105 | # Compute actual times and report |
|
2105 | # Compute actual times and report | |
2106 | wall_time = wall_end-wall_st |
|
2106 | wall_time = wall_end-wall_st | |
2107 | cpu_user = end[0]-st[0] |
|
2107 | cpu_user = end[0]-st[0] | |
2108 | cpu_sys = end[1]-st[1] |
|
2108 | cpu_sys = end[1]-st[1] | |
2109 | cpu_tot = cpu_user+cpu_sys |
|
2109 | cpu_tot = cpu_user+cpu_sys | |
2110 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
2110 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
2111 | (cpu_user,cpu_sys,cpu_tot) |
|
2111 | (cpu_user,cpu_sys,cpu_tot) | |
2112 | print "Wall time: %.2f s" % wall_time |
|
2112 | print "Wall time: %.2f s" % wall_time | |
2113 | if tc > tc_min: |
|
2113 | if tc > tc_min: | |
2114 | print "Compiler : %.2f s" % tc |
|
2114 | print "Compiler : %.2f s" % tc | |
2115 | return out |
|
2115 | return out | |
2116 |
|
2116 | |||
2117 | @skip_doctest |
|
2117 | @skip_doctest | |
2118 | def magic_macro(self,parameter_s = ''): |
|
2118 | def magic_macro(self,parameter_s = ''): | |
2119 | """Define a macro for future re-execution. It accepts ranges of history, |
|
2119 | """Define a macro for future re-execution. It accepts ranges of history, | |
2120 | filenames or string objects. |
|
2120 | filenames or string objects. | |
2121 |
|
2121 | |||
2122 | Usage:\\ |
|
2122 | Usage:\\ | |
2123 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
2123 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... | |
2124 |
|
2124 | |||
2125 | Options: |
|
2125 | Options: | |
2126 |
|
2126 | |||
2127 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2127 | -r: use 'raw' input. By default, the 'processed' history is used, | |
2128 | so that magics are loaded in their transformed version to valid |
|
2128 | so that magics are loaded in their transformed version to valid | |
2129 | Python. If this option is given, the raw input as typed as the |
|
2129 | Python. If this option is given, the raw input as typed as the | |
2130 | command line is used instead. |
|
2130 | command line is used instead. | |
2131 |
|
2131 | |||
2132 | This will define a global variable called `name` which is a string |
|
2132 | This will define a global variable called `name` which is a string | |
2133 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
2133 | made of joining the slices and lines you specify (n1,n2,... numbers | |
2134 | above) from your input history into a single string. This variable |
|
2134 | above) from your input history into a single string. This variable | |
2135 | acts like an automatic function which re-executes those lines as if |
|
2135 | acts like an automatic function which re-executes those lines as if | |
2136 | you had typed them. You just type 'name' at the prompt and the code |
|
2136 | you had typed them. You just type 'name' at the prompt and the code | |
2137 | executes. |
|
2137 | executes. | |
2138 |
|
2138 | |||
2139 | The syntax for indicating input ranges is described in %history. |
|
2139 | The syntax for indicating input ranges is described in %history. | |
2140 |
|
2140 | |||
2141 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
2141 | Note: as a 'hidden' feature, you can also use traditional python slice | |
2142 | notation, where N:M means numbers N through M-1. |
|
2142 | notation, where N:M means numbers N through M-1. | |
2143 |
|
2143 | |||
2144 | For example, if your history contains (%hist prints it):: |
|
2144 | For example, if your history contains (%hist prints it):: | |
2145 |
|
2145 | |||
2146 | 44: x=1 |
|
2146 | 44: x=1 | |
2147 | 45: y=3 |
|
2147 | 45: y=3 | |
2148 | 46: z=x+y |
|
2148 | 46: z=x+y | |
2149 | 47: print x |
|
2149 | 47: print x | |
2150 | 48: a=5 |
|
2150 | 48: a=5 | |
2151 | 49: print 'x',x,'y',y |
|
2151 | 49: print 'x',x,'y',y | |
2152 |
|
2152 | |||
2153 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
2153 | you can create a macro with lines 44 through 47 (included) and line 49 | |
2154 | called my_macro with:: |
|
2154 | called my_macro with:: | |
2155 |
|
2155 | |||
2156 | In [55]: %macro my_macro 44-47 49 |
|
2156 | In [55]: %macro my_macro 44-47 49 | |
2157 |
|
2157 | |||
2158 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
2158 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
2159 | in one pass. |
|
2159 | in one pass. | |
2160 |
|
2160 | |||
2161 | You don't need to give the line-numbers in order, and any given line |
|
2161 | You don't need to give the line-numbers in order, and any given line | |
2162 | number can appear multiple times. You can assemble macros with any |
|
2162 | number can appear multiple times. You can assemble macros with any | |
2163 | lines from your input history in any order. |
|
2163 | lines from your input history in any order. | |
2164 |
|
2164 | |||
2165 | The macro is a simple object which holds its value in an attribute, |
|
2165 | The macro is a simple object which holds its value in an attribute, | |
2166 | but IPython's display system checks for macros and executes them as |
|
2166 | but IPython's display system checks for macros and executes them as | |
2167 | code instead of printing them when you type their name. |
|
2167 | code instead of printing them when you type their name. | |
2168 |
|
2168 | |||
2169 | You can view a macro's contents by explicitly printing it with:: |
|
2169 | You can view a macro's contents by explicitly printing it with:: | |
2170 |
|
2170 | |||
2171 | print macro_name |
|
2171 | print macro_name | |
2172 |
|
2172 | |||
2173 | """ |
|
2173 | """ | |
2174 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2174 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2175 | if not args: # List existing macros |
|
2175 | if not args: # List existing macros | |
2176 | return sorted(k for k,v in self.shell.user_ns.iteritems() if\ |
|
2176 | return sorted(k for k,v in self.shell.user_ns.iteritems() if\ | |
2177 | isinstance(v, Macro)) |
|
2177 | isinstance(v, Macro)) | |
2178 | if len(args) == 1: |
|
2178 | if len(args) == 1: | |
2179 | raise UsageError( |
|
2179 | raise UsageError( | |
2180 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
2180 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") | |
2181 | name, codefrom = args[0], " ".join(args[1:]) |
|
2181 | name, codefrom = args[0], " ".join(args[1:]) | |
2182 |
|
2182 | |||
2183 | #print 'rng',ranges # dbg |
|
2183 | #print 'rng',ranges # dbg | |
2184 | try: |
|
2184 | try: | |
2185 | lines = self.shell.find_user_code(codefrom, 'r' in opts) |
|
2185 | lines = self.shell.find_user_code(codefrom, 'r' in opts) | |
2186 | except (ValueError, TypeError) as e: |
|
2186 | except (ValueError, TypeError) as e: | |
2187 | print e.args[0] |
|
2187 | print e.args[0] | |
2188 | return |
|
2188 | return | |
2189 | macro = Macro(lines) |
|
2189 | macro = Macro(lines) | |
2190 | self.shell.define_macro(name, macro) |
|
2190 | self.shell.define_macro(name, macro) | |
2191 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
2191 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
2192 | print '=== Macro contents: ===' |
|
2192 | print '=== Macro contents: ===' | |
2193 | print macro, |
|
2193 | print macro, | |
2194 |
|
2194 | |||
2195 | def magic_save(self,parameter_s = ''): |
|
2195 | def magic_save(self,parameter_s = ''): | |
2196 | """Save a set of lines or a macro to a given filename. |
|
2196 | """Save a set of lines or a macro to a given filename. | |
2197 |
|
2197 | |||
2198 | Usage:\\ |
|
2198 | Usage:\\ | |
2199 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
2199 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
2200 |
|
2200 | |||
2201 | Options: |
|
2201 | Options: | |
2202 |
|
2202 | |||
2203 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2203 | -r: use 'raw' input. By default, the 'processed' history is used, | |
2204 | so that magics are loaded in their transformed version to valid |
|
2204 | so that magics are loaded in their transformed version to valid | |
2205 | Python. If this option is given, the raw input as typed as the |
|
2205 | Python. If this option is given, the raw input as typed as the | |
2206 | command line is used instead. |
|
2206 | command line is used instead. | |
2207 |
|
2207 | |||
2208 | This function uses the same syntax as %history for input ranges, |
|
2208 | This function uses the same syntax as %history for input ranges, | |
2209 | then saves the lines to the filename you specify. |
|
2209 | then saves the lines to the filename you specify. | |
2210 |
|
2210 | |||
2211 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2211 | It adds a '.py' extension to the file if you don't do so yourself, and | |
2212 | it asks for confirmation before overwriting existing files.""" |
|
2212 | it asks for confirmation before overwriting existing files.""" | |
2213 |
|
2213 | |||
2214 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2214 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2215 | fname, codefrom = unquote_filename(args[0]), " ".join(args[1:]) |
|
2215 | fname, codefrom = unquote_filename(args[0]), " ".join(args[1:]) | |
2216 | if not fname.endswith('.py'): |
|
2216 | if not fname.endswith('.py'): | |
2217 | fname += '.py' |
|
2217 | fname += '.py' | |
2218 | if os.path.isfile(fname): |
|
2218 | if os.path.isfile(fname): | |
2219 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2219 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
2220 | if ans.lower() not in ['y','yes']: |
|
2220 | if ans.lower() not in ['y','yes']: | |
2221 | print 'Operation cancelled.' |
|
2221 | print 'Operation cancelled.' | |
2222 | return |
|
2222 | return | |
2223 | try: |
|
2223 | try: | |
2224 | cmds = self.shell.find_user_code(codefrom, 'r' in opts) |
|
2224 | cmds = self.shell.find_user_code(codefrom, 'r' in opts) | |
2225 | except (TypeError, ValueError) as e: |
|
2225 | except (TypeError, ValueError) as e: | |
2226 | print e.args[0] |
|
2226 | print e.args[0] | |
2227 | return |
|
2227 | return | |
2228 | with io.open(fname,'w', encoding="utf-8") as f: |
|
2228 | with io.open(fname,'w', encoding="utf-8") as f: | |
2229 | f.write(u"# coding: utf-8\n") |
|
2229 | f.write(u"# coding: utf-8\n") | |
2230 | f.write(py3compat.cast_unicode(cmds)) |
|
2230 | f.write(py3compat.cast_unicode(cmds)) | |
2231 | print 'The following commands were written to file `%s`:' % fname |
|
2231 | print 'The following commands were written to file `%s`:' % fname | |
2232 | print cmds |
|
2232 | print cmds | |
2233 |
|
2233 | |||
2234 | def magic_pastebin(self, parameter_s = ''): |
|
2234 | def magic_pastebin(self, parameter_s = ''): | |
2235 | """Upload code to the 'Lodge it' paste bin, returning the URL.""" |
|
2235 | """Upload code to the 'Lodge it' paste bin, returning the URL.""" | |
2236 | try: |
|
2236 | try: | |
2237 | code = self.shell.find_user_code(parameter_s) |
|
2237 | code = self.shell.find_user_code(parameter_s) | |
2238 | except (ValueError, TypeError) as e: |
|
2238 | except (ValueError, TypeError) as e: | |
2239 | print e.args[0] |
|
2239 | print e.args[0] | |
2240 | return |
|
2240 | return | |
2241 | pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/') |
|
2241 | pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/') | |
2242 | id = pbserver.pastes.newPaste("python", code) |
|
2242 | id = pbserver.pastes.newPaste("python", code) | |
2243 | return "http://paste.pocoo.org/show/" + id |
|
2243 | return "http://paste.pocoo.org/show/" + id | |
2244 |
|
2244 | |||
2245 | def magic_loadpy(self, arg_s): |
|
2245 | def magic_loadpy(self, arg_s): | |
2246 | """Load a .py python script into the GUI console. |
|
2246 | """Load a .py python script into the GUI console. | |
2247 |
|
2247 | |||
2248 | This magic command can either take a local filename or a url:: |
|
2248 | This magic command can either take a local filename or a url:: | |
2249 |
|
2249 | |||
2250 | %loadpy myscript.py |
|
2250 | %loadpy myscript.py | |
2251 | %loadpy http://www.example.com/myscript.py |
|
2251 | %loadpy http://www.example.com/myscript.py | |
2252 | """ |
|
2252 | """ | |
2253 | arg_s = unquote_filename(arg_s) |
|
2253 | arg_s = unquote_filename(arg_s) | |
2254 | remote_url = arg_s.startswith(('http://', 'https://')) |
|
2254 | remote_url = arg_s.startswith(('http://', 'https://')) | |
2255 | local_url = not remote_url |
|
2255 | local_url = not remote_url | |
2256 | if local_url and not arg_s.endswith('.py'): |
|
2256 | if local_url and not arg_s.endswith('.py'): | |
2257 | # Local files must be .py; for remote URLs it's possible that the |
|
2257 | # Local files must be .py; for remote URLs it's possible that the | |
2258 | # fetch URL doesn't have a .py in it (many servers have an opaque |
|
2258 | # fetch URL doesn't have a .py in it (many servers have an opaque | |
2259 | # URL, such as scipy-central.org). |
|
2259 | # URL, such as scipy-central.org). | |
2260 | raise ValueError('%%loadpy only works with .py files: %s' % arg_s) |
|
2260 | raise ValueError('%%loadpy only works with .py files: %s' % arg_s) | |
2261 |
|
2261 | |||
2262 | # openpy takes care of finding the source encoding (per PEP 263) |
|
2262 | # openpy takes care of finding the source encoding (per PEP 263) | |
2263 | if remote_url: |
|
2263 | if remote_url: | |
2264 | contents = openpy.read_py_url(arg_s, skip_encoding_cookie=True) |
|
2264 | contents = openpy.read_py_url(arg_s, skip_encoding_cookie=True) | |
2265 | else: |
|
2265 | else: | |
2266 | contents = openpy.read_py_file(arg_s, skip_encoding_cookie=True) |
|
2266 | contents = openpy.read_py_file(arg_s, skip_encoding_cookie=True) | |
2267 |
|
2267 | |||
2268 | self.set_next_input(contents) |
|
2268 | self.set_next_input(contents) | |
2269 |
|
2269 | |||
2270 | def _find_edit_target(self, args, opts, last_call): |
|
2270 | def _find_edit_target(self, args, opts, last_call): | |
2271 | """Utility method used by magic_edit to find what to edit.""" |
|
2271 | """Utility method used by magic_edit to find what to edit.""" | |
2272 |
|
2272 | |||
2273 | def make_filename(arg): |
|
2273 | def make_filename(arg): | |
2274 | "Make a filename from the given args" |
|
2274 | "Make a filename from the given args" | |
2275 | arg = unquote_filename(arg) |
|
2275 | arg = unquote_filename(arg) | |
2276 | try: |
|
2276 | try: | |
2277 | filename = get_py_filename(arg) |
|
2277 | filename = get_py_filename(arg) | |
2278 | except IOError: |
|
2278 | except IOError: | |
2279 | # If it ends with .py but doesn't already exist, assume we want |
|
2279 | # If it ends with .py but doesn't already exist, assume we want | |
2280 | # a new file. |
|
2280 | # a new file. | |
2281 | if arg.endswith('.py'): |
|
2281 | if arg.endswith('.py'): | |
2282 | filename = arg |
|
2282 | filename = arg | |
2283 | else: |
|
2283 | else: | |
2284 | filename = None |
|
2284 | filename = None | |
2285 | return filename |
|
2285 | return filename | |
2286 |
|
2286 | |||
2287 | # Set a few locals from the options for convenience: |
|
2287 | # Set a few locals from the options for convenience: | |
2288 | opts_prev = 'p' in opts |
|
2288 | opts_prev = 'p' in opts | |
2289 | opts_raw = 'r' in opts |
|
2289 | opts_raw = 'r' in opts | |
2290 |
|
2290 | |||
2291 | # custom exceptions |
|
2291 | # custom exceptions | |
2292 | class DataIsObject(Exception): pass |
|
2292 | class DataIsObject(Exception): pass | |
2293 |
|
2293 | |||
2294 | # Default line number value |
|
2294 | # Default line number value | |
2295 | lineno = opts.get('n',None) |
|
2295 | lineno = opts.get('n',None) | |
2296 |
|
2296 | |||
2297 | if opts_prev: |
|
2297 | if opts_prev: | |
2298 | args = '_%s' % last_call[0] |
|
2298 | args = '_%s' % last_call[0] | |
2299 | if not self.shell.user_ns.has_key(args): |
|
2299 | if not self.shell.user_ns.has_key(args): | |
2300 | args = last_call[1] |
|
2300 | args = last_call[1] | |
2301 |
|
2301 | |||
2302 | # use last_call to remember the state of the previous call, but don't |
|
2302 | # use last_call to remember the state of the previous call, but don't | |
2303 | # let it be clobbered by successive '-p' calls. |
|
2303 | # let it be clobbered by successive '-p' calls. | |
2304 | try: |
|
2304 | try: | |
2305 | last_call[0] = self.shell.displayhook.prompt_count |
|
2305 | last_call[0] = self.shell.displayhook.prompt_count | |
2306 | if not opts_prev: |
|
2306 | if not opts_prev: | |
2307 | last_call[1] = args |
|
2307 | last_call[1] = args | |
2308 | except: |
|
2308 | except: | |
2309 | pass |
|
2309 | pass | |
2310 |
|
2310 | |||
2311 | # by default this is done with temp files, except when the given |
|
2311 | # by default this is done with temp files, except when the given | |
2312 | # arg is a filename |
|
2312 | # arg is a filename | |
2313 | use_temp = True |
|
2313 | use_temp = True | |
2314 |
|
2314 | |||
2315 | data = '' |
|
2315 | data = '' | |
2316 |
|
2316 | |||
2317 | # First, see if the arguments should be a filename. |
|
2317 | # First, see if the arguments should be a filename. | |
2318 | filename = make_filename(args) |
|
2318 | filename = make_filename(args) | |
2319 | if filename: |
|
2319 | if filename: | |
2320 | use_temp = False |
|
2320 | use_temp = False | |
2321 | elif args: |
|
2321 | elif args: | |
2322 | # Mode where user specifies ranges of lines, like in %macro. |
|
2322 | # Mode where user specifies ranges of lines, like in %macro. | |
2323 | data = self.extract_input_lines(args, opts_raw) |
|
2323 | data = self.extract_input_lines(args, opts_raw) | |
2324 | if not data: |
|
2324 | if not data: | |
2325 | try: |
|
2325 | try: | |
2326 | # Load the parameter given as a variable. If not a string, |
|
2326 | # Load the parameter given as a variable. If not a string, | |
2327 | # process it as an object instead (below) |
|
2327 | # process it as an object instead (below) | |
2328 |
|
2328 | |||
2329 | #print '*** args',args,'type',type(args) # dbg |
|
2329 | #print '*** args',args,'type',type(args) # dbg | |
2330 | data = eval(args, self.shell.user_ns) |
|
2330 | data = eval(args, self.shell.user_ns) | |
2331 | if not isinstance(data, basestring): |
|
2331 | if not isinstance(data, basestring): | |
2332 | raise DataIsObject |
|
2332 | raise DataIsObject | |
2333 |
|
2333 | |||
2334 | except (NameError,SyntaxError): |
|
2334 | except (NameError,SyntaxError): | |
2335 | # given argument is not a variable, try as a filename |
|
2335 | # given argument is not a variable, try as a filename | |
2336 | filename = make_filename(args) |
|
2336 | filename = make_filename(args) | |
2337 | if filename is None: |
|
2337 | if filename is None: | |
2338 | warn("Argument given (%s) can't be found as a variable " |
|
2338 | warn("Argument given (%s) can't be found as a variable " | |
2339 | "or as a filename." % args) |
|
2339 | "or as a filename." % args) | |
2340 | return |
|
2340 | return | |
2341 | use_temp = False |
|
2341 | use_temp = False | |
2342 |
|
2342 | |||
2343 | except DataIsObject: |
|
2343 | except DataIsObject: | |
2344 | # macros have a special edit function |
|
2344 | # macros have a special edit function | |
2345 | if isinstance(data, Macro): |
|
2345 | if isinstance(data, Macro): | |
2346 | raise MacroToEdit(data) |
|
2346 | raise MacroToEdit(data) | |
2347 |
|
2347 | |||
2348 | # For objects, try to edit the file where they are defined |
|
2348 | # For objects, try to edit the file where they are defined | |
2349 | try: |
|
2349 | try: | |
2350 | filename = inspect.getabsfile(data) |
|
2350 | filename = inspect.getabsfile(data) | |
2351 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2351 | if 'fakemodule' in filename.lower() and inspect.isclass(data): | |
2352 | # class created by %edit? Try to find source |
|
2352 | # class created by %edit? Try to find source | |
2353 | # by looking for method definitions instead, the |
|
2353 | # by looking for method definitions instead, the | |
2354 | # __module__ in those classes is FakeModule. |
|
2354 | # __module__ in those classes is FakeModule. | |
2355 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2355 | attrs = [getattr(data, aname) for aname in dir(data)] | |
2356 | for attr in attrs: |
|
2356 | for attr in attrs: | |
2357 | if not inspect.ismethod(attr): |
|
2357 | if not inspect.ismethod(attr): | |
2358 | continue |
|
2358 | continue | |
2359 | filename = inspect.getabsfile(attr) |
|
2359 | filename = inspect.getabsfile(attr) | |
2360 | if filename and 'fakemodule' not in filename.lower(): |
|
2360 | if filename and 'fakemodule' not in filename.lower(): | |
2361 | # change the attribute to be the edit target instead |
|
2361 | # change the attribute to be the edit target instead | |
2362 | data = attr |
|
2362 | data = attr | |
2363 | break |
|
2363 | break | |
2364 |
|
2364 | |||
2365 | datafile = 1 |
|
2365 | datafile = 1 | |
2366 | except TypeError: |
|
2366 | except TypeError: | |
2367 | filename = make_filename(args) |
|
2367 | filename = make_filename(args) | |
2368 | datafile = 1 |
|
2368 | datafile = 1 | |
2369 | warn('Could not find file where `%s` is defined.\n' |
|
2369 | warn('Could not find file where `%s` is defined.\n' | |
2370 | 'Opening a file named `%s`' % (args,filename)) |
|
2370 | 'Opening a file named `%s`' % (args,filename)) | |
2371 | # Now, make sure we can actually read the source (if it was in |
|
2371 | # Now, make sure we can actually read the source (if it was in | |
2372 | # a temp file it's gone by now). |
|
2372 | # a temp file it's gone by now). | |
2373 | if datafile: |
|
2373 | if datafile: | |
2374 | try: |
|
2374 | try: | |
2375 | if lineno is None: |
|
2375 | if lineno is None: | |
2376 | lineno = inspect.getsourcelines(data)[1] |
|
2376 | lineno = inspect.getsourcelines(data)[1] | |
2377 | except IOError: |
|
2377 | except IOError: | |
2378 | filename = make_filename(args) |
|
2378 | filename = make_filename(args) | |
2379 | if filename is None: |
|
2379 | if filename is None: | |
2380 | warn('The file `%s` where `%s` was defined cannot ' |
|
2380 | warn('The file `%s` where `%s` was defined cannot ' | |
2381 | 'be read.' % (filename,data)) |
|
2381 | 'be read.' % (filename,data)) | |
2382 | return |
|
2382 | return | |
2383 | use_temp = False |
|
2383 | use_temp = False | |
2384 |
|
2384 | |||
2385 | if use_temp: |
|
2385 | if use_temp: | |
2386 | filename = self.shell.mktempfile(data) |
|
2386 | filename = self.shell.mktempfile(data) | |
2387 | print 'IPython will make a temporary file named:',filename |
|
2387 | print 'IPython will make a temporary file named:',filename | |
2388 |
|
2388 | |||
2389 | return filename, lineno, use_temp |
|
2389 | return filename, lineno, use_temp | |
2390 |
|
2390 | |||
2391 | def _edit_macro(self,mname,macro): |
|
2391 | def _edit_macro(self,mname,macro): | |
2392 | """open an editor with the macro data in a file""" |
|
2392 | """open an editor with the macro data in a file""" | |
2393 | filename = self.shell.mktempfile(macro.value) |
|
2393 | filename = self.shell.mktempfile(macro.value) | |
2394 | self.shell.hooks.editor(filename) |
|
2394 | self.shell.hooks.editor(filename) | |
2395 |
|
2395 | |||
2396 | # and make a new macro object, to replace the old one |
|
2396 | # and make a new macro object, to replace the old one | |
2397 | mfile = open(filename) |
|
2397 | mfile = open(filename) | |
2398 | mvalue = mfile.read() |
|
2398 | mvalue = mfile.read() | |
2399 | mfile.close() |
|
2399 | mfile.close() | |
2400 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2400 | self.shell.user_ns[mname] = Macro(mvalue) | |
2401 |
|
2401 | |||
2402 | def magic_ed(self,parameter_s=''): |
|
2402 | def magic_ed(self,parameter_s=''): | |
2403 | """Alias to %edit.""" |
|
2403 | """Alias to %edit.""" | |
2404 | return self.magic_edit(parameter_s) |
|
2404 | return self.magic_edit(parameter_s) | |
2405 |
|
2405 | |||
2406 | @skip_doctest |
|
2406 | @skip_doctest | |
2407 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2407 | def magic_edit(self,parameter_s='',last_call=['','']): | |
2408 | """Bring up an editor and execute the resulting code. |
|
2408 | """Bring up an editor and execute the resulting code. | |
2409 |
|
2409 | |||
2410 | Usage: |
|
2410 | Usage: | |
2411 | %edit [options] [args] |
|
2411 | %edit [options] [args] | |
2412 |
|
2412 | |||
2413 | %edit runs IPython's editor hook. The default version of this hook is |
|
2413 | %edit runs IPython's editor hook. The default version of this hook is | |
2414 | set to call the editor specified by your $EDITOR environment variable. |
|
2414 | set to call the editor specified by your $EDITOR environment variable. | |
2415 | If this isn't found, it will default to vi under Linux/Unix and to |
|
2415 | If this isn't found, it will default to vi under Linux/Unix and to | |
2416 | notepad under Windows. See the end of this docstring for how to change |
|
2416 | notepad under Windows. See the end of this docstring for how to change | |
2417 | the editor hook. |
|
2417 | the editor hook. | |
2418 |
|
2418 | |||
2419 | You can also set the value of this editor via the |
|
2419 | You can also set the value of this editor via the | |
2420 | ``TerminalInteractiveShell.editor`` option in your configuration file. |
|
2420 | ``TerminalInteractiveShell.editor`` option in your configuration file. | |
2421 | This is useful if you wish to use a different editor from your typical |
|
2421 | This is useful if you wish to use a different editor from your typical | |
2422 | default with IPython (and for Windows users who typically don't set |
|
2422 | default with IPython (and for Windows users who typically don't set | |
2423 | environment variables). |
|
2423 | environment variables). | |
2424 |
|
2424 | |||
2425 | This command allows you to conveniently edit multi-line code right in |
|
2425 | This command allows you to conveniently edit multi-line code right in | |
2426 | your IPython session. |
|
2426 | your IPython session. | |
2427 |
|
2427 | |||
2428 | If called without arguments, %edit opens up an empty editor with a |
|
2428 | If called without arguments, %edit opens up an empty editor with a | |
2429 | temporary file and will execute the contents of this file when you |
|
2429 | temporary file and will execute the contents of this file when you | |
2430 | close it (don't forget to save it!). |
|
2430 | close it (don't forget to save it!). | |
2431 |
|
2431 | |||
2432 |
|
2432 | |||
2433 | Options: |
|
2433 | Options: | |
2434 |
|
2434 | |||
2435 | -n <number>: open the editor at a specified line number. By default, |
|
2435 | -n <number>: open the editor at a specified line number. By default, | |
2436 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2436 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
2437 | you can configure this by providing your own modified hook if your |
|
2437 | you can configure this by providing your own modified hook if your | |
2438 | favorite editor supports line-number specifications with a different |
|
2438 | favorite editor supports line-number specifications with a different | |
2439 | syntax. |
|
2439 | syntax. | |
2440 |
|
2440 | |||
2441 | -p: this will call the editor with the same data as the previous time |
|
2441 | -p: this will call the editor with the same data as the previous time | |
2442 | it was used, regardless of how long ago (in your current session) it |
|
2442 | it was used, regardless of how long ago (in your current session) it | |
2443 | was. |
|
2443 | was. | |
2444 |
|
2444 | |||
2445 | -r: use 'raw' input. This option only applies to input taken from the |
|
2445 | -r: use 'raw' input. This option only applies to input taken from the | |
2446 | user's history. By default, the 'processed' history is used, so that |
|
2446 | user's history. By default, the 'processed' history is used, so that | |
2447 | magics are loaded in their transformed version to valid Python. If |
|
2447 | magics are loaded in their transformed version to valid Python. If | |
2448 | this option is given, the raw input as typed as the command line is |
|
2448 | this option is given, the raw input as typed as the command line is | |
2449 | used instead. When you exit the editor, it will be executed by |
|
2449 | used instead. When you exit the editor, it will be executed by | |
2450 | IPython's own processor. |
|
2450 | IPython's own processor. | |
2451 |
|
2451 | |||
2452 | -x: do not execute the edited code immediately upon exit. This is |
|
2452 | -x: do not execute the edited code immediately upon exit. This is | |
2453 | mainly useful if you are editing programs which need to be called with |
|
2453 | mainly useful if you are editing programs which need to be called with | |
2454 | command line arguments, which you can then do using %run. |
|
2454 | command line arguments, which you can then do using %run. | |
2455 |
|
2455 | |||
2456 |
|
2456 | |||
2457 | Arguments: |
|
2457 | Arguments: | |
2458 |
|
2458 | |||
2459 | If arguments are given, the following possibilities exist: |
|
2459 | If arguments are given, the following possibilities exist: | |
2460 |
|
2460 | |||
2461 | - If the argument is a filename, IPython will load that into the |
|
2461 | - If the argument is a filename, IPython will load that into the | |
2462 | editor. It will execute its contents with execfile() when you exit, |
|
2462 | editor. It will execute its contents with execfile() when you exit, | |
2463 | loading any code in the file into your interactive namespace. |
|
2463 | loading any code in the file into your interactive namespace. | |
2464 |
|
2464 | |||
2465 | - The arguments are ranges of input history, e.g. "7 ~1/4-6". |
|
2465 | - The arguments are ranges of input history, e.g. "7 ~1/4-6". | |
2466 | The syntax is the same as in the %history magic. |
|
2466 | The syntax is the same as in the %history magic. | |
2467 |
|
2467 | |||
2468 | - If the argument is a string variable, its contents are loaded |
|
2468 | - If the argument is a string variable, its contents are loaded | |
2469 | into the editor. You can thus edit any string which contains |
|
2469 | into the editor. You can thus edit any string which contains | |
2470 | python code (including the result of previous edits). |
|
2470 | python code (including the result of previous edits). | |
2471 |
|
2471 | |||
2472 | - If the argument is the name of an object (other than a string), |
|
2472 | - If the argument is the name of an object (other than a string), | |
2473 | IPython will try to locate the file where it was defined and open the |
|
2473 | IPython will try to locate the file where it was defined and open the | |
2474 | editor at the point where it is defined. You can use `%edit function` |
|
2474 | editor at the point where it is defined. You can use `%edit function` | |
2475 | to load an editor exactly at the point where 'function' is defined, |
|
2475 | to load an editor exactly at the point where 'function' is defined, | |
2476 | edit it and have the file be executed automatically. |
|
2476 | edit it and have the file be executed automatically. | |
2477 |
|
2477 | |||
2478 | - If the object is a macro (see %macro for details), this opens up your |
|
2478 | - If the object is a macro (see %macro for details), this opens up your | |
2479 | specified editor with a temporary file containing the macro's data. |
|
2479 | specified editor with a temporary file containing the macro's data. | |
2480 | Upon exit, the macro is reloaded with the contents of the file. |
|
2480 | Upon exit, the macro is reloaded with the contents of the file. | |
2481 |
|
2481 | |||
2482 | Note: opening at an exact line is only supported under Unix, and some |
|
2482 | Note: opening at an exact line is only supported under Unix, and some | |
2483 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2483 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
2484 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2484 | '+NUMBER' parameter necessary for this feature. Good editors like | |
2485 | (X)Emacs, vi, jed, pico and joe all do. |
|
2485 | (X)Emacs, vi, jed, pico and joe all do. | |
2486 |
|
2486 | |||
2487 | After executing your code, %edit will return as output the code you |
|
2487 | After executing your code, %edit will return as output the code you | |
2488 | typed in the editor (except when it was an existing file). This way |
|
2488 | typed in the editor (except when it was an existing file). This way | |
2489 | you can reload the code in further invocations of %edit as a variable, |
|
2489 | you can reload the code in further invocations of %edit as a variable, | |
2490 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2490 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
2491 | the output. |
|
2491 | the output. | |
2492 |
|
2492 | |||
2493 | Note that %edit is also available through the alias %ed. |
|
2493 | Note that %edit is also available through the alias %ed. | |
2494 |
|
2494 | |||
2495 | This is an example of creating a simple function inside the editor and |
|
2495 | This is an example of creating a simple function inside the editor and | |
2496 | then modifying it. First, start up the editor:: |
|
2496 | then modifying it. First, start up the editor:: | |
2497 |
|
2497 | |||
2498 | In [1]: ed |
|
2498 | In [1]: ed | |
2499 | Editing... done. Executing edited code... |
|
2499 | Editing... done. Executing edited code... | |
2500 | Out[1]: 'def foo():\\n print "foo() was defined in an editing |
|
2500 | Out[1]: 'def foo():\\n print "foo() was defined in an editing | |
2501 | session"\\n' |
|
2501 | session"\\n' | |
2502 |
|
2502 | |||
2503 | We can then call the function foo():: |
|
2503 | We can then call the function foo():: | |
2504 |
|
2504 | |||
2505 | In [2]: foo() |
|
2505 | In [2]: foo() | |
2506 | foo() was defined in an editing session |
|
2506 | foo() was defined in an editing session | |
2507 |
|
2507 | |||
2508 | Now we edit foo. IPython automatically loads the editor with the |
|
2508 | Now we edit foo. IPython automatically loads the editor with the | |
2509 | (temporary) file where foo() was previously defined:: |
|
2509 | (temporary) file where foo() was previously defined:: | |
2510 |
|
2510 | |||
2511 | In [3]: ed foo |
|
2511 | In [3]: ed foo | |
2512 | Editing... done. Executing edited code... |
|
2512 | Editing... done. Executing edited code... | |
2513 |
|
2513 | |||
2514 | And if we call foo() again we get the modified version:: |
|
2514 | And if we call foo() again we get the modified version:: | |
2515 |
|
2515 | |||
2516 | In [4]: foo() |
|
2516 | In [4]: foo() | |
2517 | foo() has now been changed! |
|
2517 | foo() has now been changed! | |
2518 |
|
2518 | |||
2519 | Here is an example of how to edit a code snippet successive |
|
2519 | Here is an example of how to edit a code snippet successive | |
2520 | times. First we call the editor:: |
|
2520 | times. First we call the editor:: | |
2521 |
|
2521 | |||
2522 | In [5]: ed |
|
2522 | In [5]: ed | |
2523 | Editing... done. Executing edited code... |
|
2523 | Editing... done. Executing edited code... | |
2524 | hello |
|
2524 | hello | |
2525 | Out[5]: "print 'hello'\\n" |
|
2525 | Out[5]: "print 'hello'\\n" | |
2526 |
|
2526 | |||
2527 | Now we call it again with the previous output (stored in _):: |
|
2527 | Now we call it again with the previous output (stored in _):: | |
2528 |
|
2528 | |||
2529 | In [6]: ed _ |
|
2529 | In [6]: ed _ | |
2530 | Editing... done. Executing edited code... |
|
2530 | Editing... done. Executing edited code... | |
2531 | hello world |
|
2531 | hello world | |
2532 | Out[6]: "print 'hello world'\\n" |
|
2532 | Out[6]: "print 'hello world'\\n" | |
2533 |
|
2533 | |||
2534 | Now we call it with the output #8 (stored in _8, also as Out[8]):: |
|
2534 | Now we call it with the output #8 (stored in _8, also as Out[8]):: | |
2535 |
|
2535 | |||
2536 | In [7]: ed _8 |
|
2536 | In [7]: ed _8 | |
2537 | Editing... done. Executing edited code... |
|
2537 | Editing... done. Executing edited code... | |
2538 | hello again |
|
2538 | hello again | |
2539 | Out[7]: "print 'hello again'\\n" |
|
2539 | Out[7]: "print 'hello again'\\n" | |
2540 |
|
2540 | |||
2541 |
|
2541 | |||
2542 | Changing the default editor hook: |
|
2542 | Changing the default editor hook: | |
2543 |
|
2543 | |||
2544 | If you wish to write your own editor hook, you can put it in a |
|
2544 | If you wish to write your own editor hook, you can put it in a | |
2545 | configuration file which you load at startup time. The default hook |
|
2545 | configuration file which you load at startup time. The default hook | |
2546 | is defined in the IPython.core.hooks module, and you can use that as a |
|
2546 | is defined in the IPython.core.hooks module, and you can use that as a | |
2547 | starting example for further modifications. That file also has |
|
2547 | starting example for further modifications. That file also has | |
2548 | general instructions on how to set a new hook for use once you've |
|
2548 | general instructions on how to set a new hook for use once you've | |
2549 | defined it.""" |
|
2549 | defined it.""" | |
2550 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2550 | opts,args = self.parse_options(parameter_s,'prxn:') | |
2551 |
|
2551 | |||
2552 | try: |
|
2552 | try: | |
2553 | filename, lineno, is_temp = self._find_edit_target(args, opts, last_call) |
|
2553 | filename, lineno, is_temp = self._find_edit_target(args, opts, last_call) | |
2554 | except MacroToEdit as e: |
|
2554 | except MacroToEdit as e: | |
2555 | self._edit_macro(args, e.args[0]) |
|
2555 | self._edit_macro(args, e.args[0]) | |
2556 | return |
|
2556 | return | |
2557 |
|
2557 | |||
2558 | # do actual editing here |
|
2558 | # do actual editing here | |
2559 | print 'Editing...', |
|
2559 | print 'Editing...', | |
2560 | sys.stdout.flush() |
|
2560 | sys.stdout.flush() | |
2561 | try: |
|
2561 | try: | |
2562 | # Quote filenames that may have spaces in them |
|
2562 | # Quote filenames that may have spaces in them | |
2563 | if ' ' in filename: |
|
2563 | if ' ' in filename: | |
2564 | filename = "'%s'" % filename |
|
2564 | filename = "'%s'" % filename | |
2565 | self.shell.hooks.editor(filename,lineno) |
|
2565 | self.shell.hooks.editor(filename,lineno) | |
2566 | except TryNext: |
|
2566 | except TryNext: | |
2567 | warn('Could not open editor') |
|
2567 | warn('Could not open editor') | |
2568 | return |
|
2568 | return | |
2569 |
|
2569 | |||
2570 | # XXX TODO: should this be generalized for all string vars? |
|
2570 | # XXX TODO: should this be generalized for all string vars? | |
2571 | # For now, this is special-cased to blocks created by cpaste |
|
2571 | # For now, this is special-cased to blocks created by cpaste | |
2572 | if args.strip() == 'pasted_block': |
|
2572 | if args.strip() == 'pasted_block': | |
2573 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
2573 | self.shell.user_ns['pasted_block'] = file_read(filename) | |
2574 |
|
2574 | |||
2575 | if 'x' in opts: # -x prevents actual execution |
|
2575 | if 'x' in opts: # -x prevents actual execution | |
2576 |
|
2576 | |||
2577 | else: |
|
2577 | else: | |
2578 | print 'done. Executing edited code...' |
|
2578 | print 'done. Executing edited code...' | |
2579 | if 'r' in opts: # Untranslated IPython code |
|
2579 | if 'r' in opts: # Untranslated IPython code | |
2580 | self.shell.run_cell(file_read(filename), |
|
2580 | self.shell.run_cell(file_read(filename), | |
2581 | store_history=False) |
|
2581 | store_history=False) | |
2582 | else: |
|
2582 | else: | |
2583 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2583 | self.shell.safe_execfile(filename,self.shell.user_ns, | |
2584 | self.shell.user_ns) |
|
2584 | self.shell.user_ns) | |
2585 |
|
2585 | |||
2586 | if is_temp: |
|
2586 | if is_temp: | |
2587 | try: |
|
2587 | try: | |
2588 | return open(filename).read() |
|
2588 | return open(filename).read() | |
2589 | except IOError,msg: |
|
2589 | except IOError,msg: | |
2590 | if msg.filename == filename: |
|
2590 | if msg.filename == filename: | |
2591 | warn('File not found. Did you forget to save?') |
|
2591 | warn('File not found. Did you forget to save?') | |
2592 | return |
|
2592 | return | |
2593 | else: |
|
2593 | else: | |
2594 | self.shell.showtraceback() |
|
2594 | self.shell.showtraceback() | |
2595 |
|
2595 | |||
2596 | def magic_xmode(self,parameter_s = ''): |
|
2596 | def magic_xmode(self,parameter_s = ''): | |
2597 | """Switch modes for the exception handlers. |
|
2597 | """Switch modes for the exception handlers. | |
2598 |
|
2598 | |||
2599 | Valid modes: Plain, Context and Verbose. |
|
2599 | Valid modes: Plain, Context and Verbose. | |
2600 |
|
2600 | |||
2601 | If called without arguments, acts as a toggle.""" |
|
2601 | If called without arguments, acts as a toggle.""" | |
2602 |
|
2602 | |||
2603 | def xmode_switch_err(name): |
|
2603 | def xmode_switch_err(name): | |
2604 | warn('Error changing %s exception modes.\n%s' % |
|
2604 | warn('Error changing %s exception modes.\n%s' % | |
2605 | (name,sys.exc_info()[1])) |
|
2605 | (name,sys.exc_info()[1])) | |
2606 |
|
2606 | |||
2607 | shell = self.shell |
|
2607 | shell = self.shell | |
2608 | new_mode = parameter_s.strip().capitalize() |
|
2608 | new_mode = parameter_s.strip().capitalize() | |
2609 | try: |
|
2609 | try: | |
2610 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2610 | shell.InteractiveTB.set_mode(mode=new_mode) | |
2611 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2611 | print 'Exception reporting mode:',shell.InteractiveTB.mode | |
2612 | except: |
|
2612 | except: | |
2613 | xmode_switch_err('user') |
|
2613 | xmode_switch_err('user') | |
2614 |
|
2614 | |||
2615 | def magic_colors(self,parameter_s = ''): |
|
2615 | def magic_colors(self,parameter_s = ''): | |
2616 | """Switch color scheme for prompts, info system and exception handlers. |
|
2616 | """Switch color scheme for prompts, info system and exception handlers. | |
2617 |
|
2617 | |||
2618 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2618 | Currently implemented schemes: NoColor, Linux, LightBG. | |
2619 |
|
2619 | |||
2620 | Color scheme names are not case-sensitive. |
|
2620 | Color scheme names are not case-sensitive. | |
2621 |
|
2621 | |||
2622 | Examples |
|
2622 | Examples | |
2623 | -------- |
|
2623 | -------- | |
2624 | To get a plain black and white terminal:: |
|
2624 | To get a plain black and white terminal:: | |
2625 |
|
2625 | |||
2626 | %colors nocolor |
|
2626 | %colors nocolor | |
2627 | """ |
|
2627 | """ | |
2628 |
|
2628 | |||
2629 | def color_switch_err(name): |
|
2629 | def color_switch_err(name): | |
2630 | warn('Error changing %s color schemes.\n%s' % |
|
2630 | warn('Error changing %s color schemes.\n%s' % | |
2631 | (name,sys.exc_info()[1])) |
|
2631 | (name,sys.exc_info()[1])) | |
2632 |
|
2632 | |||
2633 |
|
2633 | |||
2634 | new_scheme = parameter_s.strip() |
|
2634 | new_scheme = parameter_s.strip() | |
2635 | if not new_scheme: |
|
2635 | if not new_scheme: | |
2636 | raise UsageError( |
|
2636 | raise UsageError( | |
2637 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2637 | "%colors: you must specify a color scheme. See '%colors?'") | |
2638 | return |
|
2638 | return | |
2639 | # local shortcut |
|
2639 | # local shortcut | |
2640 | shell = self.shell |
|
2640 | shell = self.shell | |
2641 |
|
2641 | |||
2642 | import IPython.utils.rlineimpl as readline |
|
2642 | import IPython.utils.rlineimpl as readline | |
2643 |
|
2643 | |||
2644 | if not shell.colors_force and \ |
|
2644 | if not shell.colors_force and \ | |
2645 | not readline.have_readline and sys.platform == "win32": |
|
2645 | not readline.have_readline and sys.platform == "win32": | |
2646 | msg = """\ |
|
2646 | msg = """\ | |
2647 | Proper color support under MS Windows requires the pyreadline library. |
|
2647 | Proper color support under MS Windows requires the pyreadline library. | |
2648 | You can find it at: |
|
2648 | You can find it at: | |
2649 | http://ipython.org/pyreadline.html |
|
2649 | http://ipython.org/pyreadline.html | |
2650 | Gary's readline needs the ctypes module, from: |
|
2650 | Gary's readline needs the ctypes module, from: | |
2651 | http://starship.python.net/crew/theller/ctypes |
|
2651 | http://starship.python.net/crew/theller/ctypes | |
2652 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2652 | (Note that ctypes is already part of Python versions 2.5 and newer). | |
2653 |
|
2653 | |||
2654 | Defaulting color scheme to 'NoColor'""" |
|
2654 | Defaulting color scheme to 'NoColor'""" | |
2655 | new_scheme = 'NoColor' |
|
2655 | new_scheme = 'NoColor' | |
2656 | warn(msg) |
|
2656 | warn(msg) | |
2657 |
|
2657 | |||
2658 | # readline option is 0 |
|
2658 | # readline option is 0 | |
2659 | if not shell.colors_force and not shell.has_readline: |
|
2659 | if not shell.colors_force and not shell.has_readline: | |
2660 | new_scheme = 'NoColor' |
|
2660 | new_scheme = 'NoColor' | |
2661 |
|
2661 | |||
2662 | # Set prompt colors |
|
2662 | # Set prompt colors | |
2663 | try: |
|
2663 | try: | |
2664 | shell.prompt_manager.color_scheme = new_scheme |
|
2664 | shell.prompt_manager.color_scheme = new_scheme | |
2665 | except: |
|
2665 | except: | |
2666 | color_switch_err('prompt') |
|
2666 | color_switch_err('prompt') | |
2667 | else: |
|
2667 | else: | |
2668 | shell.colors = \ |
|
2668 | shell.colors = \ | |
2669 | shell.prompt_manager.color_scheme_table.active_scheme_name |
|
2669 | shell.prompt_manager.color_scheme_table.active_scheme_name | |
2670 | # Set exception colors |
|
2670 | # Set exception colors | |
2671 | try: |
|
2671 | try: | |
2672 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2672 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
2673 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2673 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
2674 | except: |
|
2674 | except: | |
2675 | color_switch_err('exception') |
|
2675 | color_switch_err('exception') | |
2676 |
|
2676 | |||
2677 | # Set info (for 'object?') colors |
|
2677 | # Set info (for 'object?') colors | |
2678 | if shell.color_info: |
|
2678 | if shell.color_info: | |
2679 | try: |
|
2679 | try: | |
2680 | shell.inspector.set_active_scheme(new_scheme) |
|
2680 | shell.inspector.set_active_scheme(new_scheme) | |
2681 | except: |
|
2681 | except: | |
2682 | color_switch_err('object inspector') |
|
2682 | color_switch_err('object inspector') | |
2683 | else: |
|
2683 | else: | |
2684 | shell.inspector.set_active_scheme('NoColor') |
|
2684 | shell.inspector.set_active_scheme('NoColor') | |
2685 |
|
2685 | |||
2686 | def magic_pprint(self, parameter_s=''): |
|
2686 | def magic_pprint(self, parameter_s=''): | |
2687 | """Toggle pretty printing on/off.""" |
|
2687 | """Toggle pretty printing on/off.""" | |
2688 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
2688 | ptformatter = self.shell.display_formatter.formatters['text/plain'] | |
2689 | ptformatter.pprint = bool(1 - ptformatter.pprint) |
|
2689 | ptformatter.pprint = bool(1 - ptformatter.pprint) | |
2690 | print 'Pretty printing has been turned', \ |
|
2690 | print 'Pretty printing has been turned', \ | |
2691 | ['OFF','ON'][ptformatter.pprint] |
|
2691 | ['OFF','ON'][ptformatter.pprint] | |
2692 |
|
2692 | |||
2693 | #...................................................................... |
|
2693 | #...................................................................... | |
2694 | # Functions to implement unix shell-type things |
|
2694 | # Functions to implement unix shell-type things | |
2695 |
|
2695 | |||
2696 | @skip_doctest |
|
2696 | @skip_doctest | |
2697 | def magic_alias(self, parameter_s = ''): |
|
2697 | def magic_alias(self, parameter_s = ''): | |
2698 | """Define an alias for a system command. |
|
2698 | """Define an alias for a system command. | |
2699 |
|
2699 | |||
2700 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2700 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
2701 |
|
2701 | |||
2702 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2702 | Then, typing 'alias_name params' will execute the system command 'cmd | |
2703 | params' (from your underlying operating system). |
|
2703 | params' (from your underlying operating system). | |
2704 |
|
2704 | |||
2705 | Aliases have lower precedence than magic functions and Python normal |
|
2705 | Aliases have lower precedence than magic functions and Python normal | |
2706 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2706 | variables, so if 'foo' is both a Python variable and an alias, the | |
2707 | alias can not be executed until 'del foo' removes the Python variable. |
|
2707 | alias can not be executed until 'del foo' removes the Python variable. | |
2708 |
|
2708 | |||
2709 | You can use the %l specifier in an alias definition to represent the |
|
2709 | You can use the %l specifier in an alias definition to represent the | |
2710 | whole line when the alias is called. For example:: |
|
2710 | whole line when the alias is called. For example:: | |
2711 |
|
2711 | |||
2712 | In [2]: alias bracket echo "Input in brackets: <%l>" |
|
2712 | In [2]: alias bracket echo "Input in brackets: <%l>" | |
2713 | In [3]: bracket hello world |
|
2713 | In [3]: bracket hello world | |
2714 | Input in brackets: <hello world> |
|
2714 | Input in brackets: <hello world> | |
2715 |
|
2715 | |||
2716 | You can also define aliases with parameters using %s specifiers (one |
|
2716 | You can also define aliases with parameters using %s specifiers (one | |
2717 | per parameter):: |
|
2717 | per parameter):: | |
2718 |
|
2718 | |||
2719 | In [1]: alias parts echo first %s second %s |
|
2719 | In [1]: alias parts echo first %s second %s | |
2720 | In [2]: %parts A B |
|
2720 | In [2]: %parts A B | |
2721 | first A second B |
|
2721 | first A second B | |
2722 | In [3]: %parts A |
|
2722 | In [3]: %parts A | |
2723 | Incorrect number of arguments: 2 expected. |
|
2723 | Incorrect number of arguments: 2 expected. | |
2724 | parts is an alias to: 'echo first %s second %s' |
|
2724 | parts is an alias to: 'echo first %s second %s' | |
2725 |
|
2725 | |||
2726 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2726 | Note that %l and %s are mutually exclusive. You can only use one or | |
2727 | the other in your aliases. |
|
2727 | the other in your aliases. | |
2728 |
|
2728 | |||
2729 | Aliases expand Python variables just like system calls using ! or !! |
|
2729 | Aliases expand Python variables just like system calls using ! or !! | |
2730 | do: all expressions prefixed with '$' get expanded. For details of |
|
2730 | do: all expressions prefixed with '$' get expanded. For details of | |
2731 | the semantic rules, see PEP-215: |
|
2731 | the semantic rules, see PEP-215: | |
2732 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2732 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
2733 | IPython for variable expansion. If you want to access a true shell |
|
2733 | IPython for variable expansion. If you want to access a true shell | |
2734 | variable, an extra $ is necessary to prevent its expansion by |
|
2734 | variable, an extra $ is necessary to prevent its expansion by | |
2735 | IPython:: |
|
2735 | IPython:: | |
2736 |
|
2736 | |||
2737 | In [6]: alias show echo |
|
2737 | In [6]: alias show echo | |
2738 | In [7]: PATH='A Python string' |
|
2738 | In [7]: PATH='A Python string' | |
2739 | In [8]: show $PATH |
|
2739 | In [8]: show $PATH | |
2740 | A Python string |
|
2740 | A Python string | |
2741 | In [9]: show $$PATH |
|
2741 | In [9]: show $$PATH | |
2742 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2742 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
2743 |
|
2743 | |||
2744 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2744 | You can use the alias facility to acess all of $PATH. See the %rehash | |
2745 | and %rehashx functions, which automatically create aliases for the |
|
2745 | and %rehashx functions, which automatically create aliases for the | |
2746 | contents of your $PATH. |
|
2746 | contents of your $PATH. | |
2747 |
|
2747 | |||
2748 | If called with no parameters, %alias prints the current alias table.""" |
|
2748 | If called with no parameters, %alias prints the current alias table.""" | |
2749 |
|
2749 | |||
2750 | par = parameter_s.strip() |
|
2750 | par = parameter_s.strip() | |
2751 | if not par: |
|
2751 | if not par: | |
2752 | stored = self.db.get('stored_aliases', {} ) |
|
2752 | stored = self.db.get('stored_aliases', {} ) | |
2753 | aliases = sorted(self.shell.alias_manager.aliases) |
|
2753 | aliases = sorted(self.shell.alias_manager.aliases) | |
2754 | # for k, v in stored: |
|
2754 | # for k, v in stored: | |
2755 | # atab.append(k, v[0]) |
|
2755 | # atab.append(k, v[0]) | |
2756 |
|
2756 | |||
2757 | print "Total number of aliases:", len(aliases) |
|
2757 | print "Total number of aliases:", len(aliases) | |
2758 | sys.stdout.flush() |
|
2758 | sys.stdout.flush() | |
2759 | return aliases |
|
2759 | return aliases | |
2760 |
|
2760 | |||
2761 | # Now try to define a new one |
|
2761 | # Now try to define a new one | |
2762 | try: |
|
2762 | try: | |
2763 | alias,cmd = par.split(None, 1) |
|
2763 | alias,cmd = par.split(None, 1) | |
2764 | except: |
|
2764 | except: | |
2765 | print oinspect.getdoc(self.magic_alias) |
|
2765 | print oinspect.getdoc(self.magic_alias) | |
2766 | else: |
|
2766 | else: | |
2767 | self.shell.alias_manager.soft_define_alias(alias, cmd) |
|
2767 | self.shell.alias_manager.soft_define_alias(alias, cmd) | |
2768 | # end magic_alias |
|
2768 | # end magic_alias | |
2769 |
|
2769 | |||
2770 | def magic_unalias(self, parameter_s = ''): |
|
2770 | def magic_unalias(self, parameter_s = ''): | |
2771 | """Remove an alias""" |
|
2771 | """Remove an alias""" | |
2772 |
|
2772 | |||
2773 | aname = parameter_s.strip() |
|
2773 | aname = parameter_s.strip() | |
2774 | self.shell.alias_manager.undefine_alias(aname) |
|
2774 | self.shell.alias_manager.undefine_alias(aname) | |
2775 | stored = self.db.get('stored_aliases', {} ) |
|
2775 | stored = self.db.get('stored_aliases', {} ) | |
2776 | if aname in stored: |
|
2776 | if aname in stored: | |
2777 | print "Removing %stored alias",aname |
|
2777 | print "Removing %stored alias",aname | |
2778 | del stored[aname] |
|
2778 | del stored[aname] | |
2779 | self.db['stored_aliases'] = stored |
|
2779 | self.db['stored_aliases'] = stored | |
2780 |
|
2780 | |||
2781 | def magic_rehashx(self, parameter_s = ''): |
|
2781 | def magic_rehashx(self, parameter_s = ''): | |
2782 | """Update the alias table with all executable files in $PATH. |
|
2782 | """Update the alias table with all executable files in $PATH. | |
2783 |
|
2783 | |||
2784 | This version explicitly checks that every entry in $PATH is a file |
|
2784 | This version explicitly checks that every entry in $PATH is a file | |
2785 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2785 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2786 |
|
2786 | |||
2787 | Under Windows, it checks executability as a match against a |
|
2787 | Under Windows, it checks executability as a match against a | |
2788 | '|'-separated string of extensions, stored in the IPython config |
|
2788 | '|'-separated string of extensions, stored in the IPython config | |
2789 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2789 | variable win_exec_ext. This defaults to 'exe|com|bat'. | |
2790 |
|
2790 | |||
2791 | This function also resets the root module cache of module completer, |
|
2791 | This function also resets the root module cache of module completer, | |
2792 | used on slow filesystems. |
|
2792 | used on slow filesystems. | |
2793 | """ |
|
2793 | """ | |
2794 | from IPython.core.alias import InvalidAliasError |
|
2794 | from IPython.core.alias import InvalidAliasError | |
2795 |
|
2795 | |||
2796 | # for the benefit of module completer in ipy_completers.py |
|
2796 | # for the benefit of module completer in ipy_completers.py | |
2797 | del self.shell.db['rootmodules'] |
|
2797 | del self.shell.db['rootmodules'] | |
2798 |
|
2798 | |||
2799 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2799 | path = [os.path.abspath(os.path.expanduser(p)) for p in | |
2800 | os.environ.get('PATH','').split(os.pathsep)] |
|
2800 | os.environ.get('PATH','').split(os.pathsep)] | |
2801 | path = filter(os.path.isdir,path) |
|
2801 | path = filter(os.path.isdir,path) | |
2802 |
|
2802 | |||
2803 | syscmdlist = [] |
|
2803 | syscmdlist = [] | |
2804 | # Now define isexec in a cross platform manner. |
|
2804 | # Now define isexec in a cross platform manner. | |
2805 | if os.name == 'posix': |
|
2805 | if os.name == 'posix': | |
2806 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2806 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2807 | os.access(fname,os.X_OK) |
|
2807 | os.access(fname,os.X_OK) | |
2808 | else: |
|
2808 | else: | |
2809 | try: |
|
2809 | try: | |
2810 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2810 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2811 | except KeyError: |
|
2811 | except KeyError: | |
2812 | winext = 'exe|com|bat|py' |
|
2812 | winext = 'exe|com|bat|py' | |
2813 | if 'py' not in winext: |
|
2813 | if 'py' not in winext: | |
2814 | winext += '|py' |
|
2814 | winext += '|py' | |
2815 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2815 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2816 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2816 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2817 | savedir = os.getcwdu() |
|
2817 | savedir = os.getcwdu() | |
2818 |
|
2818 | |||
2819 | # Now walk the paths looking for executables to alias. |
|
2819 | # Now walk the paths looking for executables to alias. | |
2820 | try: |
|
2820 | try: | |
2821 | # write the whole loop for posix/Windows so we don't have an if in |
|
2821 | # write the whole loop for posix/Windows so we don't have an if in | |
2822 | # the innermost part |
|
2822 | # the innermost part | |
2823 | if os.name == 'posix': |
|
2823 | if os.name == 'posix': | |
2824 | for pdir in path: |
|
2824 | for pdir in path: | |
2825 | os.chdir(pdir) |
|
2825 | os.chdir(pdir) | |
2826 | for ff in os.listdir(pdir): |
|
2826 | for ff in os.listdir(pdir): | |
2827 | if isexec(ff): |
|
2827 | if isexec(ff): | |
2828 | try: |
|
2828 | try: | |
2829 | # Removes dots from the name since ipython |
|
2829 | # Removes dots from the name since ipython | |
2830 | # will assume names with dots to be python. |
|
2830 | # will assume names with dots to be python. | |
2831 | self.shell.alias_manager.define_alias( |
|
2831 | self.shell.alias_manager.define_alias( | |
2832 | ff.replace('.',''), ff) |
|
2832 | ff.replace('.',''), ff) | |
2833 | except InvalidAliasError: |
|
2833 | except InvalidAliasError: | |
2834 | pass |
|
2834 | pass | |
2835 | else: |
|
2835 | else: | |
2836 | syscmdlist.append(ff) |
|
2836 | syscmdlist.append(ff) | |
2837 | else: |
|
2837 | else: | |
2838 | no_alias = self.shell.alias_manager.no_alias |
|
2838 | no_alias = self.shell.alias_manager.no_alias | |
2839 | for pdir in path: |
|
2839 | for pdir in path: | |
2840 | os.chdir(pdir) |
|
2840 | os.chdir(pdir) | |
2841 | for ff in os.listdir(pdir): |
|
2841 | for ff in os.listdir(pdir): | |
2842 | base, ext = os.path.splitext(ff) |
|
2842 | base, ext = os.path.splitext(ff) | |
2843 | if isexec(ff) and base.lower() not in no_alias: |
|
2843 | if isexec(ff) and base.lower() not in no_alias: | |
2844 | if ext.lower() == '.exe': |
|
2844 | if ext.lower() == '.exe': | |
2845 | ff = base |
|
2845 | ff = base | |
2846 | try: |
|
2846 | try: | |
2847 | # Removes dots from the name since ipython |
|
2847 | # Removes dots from the name since ipython | |
2848 | # will assume names with dots to be python. |
|
2848 | # will assume names with dots to be python. | |
2849 | self.shell.alias_manager.define_alias( |
|
2849 | self.shell.alias_manager.define_alias( | |
2850 | base.lower().replace('.',''), ff) |
|
2850 | base.lower().replace('.',''), ff) | |
2851 | except InvalidAliasError: |
|
2851 | except InvalidAliasError: | |
2852 | pass |
|
2852 | pass | |
2853 | syscmdlist.append(ff) |
|
2853 | syscmdlist.append(ff) | |
2854 | self.shell.db['syscmdlist'] = syscmdlist |
|
2854 | self.shell.db['syscmdlist'] = syscmdlist | |
2855 | finally: |
|
2855 | finally: | |
2856 | os.chdir(savedir) |
|
2856 | os.chdir(savedir) | |
2857 |
|
2857 | |||
2858 | @skip_doctest |
|
2858 | @skip_doctest | |
2859 | def magic_pwd(self, parameter_s = ''): |
|
2859 | def magic_pwd(self, parameter_s = ''): | |
2860 | """Return the current working directory path. |
|
2860 | """Return the current working directory path. | |
2861 |
|
2861 | |||
2862 | Examples |
|
2862 | Examples | |
2863 | -------- |
|
2863 | -------- | |
2864 | :: |
|
2864 | :: | |
2865 |
|
2865 | |||
2866 | In [9]: pwd |
|
2866 | In [9]: pwd | |
2867 | Out[9]: '/home/tsuser/sprint/ipython' |
|
2867 | Out[9]: '/home/tsuser/sprint/ipython' | |
2868 | """ |
|
2868 | """ | |
2869 | return os.getcwdu() |
|
2869 | return os.getcwdu() | |
2870 |
|
2870 | |||
2871 | @skip_doctest |
|
2871 | @skip_doctest | |
2872 | def magic_cd(self, parameter_s=''): |
|
2872 | def magic_cd(self, parameter_s=''): | |
2873 | """Change the current working directory. |
|
2873 | """Change the current working directory. | |
2874 |
|
2874 | |||
2875 | This command automatically maintains an internal list of directories |
|
2875 | This command automatically maintains an internal list of directories | |
2876 | you visit during your IPython session, in the variable _dh. The |
|
2876 | you visit during your IPython session, in the variable _dh. The | |
2877 | command %dhist shows this history nicely formatted. You can also |
|
2877 | command %dhist shows this history nicely formatted. You can also | |
2878 | do 'cd -<tab>' to see directory history conveniently. |
|
2878 | do 'cd -<tab>' to see directory history conveniently. | |
2879 |
|
2879 | |||
2880 | Usage: |
|
2880 | Usage: | |
2881 |
|
2881 | |||
2882 | cd 'dir': changes to directory 'dir'. |
|
2882 | cd 'dir': changes to directory 'dir'. | |
2883 |
|
2883 | |||
2884 | cd -: changes to the last visited directory. |
|
2884 | cd -: changes to the last visited directory. | |
2885 |
|
2885 | |||
2886 | cd -<n>: changes to the n-th directory in the directory history. |
|
2886 | cd -<n>: changes to the n-th directory in the directory history. | |
2887 |
|
2887 | |||
2888 | cd --foo: change to directory that matches 'foo' in history |
|
2888 | cd --foo: change to directory that matches 'foo' in history | |
2889 |
|
2889 | |||
2890 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2890 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
2891 | (note: cd <bookmark_name> is enough if there is no |
|
2891 | (note: cd <bookmark_name> is enough if there is no | |
2892 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2892 | directory <bookmark_name>, but a bookmark with the name exists.) | |
2893 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2893 | 'cd -b <tab>' allows you to tab-complete bookmark names. | |
2894 |
|
2894 | |||
2895 | Options: |
|
2895 | Options: | |
2896 |
|
2896 | |||
2897 | -q: quiet. Do not print the working directory after the cd command is |
|
2897 | -q: quiet. Do not print the working directory after the cd command is | |
2898 | executed. By default IPython's cd command does print this directory, |
|
2898 | executed. By default IPython's cd command does print this directory, | |
2899 | since the default prompts do not display path information. |
|
2899 | since the default prompts do not display path information. | |
2900 |
|
2900 | |||
2901 | Note that !cd doesn't work for this purpose because the shell where |
|
2901 | Note that !cd doesn't work for this purpose because the shell where | |
2902 | !command runs is immediately discarded after executing 'command'. |
|
2902 | !command runs is immediately discarded after executing 'command'. | |
2903 |
|
2903 | |||
2904 | Examples |
|
2904 | Examples | |
2905 | -------- |
|
2905 | -------- | |
2906 | :: |
|
2906 | :: | |
2907 |
|
2907 | |||
2908 | In [10]: cd parent/child |
|
2908 | In [10]: cd parent/child | |
2909 | /home/tsuser/parent/child |
|
2909 | /home/tsuser/parent/child | |
2910 | """ |
|
2910 | """ | |
2911 |
|
2911 | |||
2912 | parameter_s = parameter_s.strip() |
|
2912 | parameter_s = parameter_s.strip() | |
2913 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2913 | #bkms = self.shell.persist.get("bookmarks",{}) | |
2914 |
|
2914 | |||
2915 | oldcwd = os.getcwdu() |
|
2915 | oldcwd = os.getcwdu() | |
2916 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2916 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
2917 | # jump in directory history by number |
|
2917 | # jump in directory history by number | |
2918 | if numcd: |
|
2918 | if numcd: | |
2919 | nn = int(numcd.group(2)) |
|
2919 | nn = int(numcd.group(2)) | |
2920 | try: |
|
2920 | try: | |
2921 | ps = self.shell.user_ns['_dh'][nn] |
|
2921 | ps = self.shell.user_ns['_dh'][nn] | |
2922 | except IndexError: |
|
2922 | except IndexError: | |
2923 | print 'The requested directory does not exist in history.' |
|
2923 | print 'The requested directory does not exist in history.' | |
2924 | return |
|
2924 | return | |
2925 | else: |
|
2925 | else: | |
2926 | opts = {} |
|
2926 | opts = {} | |
2927 | elif parameter_s.startswith('--'): |
|
2927 | elif parameter_s.startswith('--'): | |
2928 | ps = None |
|
2928 | ps = None | |
2929 | fallback = None |
|
2929 | fallback = None | |
2930 | pat = parameter_s[2:] |
|
2930 | pat = parameter_s[2:] | |
2931 | dh = self.shell.user_ns['_dh'] |
|
2931 | dh = self.shell.user_ns['_dh'] | |
2932 | # first search only by basename (last component) |
|
2932 | # first search only by basename (last component) | |
2933 | for ent in reversed(dh): |
|
2933 | for ent in reversed(dh): | |
2934 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
2934 | if pat in os.path.basename(ent) and os.path.isdir(ent): | |
2935 | ps = ent |
|
2935 | ps = ent | |
2936 | break |
|
2936 | break | |
2937 |
|
2937 | |||
2938 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
2938 | if fallback is None and pat in ent and os.path.isdir(ent): | |
2939 | fallback = ent |
|
2939 | fallback = ent | |
2940 |
|
2940 | |||
2941 | # if we have no last part match, pick the first full path match |
|
2941 | # if we have no last part match, pick the first full path match | |
2942 | if ps is None: |
|
2942 | if ps is None: | |
2943 | ps = fallback |
|
2943 | ps = fallback | |
2944 |
|
2944 | |||
2945 | if ps is None: |
|
2945 | if ps is None: | |
2946 | print "No matching entry in directory history" |
|
2946 | print "No matching entry in directory history" | |
2947 | return |
|
2947 | return | |
2948 | else: |
|
2948 | else: | |
2949 | opts = {} |
|
2949 | opts = {} | |
2950 |
|
2950 | |||
2951 |
|
2951 | |||
2952 | else: |
|
2952 | else: | |
2953 | #turn all non-space-escaping backslashes to slashes, |
|
2953 | #turn all non-space-escaping backslashes to slashes, | |
2954 | # for c:\windows\directory\names\ |
|
2954 | # for c:\windows\directory\names\ | |
2955 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2955 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) | |
2956 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2956 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
2957 | # jump to previous |
|
2957 | # jump to previous | |
2958 | if ps == '-': |
|
2958 | if ps == '-': | |
2959 | try: |
|
2959 | try: | |
2960 | ps = self.shell.user_ns['_dh'][-2] |
|
2960 | ps = self.shell.user_ns['_dh'][-2] | |
2961 | except IndexError: |
|
2961 | except IndexError: | |
2962 | raise UsageError('%cd -: No previous directory to change to.') |
|
2962 | raise UsageError('%cd -: No previous directory to change to.') | |
2963 | # jump to bookmark if needed |
|
2963 | # jump to bookmark if needed | |
2964 | else: |
|
2964 | else: | |
2965 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2965 | if not os.path.isdir(ps) or opts.has_key('b'): | |
2966 | bkms = self.db.get('bookmarks', {}) |
|
2966 | bkms = self.db.get('bookmarks', {}) | |
2967 |
|
2967 | |||
2968 | if bkms.has_key(ps): |
|
2968 | if bkms.has_key(ps): | |
2969 | target = bkms[ps] |
|
2969 | target = bkms[ps] | |
2970 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2970 | print '(bookmark:%s) -> %s' % (ps,target) | |
2971 | ps = target |
|
2971 | ps = target | |
2972 | else: |
|
2972 | else: | |
2973 | if opts.has_key('b'): |
|
2973 | if opts.has_key('b'): | |
2974 | raise UsageError("Bookmark '%s' not found. " |
|
2974 | raise UsageError("Bookmark '%s' not found. " | |
2975 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2975 | "Use '%%bookmark -l' to see your bookmarks." % ps) | |
2976 |
|
2976 | |||
2977 | # strip extra quotes on Windows, because os.chdir doesn't like them |
|
2977 | # strip extra quotes on Windows, because os.chdir doesn't like them | |
2978 | ps = unquote_filename(ps) |
|
2978 | ps = unquote_filename(ps) | |
2979 | # at this point ps should point to the target dir |
|
2979 | # at this point ps should point to the target dir | |
2980 | if ps: |
|
2980 | if ps: | |
2981 | try: |
|
2981 | try: | |
2982 | os.chdir(os.path.expanduser(ps)) |
|
2982 | os.chdir(os.path.expanduser(ps)) | |
2983 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2983 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
2984 | set_term_title('IPython: ' + abbrev_cwd()) |
|
2984 | set_term_title('IPython: ' + abbrev_cwd()) | |
2985 | except OSError: |
|
2985 | except OSError: | |
2986 | print sys.exc_info()[1] |
|
2986 | print sys.exc_info()[1] | |
2987 | else: |
|
2987 | else: | |
2988 | cwd = os.getcwdu() |
|
2988 | cwd = os.getcwdu() | |
2989 | dhist = self.shell.user_ns['_dh'] |
|
2989 | dhist = self.shell.user_ns['_dh'] | |
2990 | if oldcwd != cwd: |
|
2990 | if oldcwd != cwd: | |
2991 | dhist.append(cwd) |
|
2991 | dhist.append(cwd) | |
2992 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2992 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2993 |
|
2993 | |||
2994 | else: |
|
2994 | else: | |
2995 | os.chdir(self.shell.home_dir) |
|
2995 | os.chdir(self.shell.home_dir) | |
2996 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2996 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
2997 | set_term_title('IPython: ' + '~') |
|
2997 | set_term_title('IPython: ' + '~') | |
2998 | cwd = os.getcwdu() |
|
2998 | cwd = os.getcwdu() | |
2999 | dhist = self.shell.user_ns['_dh'] |
|
2999 | dhist = self.shell.user_ns['_dh'] | |
3000 |
|
3000 | |||
3001 | if oldcwd != cwd: |
|
3001 | if oldcwd != cwd: | |
3002 | dhist.append(cwd) |
|
3002 | dhist.append(cwd) | |
3003 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
3003 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
3004 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
3004 | if not 'q' in opts and self.shell.user_ns['_dh']: | |
3005 | print self.shell.user_ns['_dh'][-1] |
|
3005 | print self.shell.user_ns['_dh'][-1] | |
3006 |
|
3006 | |||
3007 |
|
3007 | |||
3008 | def magic_env(self, parameter_s=''): |
|
3008 | def magic_env(self, parameter_s=''): | |
3009 | """List environment variables.""" |
|
3009 | """List environment variables.""" | |
3010 |
|
3010 | |||
3011 | return dict(os.environ) |
|
3011 | return dict(os.environ) | |
3012 |
|
3012 | |||
3013 | def magic_pushd(self, parameter_s=''): |
|
3013 | def magic_pushd(self, parameter_s=''): | |
3014 | """Place the current dir on stack and change directory. |
|
3014 | """Place the current dir on stack and change directory. | |
3015 |
|
3015 | |||
3016 | Usage:\\ |
|
3016 | Usage:\\ | |
3017 | %pushd ['dirname'] |
|
3017 | %pushd ['dirname'] | |
3018 | """ |
|
3018 | """ | |
3019 |
|
3019 | |||
3020 | dir_s = self.shell.dir_stack |
|
3020 | dir_s = self.shell.dir_stack | |
3021 | tgt = os.path.expanduser(unquote_filename(parameter_s)) |
|
3021 | tgt = os.path.expanduser(unquote_filename(parameter_s)) | |
3022 | cwd = os.getcwdu().replace(self.home_dir,'~') |
|
3022 | cwd = os.getcwdu().replace(self.home_dir,'~') | |
3023 | if tgt: |
|
3023 | if tgt: | |
3024 | self.magic_cd(parameter_s) |
|
3024 | self.magic_cd(parameter_s) | |
3025 | dir_s.insert(0,cwd) |
|
3025 | dir_s.insert(0,cwd) | |
3026 | return self.magic_dirs() |
|
3026 | return self.magic_dirs() | |
3027 |
|
3027 | |||
3028 | def magic_popd(self, parameter_s=''): |
|
3028 | def magic_popd(self, parameter_s=''): | |
3029 | """Change to directory popped off the top of the stack. |
|
3029 | """Change to directory popped off the top of the stack. | |
3030 | """ |
|
3030 | """ | |
3031 | if not self.shell.dir_stack: |
|
3031 | if not self.shell.dir_stack: | |
3032 | raise UsageError("%popd on empty stack") |
|
3032 | raise UsageError("%popd on empty stack") | |
3033 | top = self.shell.dir_stack.pop(0) |
|
3033 | top = self.shell.dir_stack.pop(0) | |
3034 | self.magic_cd(top) |
|
3034 | self.magic_cd(top) | |
3035 | print "popd ->",top |
|
3035 | print "popd ->",top | |
3036 |
|
3036 | |||
3037 | def magic_dirs(self, parameter_s=''): |
|
3037 | def magic_dirs(self, parameter_s=''): | |
3038 | """Return the current directory stack.""" |
|
3038 | """Return the current directory stack.""" | |
3039 |
|
3039 | |||
3040 | return self.shell.dir_stack |
|
3040 | return self.shell.dir_stack | |
3041 |
|
3041 | |||
3042 | def magic_dhist(self, parameter_s=''): |
|
3042 | def magic_dhist(self, parameter_s=''): | |
3043 | """Print your history of visited directories. |
|
3043 | """Print your history of visited directories. | |
3044 |
|
3044 | |||
3045 | %dhist -> print full history\\ |
|
3045 | %dhist -> print full history\\ | |
3046 | %dhist n -> print last n entries only\\ |
|
3046 | %dhist n -> print last n entries only\\ | |
3047 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
3047 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
3048 |
|
3048 | |||
3049 | This history is automatically maintained by the %cd command, and |
|
3049 | This history is automatically maintained by the %cd command, and | |
3050 | always available as the global list variable _dh. You can use %cd -<n> |
|
3050 | always available as the global list variable _dh. You can use %cd -<n> | |
3051 | to go to directory number <n>. |
|
3051 | to go to directory number <n>. | |
3052 |
|
3052 | |||
3053 | Note that most of time, you should view directory history by entering |
|
3053 | Note that most of time, you should view directory history by entering | |
3054 | cd -<TAB>. |
|
3054 | cd -<TAB>. | |
3055 |
|
3055 | |||
3056 | """ |
|
3056 | """ | |
3057 |
|
3057 | |||
3058 | dh = self.shell.user_ns['_dh'] |
|
3058 | dh = self.shell.user_ns['_dh'] | |
3059 | if parameter_s: |
|
3059 | if parameter_s: | |
3060 | try: |
|
3060 | try: | |
3061 | args = map(int,parameter_s.split()) |
|
3061 | args = map(int,parameter_s.split()) | |
3062 | except: |
|
3062 | except: | |
3063 | self.arg_err(Magic.magic_dhist) |
|
3063 | self.arg_err(Magic.magic_dhist) | |
3064 | return |
|
3064 | return | |
3065 | if len(args) == 1: |
|
3065 | if len(args) == 1: | |
3066 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
3066 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
3067 | elif len(args) == 2: |
|
3067 | elif len(args) == 2: | |
3068 | ini,fin = args |
|
3068 | ini,fin = args | |
3069 | else: |
|
3069 | else: | |
3070 | self.arg_err(Magic.magic_dhist) |
|
3070 | self.arg_err(Magic.magic_dhist) | |
3071 | return |
|
3071 | return | |
3072 | else: |
|
3072 | else: | |
3073 | ini,fin = 0,len(dh) |
|
3073 | ini,fin = 0,len(dh) | |
3074 | nlprint(dh, |
|
3074 | nlprint(dh, | |
3075 | header = 'Directory history (kept in _dh)', |
|
3075 | header = 'Directory history (kept in _dh)', | |
3076 | start=ini,stop=fin) |
|
3076 | start=ini,stop=fin) | |
3077 |
|
3077 | |||
3078 | @skip_doctest |
|
3078 | @skip_doctest | |
3079 | def magic_sc(self, parameter_s=''): |
|
3079 | def magic_sc(self, parameter_s=''): | |
3080 | """Shell capture - execute a shell command and capture its output. |
|
3080 | """Shell capture - execute a shell command and capture its output. | |
3081 |
|
3081 | |||
3082 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
3082 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
3083 |
|
3083 | |||
3084 | You should use the form 'var = !command' instead. Example: |
|
3084 | You should use the form 'var = !command' instead. Example: | |
3085 |
|
3085 | |||
3086 | "%sc -l myfiles = ls ~" should now be written as |
|
3086 | "%sc -l myfiles = ls ~" should now be written as | |
3087 |
|
3087 | |||
3088 | "myfiles = !ls ~" |
|
3088 | "myfiles = !ls ~" | |
3089 |
|
3089 | |||
3090 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
3090 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
3091 | below. |
|
3091 | below. | |
3092 |
|
3092 | |||
3093 | -- |
|
3093 | -- | |
3094 | %sc [options] varname=command |
|
3094 | %sc [options] varname=command | |
3095 |
|
3095 | |||
3096 | IPython will run the given command using commands.getoutput(), and |
|
3096 | IPython will run the given command using commands.getoutput(), and | |
3097 | will then update the user's interactive namespace with a variable |
|
3097 | will then update the user's interactive namespace with a variable | |
3098 | called varname, containing the value of the call. Your command can |
|
3098 | called varname, containing the value of the call. Your command can | |
3099 | contain shell wildcards, pipes, etc. |
|
3099 | contain shell wildcards, pipes, etc. | |
3100 |
|
3100 | |||
3101 | The '=' sign in the syntax is mandatory, and the variable name you |
|
3101 | The '=' sign in the syntax is mandatory, and the variable name you | |
3102 | supply must follow Python's standard conventions for valid names. |
|
3102 | supply must follow Python's standard conventions for valid names. | |
3103 |
|
3103 | |||
3104 | (A special format without variable name exists for internal use) |
|
3104 | (A special format without variable name exists for internal use) | |
3105 |
|
3105 | |||
3106 | Options: |
|
3106 | Options: | |
3107 |
|
3107 | |||
3108 | -l: list output. Split the output on newlines into a list before |
|
3108 | -l: list output. Split the output on newlines into a list before | |
3109 | assigning it to the given variable. By default the output is stored |
|
3109 | assigning it to the given variable. By default the output is stored | |
3110 | as a single string. |
|
3110 | as a single string. | |
3111 |
|
3111 | |||
3112 | -v: verbose. Print the contents of the variable. |
|
3112 | -v: verbose. Print the contents of the variable. | |
3113 |
|
3113 | |||
3114 | In most cases you should not need to split as a list, because the |
|
3114 | In most cases you should not need to split as a list, because the | |
3115 | returned value is a special type of string which can automatically |
|
3115 | returned value is a special type of string which can automatically | |
3116 | provide its contents either as a list (split on newlines) or as a |
|
3116 | provide its contents either as a list (split on newlines) or as a | |
3117 | space-separated string. These are convenient, respectively, either |
|
3117 | space-separated string. These are convenient, respectively, either | |
3118 | for sequential processing or to be passed to a shell command. |
|
3118 | for sequential processing or to be passed to a shell command. | |
3119 |
|
3119 | |||
3120 | For example:: |
|
3120 | For example:: | |
3121 |
|
3121 | |||
3122 | # Capture into variable a |
|
3122 | # Capture into variable a | |
3123 | In [1]: sc a=ls *py |
|
3123 | In [1]: sc a=ls *py | |
3124 |
|
3124 | |||
3125 | # a is a string with embedded newlines |
|
3125 | # a is a string with embedded newlines | |
3126 | In [2]: a |
|
3126 | In [2]: a | |
3127 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
3127 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' | |
3128 |
|
3128 | |||
3129 | # which can be seen as a list: |
|
3129 | # which can be seen as a list: | |
3130 | In [3]: a.l |
|
3130 | In [3]: a.l | |
3131 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
3131 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] | |
3132 |
|
3132 | |||
3133 | # or as a whitespace-separated string: |
|
3133 | # or as a whitespace-separated string: | |
3134 | In [4]: a.s |
|
3134 | In [4]: a.s | |
3135 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
3135 | Out[4]: 'setup.py win32_manual_post_install.py' | |
3136 |
|
3136 | |||
3137 | # a.s is useful to pass as a single command line: |
|
3137 | # a.s is useful to pass as a single command line: | |
3138 | In [5]: !wc -l $a.s |
|
3138 | In [5]: !wc -l $a.s | |
3139 | 146 setup.py |
|
3139 | 146 setup.py | |
3140 | 130 win32_manual_post_install.py |
|
3140 | 130 win32_manual_post_install.py | |
3141 | 276 total |
|
3141 | 276 total | |
3142 |
|
3142 | |||
3143 | # while the list form is useful to loop over: |
|
3143 | # while the list form is useful to loop over: | |
3144 | In [6]: for f in a.l: |
|
3144 | In [6]: for f in a.l: | |
3145 | ...: !wc -l $f |
|
3145 | ...: !wc -l $f | |
3146 | ...: |
|
3146 | ...: | |
3147 | 146 setup.py |
|
3147 | 146 setup.py | |
3148 | 130 win32_manual_post_install.py |
|
3148 | 130 win32_manual_post_install.py | |
3149 |
|
3149 | |||
3150 | Similarly, the lists returned by the -l option are also special, in |
|
3150 | Similarly, the lists returned by the -l option are also special, in | |
3151 | the sense that you can equally invoke the .s attribute on them to |
|
3151 | the sense that you can equally invoke the .s attribute on them to | |
3152 | automatically get a whitespace-separated string from their contents:: |
|
3152 | automatically get a whitespace-separated string from their contents:: | |
3153 |
|
3153 | |||
3154 | In [7]: sc -l b=ls *py |
|
3154 | In [7]: sc -l b=ls *py | |
3155 |
|
3155 | |||
3156 | In [8]: b |
|
3156 | In [8]: b | |
3157 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
3157 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] | |
3158 |
|
3158 | |||
3159 | In [9]: b.s |
|
3159 | In [9]: b.s | |
3160 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
3160 | Out[9]: 'setup.py win32_manual_post_install.py' | |
3161 |
|
3161 | |||
3162 | In summary, both the lists and strings used for output capture have |
|
3162 | In summary, both the lists and strings used for output capture have | |
3163 | the following special attributes:: |
|
3163 | the following special attributes:: | |
3164 |
|
3164 | |||
3165 | .l (or .list) : value as list. |
|
3165 | .l (or .list) : value as list. | |
3166 | .n (or .nlstr): value as newline-separated string. |
|
3166 | .n (or .nlstr): value as newline-separated string. | |
3167 | .s (or .spstr): value as space-separated string. |
|
3167 | .s (or .spstr): value as space-separated string. | |
3168 | """ |
|
3168 | """ | |
3169 |
|
3169 | |||
3170 | opts,args = self.parse_options(parameter_s,'lv') |
|
3170 | opts,args = self.parse_options(parameter_s,'lv') | |
3171 | # Try to get a variable name and command to run |
|
3171 | # Try to get a variable name and command to run | |
3172 | try: |
|
3172 | try: | |
3173 | # the variable name must be obtained from the parse_options |
|
3173 | # the variable name must be obtained from the parse_options | |
3174 | # output, which uses shlex.split to strip options out. |
|
3174 | # output, which uses shlex.split to strip options out. | |
3175 | var,_ = args.split('=',1) |
|
3175 | var,_ = args.split('=',1) | |
3176 | var = var.strip() |
|
3176 | var = var.strip() | |
3177 | # But the command has to be extracted from the original input |
|
3177 | # But the command has to be extracted from the original input | |
3178 | # parameter_s, not on what parse_options returns, to avoid the |
|
3178 | # parameter_s, not on what parse_options returns, to avoid the | |
3179 | # quote stripping which shlex.split performs on it. |
|
3179 | # quote stripping which shlex.split performs on it. | |
3180 | _,cmd = parameter_s.split('=',1) |
|
3180 | _,cmd = parameter_s.split('=',1) | |
3181 | except ValueError: |
|
3181 | except ValueError: | |
3182 | var,cmd = '','' |
|
3182 | var,cmd = '','' | |
3183 | # If all looks ok, proceed |
|
3183 | # If all looks ok, proceed | |
3184 | split = 'l' in opts |
|
3184 | split = 'l' in opts | |
3185 | out = self.shell.getoutput(cmd, split=split) |
|
3185 | out = self.shell.getoutput(cmd, split=split) | |
3186 | if opts.has_key('v'): |
|
3186 | if opts.has_key('v'): | |
3187 | print '%s ==\n%s' % (var,pformat(out)) |
|
3187 | print '%s ==\n%s' % (var,pformat(out)) | |
3188 | if var: |
|
3188 | if var: | |
3189 | self.shell.user_ns.update({var:out}) |
|
3189 | self.shell.user_ns.update({var:out}) | |
3190 | else: |
|
3190 | else: | |
3191 | return out |
|
3191 | return out | |
3192 |
|
3192 | |||
3193 | def magic_sx(self, parameter_s=''): |
|
3193 | def magic_sx(self, parameter_s=''): | |
3194 | """Shell execute - run a shell command and capture its output. |
|
3194 | """Shell execute - run a shell command and capture its output. | |
3195 |
|
3195 | |||
3196 | %sx command |
|
3196 | %sx command | |
3197 |
|
3197 | |||
3198 | IPython will run the given command using commands.getoutput(), and |
|
3198 | IPython will run the given command using commands.getoutput(), and | |
3199 | return the result formatted as a list (split on '\\n'). Since the |
|
3199 | return the result formatted as a list (split on '\\n'). Since the | |
3200 | output is _returned_, it will be stored in ipython's regular output |
|
3200 | output is _returned_, it will be stored in ipython's regular output | |
3201 | cache Out[N] and in the '_N' automatic variables. |
|
3201 | cache Out[N] and in the '_N' automatic variables. | |
3202 |
|
3202 | |||
3203 | Notes: |
|
3203 | Notes: | |
3204 |
|
3204 | |||
3205 | 1) If an input line begins with '!!', then %sx is automatically |
|
3205 | 1) If an input line begins with '!!', then %sx is automatically | |
3206 | invoked. That is, while:: |
|
3206 | invoked. That is, while:: | |
3207 |
|
3207 | |||
3208 | !ls |
|
3208 | !ls | |
3209 |
|
3209 | |||
3210 | causes ipython to simply issue system('ls'), typing:: |
|
3210 | causes ipython to simply issue system('ls'), typing:: | |
3211 |
|
3211 | |||
3212 | !!ls |
|
3212 | !!ls | |
3213 |
|
3213 | |||
3214 | is a shorthand equivalent to:: |
|
3214 | is a shorthand equivalent to:: | |
3215 |
|
3215 | |||
3216 | %sx ls |
|
3216 | %sx ls | |
3217 |
|
3217 | |||
3218 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
3218 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
3219 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
3219 | like '%sc -l'. The reason for this is to make it as easy as possible | |
3220 | to process line-oriented shell output via further python commands. |
|
3220 | to process line-oriented shell output via further python commands. | |
3221 | %sc is meant to provide much finer control, but requires more |
|
3221 | %sc is meant to provide much finer control, but requires more | |
3222 | typing. |
|
3222 | typing. | |
3223 |
|
3223 | |||
3224 | 3) Just like %sc -l, this is a list with special attributes: |
|
3224 | 3) Just like %sc -l, this is a list with special attributes: | |
3225 | :: |
|
3225 | :: | |
3226 |
|
3226 | |||
3227 | .l (or .list) : value as list. |
|
3227 | .l (or .list) : value as list. | |
3228 | .n (or .nlstr): value as newline-separated string. |
|
3228 | .n (or .nlstr): value as newline-separated string. | |
3229 | .s (or .spstr): value as whitespace-separated string. |
|
3229 | .s (or .spstr): value as whitespace-separated string. | |
3230 |
|
3230 | |||
3231 | This is very useful when trying to use such lists as arguments to |
|
3231 | This is very useful when trying to use such lists as arguments to | |
3232 | system commands.""" |
|
3232 | system commands.""" | |
3233 |
|
3233 | |||
3234 | if parameter_s: |
|
3234 | if parameter_s: | |
3235 | return self.shell.getoutput(parameter_s) |
|
3235 | return self.shell.getoutput(parameter_s) | |
3236 |
|
3236 | |||
3237 |
|
3237 | |||
3238 | def magic_bookmark(self, parameter_s=''): |
|
3238 | def magic_bookmark(self, parameter_s=''): | |
3239 | """Manage IPython's bookmark system. |
|
3239 | """Manage IPython's bookmark system. | |
3240 |
|
3240 | |||
3241 | %bookmark <name> - set bookmark to current dir |
|
3241 | %bookmark <name> - set bookmark to current dir | |
3242 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3242 | %bookmark <name> <dir> - set bookmark to <dir> | |
3243 | %bookmark -l - list all bookmarks |
|
3243 | %bookmark -l - list all bookmarks | |
3244 | %bookmark -d <name> - remove bookmark |
|
3244 | %bookmark -d <name> - remove bookmark | |
3245 | %bookmark -r - remove all bookmarks |
|
3245 | %bookmark -r - remove all bookmarks | |
3246 |
|
3246 | |||
3247 | You can later on access a bookmarked folder with:: |
|
3247 | You can later on access a bookmarked folder with:: | |
3248 |
|
3248 | |||
3249 | %cd -b <name> |
|
3249 | %cd -b <name> | |
3250 |
|
3250 | |||
3251 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3251 | or simply '%cd <name>' if there is no directory called <name> AND | |
3252 | there is such a bookmark defined. |
|
3252 | there is such a bookmark defined. | |
3253 |
|
3253 | |||
3254 | Your bookmarks persist through IPython sessions, but they are |
|
3254 | Your bookmarks persist through IPython sessions, but they are | |
3255 | associated with each profile.""" |
|
3255 | associated with each profile.""" | |
3256 |
|
3256 | |||
3257 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3257 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
3258 | if len(args) > 2: |
|
3258 | if len(args) > 2: | |
3259 | raise UsageError("%bookmark: too many arguments") |
|
3259 | raise UsageError("%bookmark: too many arguments") | |
3260 |
|
3260 | |||
3261 | bkms = self.db.get('bookmarks',{}) |
|
3261 | bkms = self.db.get('bookmarks',{}) | |
3262 |
|
3262 | |||
3263 | if opts.has_key('d'): |
|
3263 | if opts.has_key('d'): | |
3264 | try: |
|
3264 | try: | |
3265 | todel = args[0] |
|
3265 | todel = args[0] | |
3266 | except IndexError: |
|
3266 | except IndexError: | |
3267 | raise UsageError( |
|
3267 | raise UsageError( | |
3268 | "%bookmark -d: must provide a bookmark to delete") |
|
3268 | "%bookmark -d: must provide a bookmark to delete") | |
3269 | else: |
|
3269 | else: | |
3270 | try: |
|
3270 | try: | |
3271 | del bkms[todel] |
|
3271 | del bkms[todel] | |
3272 | except KeyError: |
|
3272 | except KeyError: | |
3273 | raise UsageError( |
|
3273 | raise UsageError( | |
3274 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3274 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) | |
3275 |
|
3275 | |||
3276 | elif opts.has_key('r'): |
|
3276 | elif opts.has_key('r'): | |
3277 | bkms = {} |
|
3277 | bkms = {} | |
3278 | elif opts.has_key('l'): |
|
3278 | elif opts.has_key('l'): | |
3279 | bks = bkms.keys() |
|
3279 | bks = bkms.keys() | |
3280 | bks.sort() |
|
3280 | bks.sort() | |
3281 | if bks: |
|
3281 | if bks: | |
3282 | size = max(map(len,bks)) |
|
3282 | size = max(map(len,bks)) | |
3283 | else: |
|
3283 | else: | |
3284 | size = 0 |
|
3284 | size = 0 | |
3285 | fmt = '%-'+str(size)+'s -> %s' |
|
3285 | fmt = '%-'+str(size)+'s -> %s' | |
3286 | print 'Current bookmarks:' |
|
3286 | print 'Current bookmarks:' | |
3287 | for bk in bks: |
|
3287 | for bk in bks: | |
3288 | print fmt % (bk,bkms[bk]) |
|
3288 | print fmt % (bk,bkms[bk]) | |
3289 | else: |
|
3289 | else: | |
3290 | if not args: |
|
3290 | if not args: | |
3291 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3291 | raise UsageError("%bookmark: You must specify the bookmark name") | |
3292 | elif len(args)==1: |
|
3292 | elif len(args)==1: | |
3293 | bkms[args[0]] = os.getcwdu() |
|
3293 | bkms[args[0]] = os.getcwdu() | |
3294 | elif len(args)==2: |
|
3294 | elif len(args)==2: | |
3295 | bkms[args[0]] = args[1] |
|
3295 | bkms[args[0]] = args[1] | |
3296 | self.db['bookmarks'] = bkms |
|
3296 | self.db['bookmarks'] = bkms | |
3297 |
|
3297 | |||
3298 | def magic_pycat(self, parameter_s=''): |
|
3298 | def magic_pycat(self, parameter_s=''): | |
3299 | """Show a syntax-highlighted file through a pager. |
|
3299 | """Show a syntax-highlighted file through a pager. | |
3300 |
|
3300 | |||
3301 | This magic is similar to the cat utility, but it will assume the file |
|
3301 | This magic is similar to the cat utility, but it will assume the file | |
3302 | to be Python source and will show it with syntax highlighting. """ |
|
3302 | to be Python source and will show it with syntax highlighting. """ | |
3303 |
|
3303 | |||
3304 | try: |
|
3304 | try: | |
3305 | filename = get_py_filename(parameter_s) |
|
3305 | filename = get_py_filename(parameter_s) | |
3306 | cont = file_read(filename) |
|
3306 | cont = file_read(filename) | |
3307 | except IOError: |
|
3307 | except IOError: | |
3308 | try: |
|
3308 | try: | |
3309 | cont = eval(parameter_s,self.user_ns) |
|
3309 | cont = eval(parameter_s,self.user_ns) | |
3310 | except NameError: |
|
3310 | except NameError: | |
3311 | cont = None |
|
3311 | cont = None | |
3312 | if cont is None: |
|
3312 | if cont is None: | |
3313 | print "Error: no such file or variable" |
|
3313 | print "Error: no such file or variable" | |
3314 | return |
|
3314 | return | |
3315 |
|
3315 | |||
3316 | page.page(self.shell.pycolorize(cont)) |
|
3316 | page.page(self.shell.pycolorize(cont)) | |
3317 |
|
3317 | |||
3318 | def magic_quickref(self,arg): |
|
3318 | def magic_quickref(self,arg): | |
3319 | """ Show a quick reference sheet """ |
|
3319 | """ Show a quick reference sheet """ | |
3320 | import IPython.core.usage |
|
3320 | import IPython.core.usage | |
3321 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') |
|
3321 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') | |
3322 |
|
3322 | |||
3323 | page.page(qr) |
|
3323 | page.page(qr) | |
3324 |
|
3324 | |||
3325 | def magic_doctest_mode(self,parameter_s=''): |
|
3325 | def magic_doctest_mode(self,parameter_s=''): | |
3326 | """Toggle doctest mode on and off. |
|
3326 | """Toggle doctest mode on and off. | |
3327 |
|
3327 | |||
3328 | This mode is intended to make IPython behave as much as possible like a |
|
3328 | This mode is intended to make IPython behave as much as possible like a | |
3329 | plain Python shell, from the perspective of how its prompts, exceptions |
|
3329 | plain Python shell, from the perspective of how its prompts, exceptions | |
3330 | and output look. This makes it easy to copy and paste parts of a |
|
3330 | and output look. This makes it easy to copy and paste parts of a | |
3331 | session into doctests. It does so by: |
|
3331 | session into doctests. It does so by: | |
3332 |
|
3332 | |||
3333 | - Changing the prompts to the classic ``>>>`` ones. |
|
3333 | - Changing the prompts to the classic ``>>>`` ones. | |
3334 | - Changing the exception reporting mode to 'Plain'. |
|
3334 | - Changing the exception reporting mode to 'Plain'. | |
3335 | - Disabling pretty-printing of output. |
|
3335 | - Disabling pretty-printing of output. | |
3336 |
|
3336 | |||
3337 | Note that IPython also supports the pasting of code snippets that have |
|
3337 | Note that IPython also supports the pasting of code snippets that have | |
3338 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
3338 | leading '>>>' and '...' prompts in them. This means that you can paste | |
3339 | doctests from files or docstrings (even if they have leading |
|
3339 | doctests from files or docstrings (even if they have leading | |
3340 | whitespace), and the code will execute correctly. You can then use |
|
3340 | whitespace), and the code will execute correctly. You can then use | |
3341 | '%history -t' to see the translated history; this will give you the |
|
3341 | '%history -t' to see the translated history; this will give you the | |
3342 | input after removal of all the leading prompts and whitespace, which |
|
3342 | input after removal of all the leading prompts and whitespace, which | |
3343 | can be pasted back into an editor. |
|
3343 | can be pasted back into an editor. | |
3344 |
|
3344 | |||
3345 | With these features, you can switch into this mode easily whenever you |
|
3345 | With these features, you can switch into this mode easily whenever you | |
3346 | need to do testing and changes to doctests, without having to leave |
|
3346 | need to do testing and changes to doctests, without having to leave | |
3347 | your existing IPython session. |
|
3347 | your existing IPython session. | |
3348 | """ |
|
3348 | """ | |
3349 |
|
3349 | |||
3350 | from IPython.utils.ipstruct import Struct |
|
3350 | from IPython.utils.ipstruct import Struct | |
3351 |
|
3351 | |||
3352 | # Shorthands |
|
3352 | # Shorthands | |
3353 | shell = self.shell |
|
3353 | shell = self.shell | |
3354 | pm = shell.prompt_manager |
|
3354 | pm = shell.prompt_manager | |
3355 | meta = shell.meta |
|
3355 | meta = shell.meta | |
3356 | disp_formatter = self.shell.display_formatter |
|
3356 | disp_formatter = self.shell.display_formatter | |
3357 | ptformatter = disp_formatter.formatters['text/plain'] |
|
3357 | ptformatter = disp_formatter.formatters['text/plain'] | |
3358 | # dstore is a data store kept in the instance metadata bag to track any |
|
3358 | # dstore is a data store kept in the instance metadata bag to track any | |
3359 | # changes we make, so we can undo them later. |
|
3359 | # changes we make, so we can undo them later. | |
3360 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3360 | dstore = meta.setdefault('doctest_mode',Struct()) | |
3361 | save_dstore = dstore.setdefault |
|
3361 | save_dstore = dstore.setdefault | |
3362 |
|
3362 | |||
3363 | # save a few values we'll need to recover later |
|
3363 | # save a few values we'll need to recover later | |
3364 | mode = save_dstore('mode',False) |
|
3364 | mode = save_dstore('mode',False) | |
3365 | save_dstore('rc_pprint',ptformatter.pprint) |
|
3365 | save_dstore('rc_pprint',ptformatter.pprint) | |
3366 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3366 | save_dstore('xmode',shell.InteractiveTB.mode) | |
3367 | save_dstore('rc_separate_out',shell.separate_out) |
|
3367 | save_dstore('rc_separate_out',shell.separate_out) | |
3368 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
3368 | save_dstore('rc_separate_out2',shell.separate_out2) | |
3369 | save_dstore('rc_prompts_pad_left',pm.justify) |
|
3369 | save_dstore('rc_prompts_pad_left',pm.justify) | |
3370 | save_dstore('rc_separate_in',shell.separate_in) |
|
3370 | save_dstore('rc_separate_in',shell.separate_in) | |
3371 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) |
|
3371 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) | |
3372 | save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template)) |
|
3372 | save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template)) | |
3373 |
|
3373 | |||
3374 | if mode == False: |
|
3374 | if mode == False: | |
3375 | # turn on |
|
3375 | # turn on | |
3376 | pm.in_template = '>>> ' |
|
3376 | pm.in_template = '>>> ' | |
3377 | pm.in2_template = '... ' |
|
3377 | pm.in2_template = '... ' | |
3378 | pm.out_template = '' |
|
3378 | pm.out_template = '' | |
3379 |
|
3379 | |||
3380 | # Prompt separators like plain python |
|
3380 | # Prompt separators like plain python | |
3381 | shell.separate_in = '' |
|
3381 | shell.separate_in = '' | |
3382 | shell.separate_out = '' |
|
3382 | shell.separate_out = '' | |
3383 | shell.separate_out2 = '' |
|
3383 | shell.separate_out2 = '' | |
3384 |
|
3384 | |||
3385 | pm.justify = False |
|
3385 | pm.justify = False | |
3386 |
|
3386 | |||
3387 | ptformatter.pprint = False |
|
3387 | ptformatter.pprint = False | |
3388 | disp_formatter.plain_text_only = True |
|
3388 | disp_formatter.plain_text_only = True | |
3389 |
|
3389 | |||
3390 | shell.magic_xmode('Plain') |
|
3390 | shell.magic_xmode('Plain') | |
3391 | else: |
|
3391 | else: | |
3392 | # turn off |
|
3392 | # turn off | |
3393 | pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates |
|
3393 | pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates | |
3394 |
|
3394 | |||
3395 | shell.separate_in = dstore.rc_separate_in |
|
3395 | shell.separate_in = dstore.rc_separate_in | |
3396 |
|
3396 | |||
3397 | shell.separate_out = dstore.rc_separate_out |
|
3397 | shell.separate_out = dstore.rc_separate_out | |
3398 | shell.separate_out2 = dstore.rc_separate_out2 |
|
3398 | shell.separate_out2 = dstore.rc_separate_out2 | |
3399 |
|
3399 | |||
3400 | pm.justify = dstore.rc_prompts_pad_left |
|
3400 | pm.justify = dstore.rc_prompts_pad_left | |
3401 |
|
3401 | |||
3402 | ptformatter.pprint = dstore.rc_pprint |
|
3402 | ptformatter.pprint = dstore.rc_pprint | |
3403 | disp_formatter.plain_text_only = dstore.rc_plain_text_only |
|
3403 | disp_formatter.plain_text_only = dstore.rc_plain_text_only | |
3404 |
|
3404 | |||
3405 | shell.magic_xmode(dstore.xmode) |
|
3405 | shell.magic_xmode(dstore.xmode) | |
3406 |
|
3406 | |||
3407 | # Store new mode and inform |
|
3407 | # Store new mode and inform | |
3408 | dstore.mode = bool(1-int(mode)) |
|
3408 | dstore.mode = bool(1-int(mode)) | |
3409 | mode_label = ['OFF','ON'][dstore.mode] |
|
3409 | mode_label = ['OFF','ON'][dstore.mode] | |
3410 | print 'Doctest mode is:', mode_label |
|
3410 | print 'Doctest mode is:', mode_label | |
3411 |
|
3411 | |||
3412 | def magic_gui(self, parameter_s=''): |
|
3412 | def magic_gui(self, parameter_s=''): | |
3413 | """Enable or disable IPython GUI event loop integration. |
|
3413 | """Enable or disable IPython GUI event loop integration. | |
3414 |
|
3414 | |||
3415 | %gui [GUINAME] |
|
3415 | %gui [GUINAME] | |
3416 |
|
3416 | |||
3417 | This magic replaces IPython's threaded shells that were activated |
|
3417 | This magic replaces IPython's threaded shells that were activated | |
3418 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
3418 | using the (pylab/wthread/etc.) command line flags. GUI toolkits | |
3419 | can now be enabled at runtime and keyboard |
|
3419 | can now be enabled at runtime and keyboard | |
3420 | interrupts should work without any problems. The following toolkits |
|
3420 | interrupts should work without any problems. The following toolkits | |
3421 | are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX):: |
|
3421 | are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX):: | |
3422 |
|
3422 | |||
3423 | %gui wx # enable wxPython event loop integration |
|
3423 | %gui wx # enable wxPython event loop integration | |
3424 | %gui qt4|qt # enable PyQt4 event loop integration |
|
3424 | %gui qt4|qt # enable PyQt4 event loop integration | |
3425 | %gui gtk # enable PyGTK event loop integration |
|
3425 | %gui gtk # enable PyGTK event loop integration | |
3426 | %gui gtk3 # enable Gtk3 event loop integration |
|
3426 | %gui gtk3 # enable Gtk3 event loop integration | |
3427 | %gui tk # enable Tk event loop integration |
|
3427 | %gui tk # enable Tk event loop integration | |
3428 | %gui OSX # enable Cocoa event loop integration |
|
3428 | %gui OSX # enable Cocoa event loop integration | |
3429 | # (requires %matplotlib 1.1) |
|
3429 | # (requires %matplotlib 1.1) | |
3430 | %gui # disable all event loop integration |
|
3430 | %gui # disable all event loop integration | |
3431 |
|
3431 | |||
3432 | WARNING: after any of these has been called you can simply create |
|
3432 | WARNING: after any of these has been called you can simply create | |
3433 | an application object, but DO NOT start the event loop yourself, as |
|
3433 | an application object, but DO NOT start the event loop yourself, as | |
3434 | we have already handled that. |
|
3434 | we have already handled that. | |
3435 | """ |
|
3435 | """ | |
3436 | opts, arg = self.parse_options(parameter_s, '') |
|
3436 | opts, arg = self.parse_options(parameter_s, '') | |
3437 | if arg=='': arg = None |
|
3437 | if arg=='': arg = None | |
3438 | try: |
|
3438 | try: | |
3439 | return self.enable_gui(arg) |
|
3439 | return self.enable_gui(arg) | |
3440 | except Exception as e: |
|
3440 | except Exception as e: | |
3441 | # print simple error message, rather than traceback if we can't |
|
3441 | # print simple error message, rather than traceback if we can't | |
3442 | # hook up the GUI |
|
3442 | # hook up the GUI | |
3443 | error(str(e)) |
|
3443 | error(str(e)) | |
3444 |
|
3444 | |||
3445 | def magic_install_ext(self, parameter_s): |
|
3445 | def magic_install_ext(self, parameter_s): | |
3446 | """Download and install an extension from a URL, e.g.:: |
|
3446 | """Download and install an extension from a URL, e.g.:: | |
3447 |
|
3447 | |||
3448 | %install_ext https://bitbucket.org/birkenfeld/ipython-physics/raw/d1310a2ab15d/physics.py |
|
3448 | %install_ext https://bitbucket.org/birkenfeld/ipython-physics/raw/d1310a2ab15d/physics.py | |
3449 |
|
3449 | |||
3450 | The URL should point to an importable Python module - either a .py file |
|
3450 | The URL should point to an importable Python module - either a .py file | |
3451 | or a .zip file. |
|
3451 | or a .zip file. | |
3452 |
|
3452 | |||
3453 | Parameters: |
|
3453 | Parameters: | |
3454 |
|
3454 | |||
3455 | -n filename : Specify a name for the file, rather than taking it from |
|
3455 | -n filename : Specify a name for the file, rather than taking it from | |
3456 | the URL. |
|
3456 | the URL. | |
3457 | """ |
|
3457 | """ | |
3458 | opts, args = self.parse_options(parameter_s, 'n:') |
|
3458 | opts, args = self.parse_options(parameter_s, 'n:') | |
3459 | try: |
|
3459 | try: | |
3460 | filename = self.extension_manager.install_extension(args, opts.get('n')) |
|
3460 | filename = self.extension_manager.install_extension(args, opts.get('n')) | |
3461 | except ValueError as e: |
|
3461 | except ValueError as e: | |
3462 | print e |
|
3462 | print e | |
3463 | return |
|
3463 | return | |
3464 |
|
3464 | |||
3465 | filename = os.path.basename(filename) |
|
3465 | filename = os.path.basename(filename) | |
3466 | print "Installed %s. To use it, type:" % filename |
|
3466 | print "Installed %s. To use it, type:" % filename | |
3467 | print " %%load_ext %s" % os.path.splitext(filename)[0] |
|
3467 | print " %%load_ext %s" % os.path.splitext(filename)[0] | |
3468 |
|
3468 | |||
3469 |
|
3469 | |||
3470 | def magic_load_ext(self, module_str): |
|
3470 | def magic_load_ext(self, module_str): | |
3471 | """Load an IPython extension by its module name.""" |
|
3471 | """Load an IPython extension by its module name.""" | |
3472 | return self.extension_manager.load_extension(module_str) |
|
3472 | return self.extension_manager.load_extension(module_str) | |
3473 |
|
3473 | |||
3474 | def magic_unload_ext(self, module_str): |
|
3474 | def magic_unload_ext(self, module_str): | |
3475 | """Unload an IPython extension by its module name.""" |
|
3475 | """Unload an IPython extension by its module name.""" | |
3476 | self.extension_manager.unload_extension(module_str) |
|
3476 | self.extension_manager.unload_extension(module_str) | |
3477 |
|
3477 | |||
3478 | def magic_reload_ext(self, module_str): |
|
3478 | def magic_reload_ext(self, module_str): | |
3479 | """Reload an IPython extension by its module name.""" |
|
3479 | """Reload an IPython extension by its module name.""" | |
3480 | self.extension_manager.reload_extension(module_str) |
|
3480 | self.extension_manager.reload_extension(module_str) | |
3481 |
|
3481 | |||
3482 | def magic_install_profiles(self, s): |
|
3482 | def magic_install_profiles(self, s): | |
3483 | """%install_profiles has been deprecated.""" |
|
3483 | """%install_profiles has been deprecated.""" | |
3484 | print '\n'.join([ |
|
3484 | print '\n'.join([ | |
3485 | "%install_profiles has been deprecated.", |
|
3485 | "%install_profiles has been deprecated.", | |
3486 | "Use `ipython profile list` to view available profiles.", |
|
3486 | "Use `ipython profile list` to view available profiles.", | |
3487 | "Requesting a profile with `ipython profile create <name>`", |
|
3487 | "Requesting a profile with `ipython profile create <name>`", | |
3488 | "or `ipython --profile=<name>` will start with the bundled", |
|
3488 | "or `ipython --profile=<name>` will start with the bundled", | |
3489 | "profile of that name if it exists." |
|
3489 | "profile of that name if it exists." | |
3490 | ]) |
|
3490 | ]) | |
3491 |
|
3491 | |||
3492 | def magic_install_default_config(self, s): |
|
3492 | def magic_install_default_config(self, s): | |
3493 | """%install_default_config has been deprecated.""" |
|
3493 | """%install_default_config has been deprecated.""" | |
3494 | print '\n'.join([ |
|
3494 | print '\n'.join([ | |
3495 | "%install_default_config has been deprecated.", |
|
3495 | "%install_default_config has been deprecated.", | |
3496 | "Use `ipython profile create <name>` to initialize a profile", |
|
3496 | "Use `ipython profile create <name>` to initialize a profile", | |
3497 | "with the default config files.", |
|
3497 | "with the default config files.", | |
3498 | "Add `--reset` to overwrite already existing config files with defaults." |
|
3498 | "Add `--reset` to overwrite already existing config files with defaults." | |
3499 | ]) |
|
3499 | ]) | |
3500 |
|
3500 | |||
3501 | # Pylab support: simple wrappers that activate pylab, load gui input |
|
3501 | # Pylab support: simple wrappers that activate pylab, load gui input | |
3502 | # handling and modify slightly %run |
|
3502 | # handling and modify slightly %run | |
3503 |
|
3503 | |||
3504 | @skip_doctest |
|
3504 | @skip_doctest | |
3505 | def _pylab_magic_run(self, parameter_s=''): |
|
3505 | def _pylab_magic_run(self, parameter_s=''): | |
3506 | Magic.magic_run(self, parameter_s, |
|
3506 | Magic.magic_run(self, parameter_s, | |
3507 | runner=mpl_runner(self.shell.safe_execfile)) |
|
3507 | runner=mpl_runner(self.shell.safe_execfile)) | |
3508 |
|
3508 | |||
3509 | _pylab_magic_run.__doc__ = magic_run.__doc__ |
|
3509 | _pylab_magic_run.__doc__ = magic_run.__doc__ | |
3510 |
|
3510 | |||
3511 | @skip_doctest |
|
3511 | @skip_doctest | |
3512 | def magic_pylab(self, s): |
|
3512 | def magic_pylab(self, s): | |
3513 | """Load numpy and matplotlib to work interactively. |
|
3513 | """Load numpy and matplotlib to work interactively. | |
3514 |
|
3514 | |||
3515 | %pylab [GUINAME] |
|
3515 | %pylab [GUINAME] | |
3516 |
|
3516 | |||
3517 | This function lets you activate pylab (matplotlib, numpy and |
|
3517 | This function lets you activate pylab (matplotlib, numpy and | |
3518 | interactive support) at any point during an IPython session. |
|
3518 | interactive support) at any point during an IPython session. | |
3519 |
|
3519 | |||
3520 | It will import at the top level numpy as np, pyplot as plt, matplotlib, |
|
3520 | It will import at the top level numpy as np, pyplot as plt, matplotlib, | |
3521 | pylab and mlab, as well as all names from numpy and pylab. |
|
3521 | pylab and mlab, as well as all names from numpy and pylab. | |
3522 |
|
3522 | |||
3523 | If you are using the inline matplotlib backend for embedded figures, |
|
3523 | If you are using the inline matplotlib backend for embedded figures, | |
3524 | you can adjust its behavior via the %config magic:: |
|
3524 | you can adjust its behavior via the %config magic:: | |
3525 |
|
3525 | |||
3526 | # enable SVG figures, necessary for SVG+XHTML export in the qtconsole |
|
3526 | # enable SVG figures, necessary for SVG+XHTML export in the qtconsole | |
3527 | In [1]: %config InlineBackend.figure_format = 'svg' |
|
3527 | In [1]: %config InlineBackend.figure_format = 'svg' | |
3528 |
|
3528 | |||
3529 | # change the behavior of closing all figures at the end of each |
|
3529 | # change the behavior of closing all figures at the end of each | |
3530 | # execution (cell), or allowing reuse of active figures across |
|
3530 | # execution (cell), or allowing reuse of active figures across | |
3531 | # cells: |
|
3531 | # cells: | |
3532 | In [2]: %config InlineBackend.close_figures = False |
|
3532 | In [2]: %config InlineBackend.close_figures = False | |
3533 |
|
3533 | |||
3534 | Parameters |
|
3534 | Parameters | |
3535 | ---------- |
|
3535 | ---------- | |
3536 | guiname : optional |
|
3536 | guiname : optional | |
3537 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', |
|
3537 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', | |
3538 | 'osx' or 'tk'). If given, the corresponding Matplotlib backend is |
|
3538 | 'osx' or 'tk'). If given, the corresponding Matplotlib backend is | |
3539 | used, otherwise matplotlib's default (which you can override in your |
|
3539 | used, otherwise matplotlib's default (which you can override in your | |
3540 | matplotlib config file) is used. |
|
3540 | matplotlib config file) is used. | |
3541 |
|
3541 | |||
3542 | Examples |
|
3542 | Examples | |
3543 | -------- |
|
3543 | -------- | |
3544 | In this case, where the MPL default is TkAgg:: |
|
3544 | In this case, where the MPL default is TkAgg:: | |
3545 |
|
3545 | |||
3546 | In [2]: %pylab |
|
3546 | In [2]: %pylab | |
3547 |
|
3547 | |||
3548 | Welcome to pylab, a matplotlib-based Python environment. |
|
3548 | Welcome to pylab, a matplotlib-based Python environment. | |
3549 | Backend in use: TkAgg |
|
3549 | Backend in use: TkAgg | |
3550 | For more information, type 'help(pylab)'. |
|
3550 | For more information, type 'help(pylab)'. | |
3551 |
|
3551 | |||
3552 | But you can explicitly request a different backend:: |
|
3552 | But you can explicitly request a different backend:: | |
3553 |
|
3553 | |||
3554 | In [3]: %pylab qt |
|
3554 | In [3]: %pylab qt | |
3555 |
|
3555 | |||
3556 | Welcome to pylab, a matplotlib-based Python environment. |
|
3556 | Welcome to pylab, a matplotlib-based Python environment. | |
3557 | Backend in use: Qt4Agg |
|
3557 | Backend in use: Qt4Agg | |
3558 | For more information, type 'help(pylab)'. |
|
3558 | For more information, type 'help(pylab)'. | |
3559 | """ |
|
3559 | """ | |
3560 |
|
3560 | |||
3561 | if Application.initialized(): |
|
3561 | if Application.initialized(): | |
3562 | app = Application.instance() |
|
3562 | app = Application.instance() | |
3563 | try: |
|
3563 | try: | |
3564 | import_all_status = app.pylab_import_all |
|
3564 | import_all_status = app.pylab_import_all | |
3565 | except AttributeError: |
|
3565 | except AttributeError: | |
3566 | import_all_status = True |
|
3566 | import_all_status = True | |
3567 | else: |
|
3567 | else: | |
3568 | import_all_status = True |
|
3568 | import_all_status = True | |
3569 |
|
3569 | |||
3570 | self.shell.enable_pylab(s, import_all=import_all_status) |
|
3570 | self.shell.enable_pylab(s, import_all=import_all_status) | |
3571 |
|
3571 | |||
3572 | def magic_tb(self, s): |
|
3572 | def magic_tb(self, s): | |
3573 | """Print the last traceback with the currently active exception mode. |
|
3573 | """Print the last traceback with the currently active exception mode. | |
3574 |
|
3574 | |||
3575 | See %xmode for changing exception reporting modes.""" |
|
3575 | See %xmode for changing exception reporting modes.""" | |
3576 | self.shell.showtraceback() |
|
3576 | self.shell.showtraceback() | |
3577 |
|
3577 | |||
3578 | @skip_doctest |
|
3578 | @skip_doctest | |
3579 | def magic_precision(self, s=''): |
|
3579 | def magic_precision(self, s=''): | |
3580 | """Set floating point precision for pretty printing. |
|
3580 | """Set floating point precision for pretty printing. | |
3581 |
|
3581 | |||
3582 | Can set either integer precision or a format string. |
|
3582 | Can set either integer precision or a format string. | |
3583 |
|
3583 | |||
3584 | If numpy has been imported and precision is an int, |
|
3584 | If numpy has been imported and precision is an int, | |
3585 | numpy display precision will also be set, via ``numpy.set_printoptions``. |
|
3585 | numpy display precision will also be set, via ``numpy.set_printoptions``. | |
3586 |
|
3586 | |||
3587 | If no argument is given, defaults will be restored. |
|
3587 | If no argument is given, defaults will be restored. | |
3588 |
|
3588 | |||
3589 | Examples |
|
3589 | Examples | |
3590 | -------- |
|
3590 | -------- | |
3591 | :: |
|
3591 | :: | |
3592 |
|
3592 | |||
3593 | In [1]: from math import pi |
|
3593 | In [1]: from math import pi | |
3594 |
|
3594 | |||
3595 | In [2]: %precision 3 |
|
3595 | In [2]: %precision 3 | |
3596 | Out[2]: u'%.3f' |
|
3596 | Out[2]: u'%.3f' | |
3597 |
|
3597 | |||
3598 | In [3]: pi |
|
3598 | In [3]: pi | |
3599 | Out[3]: 3.142 |
|
3599 | Out[3]: 3.142 | |
3600 |
|
3600 | |||
3601 | In [4]: %precision %i |
|
3601 | In [4]: %precision %i | |
3602 | Out[4]: u'%i' |
|
3602 | Out[4]: u'%i' | |
3603 |
|
3603 | |||
3604 | In [5]: pi |
|
3604 | In [5]: pi | |
3605 | Out[5]: 3 |
|
3605 | Out[5]: 3 | |
3606 |
|
3606 | |||
3607 | In [6]: %precision %e |
|
3607 | In [6]: %precision %e | |
3608 | Out[6]: u'%e' |
|
3608 | Out[6]: u'%e' | |
3609 |
|
3609 | |||
3610 | In [7]: pi**10 |
|
3610 | In [7]: pi**10 | |
3611 | Out[7]: 9.364805e+04 |
|
3611 | Out[7]: 9.364805e+04 | |
3612 |
|
3612 | |||
3613 | In [8]: %precision |
|
3613 | In [8]: %precision | |
3614 | Out[8]: u'%r' |
|
3614 | Out[8]: u'%r' | |
3615 |
|
3615 | |||
3616 | In [9]: pi**10 |
|
3616 | In [9]: pi**10 | |
3617 | Out[9]: 93648.047476082982 |
|
3617 | Out[9]: 93648.047476082982 | |
3618 |
|
3618 | |||
3619 | """ |
|
3619 | """ | |
3620 |
|
3620 | |||
3621 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
3621 | ptformatter = self.shell.display_formatter.formatters['text/plain'] | |
3622 | ptformatter.float_precision = s |
|
3622 | ptformatter.float_precision = s | |
3623 | return ptformatter.float_format |
|
3623 | return ptformatter.float_format | |
3624 |
|
3624 | |||
3625 |
|
3625 | |||
3626 | @magic_arguments.magic_arguments() |
|
3626 | @magic_arguments.magic_arguments() | |
3627 | @magic_arguments.argument( |
|
3627 | @magic_arguments.argument( | |
3628 | '-e', '--export', action='store_true', default=False, |
|
3628 | '-e', '--export', action='store_true', default=False, | |
3629 | help='Export IPython history as a notebook. The filename argument ' |
|
3629 | help='Export IPython history as a notebook. The filename argument ' | |
3630 | 'is used to specify the notebook name and format. For example ' |
|
3630 | 'is used to specify the notebook name and format. For example ' | |
3631 | 'a filename of notebook.ipynb will result in a notebook name ' |
|
3631 | 'a filename of notebook.ipynb will result in a notebook name ' | |
3632 | 'of "notebook" and a format of "xml". Likewise using a ".json" ' |
|
3632 | 'of "notebook" and a format of "xml". Likewise using a ".json" ' | |
3633 | 'or ".py" file extension will write the notebook in the json ' |
|
3633 | 'or ".py" file extension will write the notebook in the json ' | |
3634 | 'or py formats.' |
|
3634 | 'or py formats.' | |
3635 | ) |
|
3635 | ) | |
3636 | @magic_arguments.argument( |
|
3636 | @magic_arguments.argument( | |
3637 | '-f', '--format', |
|
3637 | '-f', '--format', | |
3638 | help='Convert an existing IPython notebook to a new format. This option ' |
|
3638 | help='Convert an existing IPython notebook to a new format. This option ' | |
3639 | 'specifies the new format and can have the values: xml, json, py. ' |
|
3639 | 'specifies the new format and can have the values: xml, json, py. ' | |
3640 | 'The target filename is chosen automatically based on the new ' |
|
3640 | 'The target filename is chosen automatically based on the new ' | |
3641 | 'format. The filename argument gives the name of the source file.' |
|
3641 | 'format. The filename argument gives the name of the source file.' | |
3642 | ) |
|
3642 | ) | |
3643 | @magic_arguments.argument( |
|
3643 | @magic_arguments.argument( | |
3644 | 'filename', type=unicode, |
|
3644 | 'filename', type=unicode, | |
3645 | help='Notebook name or filename' |
|
3645 | help='Notebook name or filename' | |
3646 | ) |
|
3646 | ) | |
3647 | def magic_notebook(self, s): |
|
3647 | def magic_notebook(self, s): | |
3648 | """Export and convert IPython notebooks. |
|
3648 | """Export and convert IPython notebooks. | |
3649 |
|
3649 | |||
3650 | This function can export the current IPython history to a notebook file |
|
3650 | This function can export the current IPython history to a notebook file | |
3651 | or can convert an existing notebook file into a different format. For |
|
3651 | or can convert an existing notebook file into a different format. For | |
3652 | example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb". |
|
3652 | example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb". | |
3653 | To export the history to "foo.py" do "%notebook -e foo.py". To convert |
|
3653 | To export the history to "foo.py" do "%notebook -e foo.py". To convert | |
3654 | "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible |
|
3654 | "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible | |
3655 | formats include (json/ipynb, py). |
|
3655 | formats include (json/ipynb, py). | |
3656 | """ |
|
3656 | """ | |
3657 | args = magic_arguments.parse_argstring(self.magic_notebook, s) |
|
3657 | args = magic_arguments.parse_argstring(self.magic_notebook, s) | |
3658 |
|
3658 | |||
3659 | from IPython.nbformat import current |
|
3659 | from IPython.nbformat import current | |
3660 | args.filename = unquote_filename(args.filename) |
|
3660 | args.filename = unquote_filename(args.filename) | |
3661 | if args.export: |
|
3661 | if args.export: | |
3662 | fname, name, format = current.parse_filename(args.filename) |
|
3662 | fname, name, format = current.parse_filename(args.filename) | |
3663 | cells = [] |
|
3663 | cells = [] | |
3664 | hist = list(self.history_manager.get_range()) |
|
3664 | hist = list(self.history_manager.get_range()) | |
3665 | for session, prompt_number, input in hist[:-1]: |
|
3665 | for session, prompt_number, input in hist[:-1]: | |
3666 | cells.append(current.new_code_cell(prompt_number=prompt_number, input=input)) |
|
3666 | cells.append(current.new_code_cell(prompt_number=prompt_number, input=input)) | |
3667 | worksheet = current.new_worksheet(cells=cells) |
|
3667 | worksheet = current.new_worksheet(cells=cells) | |
3668 | nb = current.new_notebook(name=name,worksheets=[worksheet]) |
|
3668 | nb = current.new_notebook(name=name,worksheets=[worksheet]) | |
3669 | with io.open(fname, 'w', encoding='utf-8') as f: |
|
3669 | with io.open(fname, 'w', encoding='utf-8') as f: | |
3670 | current.write(nb, f, format); |
|
3670 | current.write(nb, f, format); | |
3671 | elif args.format is not None: |
|
3671 | elif args.format is not None: | |
3672 | old_fname, old_name, old_format = current.parse_filename(args.filename) |
|
3672 | old_fname, old_name, old_format = current.parse_filename(args.filename) | |
3673 | new_format = args.format |
|
3673 | new_format = args.format | |
3674 | if new_format == u'xml': |
|
3674 | if new_format == u'xml': | |
3675 | raise ValueError('Notebooks cannot be written as xml.') |
|
3675 | raise ValueError('Notebooks cannot be written as xml.') | |
3676 | elif new_format == u'ipynb' or new_format == u'json': |
|
3676 | elif new_format == u'ipynb' or new_format == u'json': | |
3677 | new_fname = old_name + u'.ipynb' |
|
3677 | new_fname = old_name + u'.ipynb' | |
3678 | new_format = u'json' |
|
3678 | new_format = u'json' | |
3679 | elif new_format == u'py': |
|
3679 | elif new_format == u'py': | |
3680 | new_fname = old_name + u'.py' |
|
3680 | new_fname = old_name + u'.py' | |
3681 | else: |
|
3681 | else: | |
3682 | raise ValueError('Invalid notebook format: %s' % new_format) |
|
3682 | raise ValueError('Invalid notebook format: %s' % new_format) | |
3683 | with io.open(old_fname, 'r', encoding='utf-8') as f: |
|
3683 | with io.open(old_fname, 'r', encoding='utf-8') as f: | |
3684 | nb = current.read(f, old_format) |
|
3684 | nb = current.read(f, old_format) | |
3685 | with io.open(new_fname, 'w', encoding='utf-8') as f: |
|
3685 | with io.open(new_fname, 'w', encoding='utf-8') as f: | |
3686 | current.write(nb, f, new_format) |
|
3686 | current.write(nb, f, new_format) | |
3687 |
|
3687 | |||
3688 | def magic_config(self, s): |
|
3688 | def magic_config(self, s): | |
3689 | """configure IPython |
|
3689 | """configure IPython | |
3690 |
|
3690 | |||
3691 | %config Class[.trait=value] |
|
3691 | %config Class[.trait=value] | |
3692 |
|
3692 | |||
3693 | This magic exposes most of the IPython config system. Any |
|
3693 | This magic exposes most of the IPython config system. Any | |
3694 | Configurable class should be able to be configured with the simple |
|
3694 | Configurable class should be able to be configured with the simple | |
3695 | line:: |
|
3695 | line:: | |
3696 |
|
3696 | |||
3697 | %config Class.trait=value |
|
3697 | %config Class.trait=value | |
3698 |
|
3698 | |||
3699 | Where `value` will be resolved in the user's namespace, if it is an |
|
3699 | Where `value` will be resolved in the user's namespace, if it is an | |
3700 | expression or variable name. |
|
3700 | expression or variable name. | |
3701 |
|
3701 | |||
3702 | Examples |
|
3702 | Examples | |
3703 | -------- |
|
3703 | -------- | |
3704 |
|
3704 | |||
3705 | To see what classes are available for config, pass no arguments:: |
|
3705 | To see what classes are available for config, pass no arguments:: | |
3706 |
|
3706 | |||
3707 | In [1]: %config |
|
3707 | In [1]: %config | |
3708 | Available objects for config: |
|
3708 | Available objects for config: | |
3709 | TerminalInteractiveShell |
|
3709 | TerminalInteractiveShell | |
3710 | HistoryManager |
|
3710 | HistoryManager | |
3711 | PrefilterManager |
|
3711 | PrefilterManager | |
3712 | AliasManager |
|
3712 | AliasManager | |
3713 | IPCompleter |
|
3713 | IPCompleter | |
3714 | PromptManager |
|
3714 | PromptManager | |
3715 | DisplayFormatter |
|
3715 | DisplayFormatter | |
3716 |
|
3716 | |||
3717 | To view what is configurable on a given class, just pass the class |
|
3717 | To view what is configurable on a given class, just pass the class | |
3718 | name:: |
|
3718 | name:: | |
3719 |
|
3719 | |||
3720 | In [2]: %config IPCompleter |
|
3720 | In [2]: %config IPCompleter | |
3721 | IPCompleter options |
|
3721 | IPCompleter options | |
3722 | ----------------- |
|
3722 | ----------------- | |
3723 | IPCompleter.omit__names=<Enum> |
|
3723 | IPCompleter.omit__names=<Enum> | |
3724 | Current: 2 |
|
3724 | Current: 2 | |
3725 | Choices: (0, 1, 2) |
|
3725 | Choices: (0, 1, 2) | |
3726 | Instruct the completer to omit private method names |
|
3726 | Instruct the completer to omit private method names | |
3727 | Specifically, when completing on ``object.<tab>``. |
|
3727 | Specifically, when completing on ``object.<tab>``. | |
3728 | When 2 [default]: all names that start with '_' will be excluded. |
|
3728 | When 2 [default]: all names that start with '_' will be excluded. | |
3729 | When 1: all 'magic' names (``__foo__``) will be excluded. |
|
3729 | When 1: all 'magic' names (``__foo__``) will be excluded. | |
3730 | When 0: nothing will be excluded. |
|
3730 | When 0: nothing will be excluded. | |
3731 | IPCompleter.merge_completions=<CBool> |
|
3731 | IPCompleter.merge_completions=<CBool> | |
3732 | Current: True |
|
3732 | Current: True | |
3733 | Whether to merge completion results into a single list |
|
3733 | Whether to merge completion results into a single list | |
3734 | If False, only the completion results from the first non-empty completer |
|
3734 | If False, only the completion results from the first non-empty completer | |
3735 | will be returned. |
|
3735 | will be returned. | |
3736 | IPCompleter.limit_to__all__=<CBool> |
|
3736 | IPCompleter.limit_to__all__=<CBool> | |
3737 | Current: False |
|
3737 | Current: False | |
3738 | Instruct the completer to use __all__ for the completion |
|
3738 | Instruct the completer to use __all__ for the completion | |
3739 | Specifically, when completing on ``object.<tab>``. |
|
3739 | Specifically, when completing on ``object.<tab>``. | |
3740 | When True: only those names in obj.__all__ will be included. |
|
3740 | When True: only those names in obj.__all__ will be included. | |
3741 | When False [default]: the __all__ attribute is ignored |
|
3741 | When False [default]: the __all__ attribute is ignored | |
3742 | IPCompleter.greedy=<CBool> |
|
3742 | IPCompleter.greedy=<CBool> | |
3743 | Current: False |
|
3743 | Current: False | |
3744 | Activate greedy completion |
|
3744 | Activate greedy completion | |
3745 | This will enable completion on elements of lists, results of function calls, |
|
3745 | This will enable completion on elements of lists, results of function calls, | |
3746 | etc., but can be unsafe because the code is actually evaluated on TAB. |
|
3746 | etc., but can be unsafe because the code is actually evaluated on TAB. | |
3747 |
|
3747 | |||
3748 | but the real use is in setting values:: |
|
3748 | but the real use is in setting values:: | |
3749 |
|
3749 | |||
3750 | In [3]: %config IPCompleter.greedy = True |
|
3750 | In [3]: %config IPCompleter.greedy = True | |
3751 |
|
3751 | |||
3752 | and these values are read from the user_ns if they are variables:: |
|
3752 | and these values are read from the user_ns if they are variables:: | |
3753 |
|
3753 | |||
3754 | In [4]: feeling_greedy=False |
|
3754 | In [4]: feeling_greedy=False | |
3755 |
|
3755 | |||
3756 | In [5]: %config IPCompleter.greedy = feeling_greedy |
|
3756 | In [5]: %config IPCompleter.greedy = feeling_greedy | |
3757 |
|
3757 | |||
3758 | """ |
|
3758 | """ | |
3759 | from IPython.config.loader import Config |
|
3759 | from IPython.config.loader import Config | |
3760 | # some IPython objects are Configurable, but do not yet have |
|
3760 | # some IPython objects are Configurable, but do not yet have | |
3761 | # any configurable traits. Exclude them from the effects of |
|
3761 | # any configurable traits. Exclude them from the effects of | |
3762 | # this magic, as their presence is just noise: |
|
3762 | # this magic, as their presence is just noise: | |
3763 | configurables = [ c for c in self.configurables if c.__class__.class_traits(config=True) ] |
|
3763 | configurables = [ c for c in self.configurables if c.__class__.class_traits(config=True) ] | |
3764 | classnames = [ c.__class__.__name__ for c in configurables ] |
|
3764 | classnames = [ c.__class__.__name__ for c in configurables ] | |
3765 |
|
3765 | |||
3766 | line = s.strip() |
|
3766 | line = s.strip() | |
3767 | if not line: |
|
3767 | if not line: | |
3768 | # print available configurable names |
|
3768 | # print available configurable names | |
3769 | print "Available objects for config:" |
|
3769 | print "Available objects for config:" | |
3770 | for name in classnames: |
|
3770 | for name in classnames: | |
3771 | print " ", name |
|
3771 | print " ", name | |
3772 | return |
|
3772 | return | |
3773 | elif line in classnames: |
|
3773 | elif line in classnames: | |
3774 | # `%config TerminalInteractiveShell` will print trait info for |
|
3774 | # `%config TerminalInteractiveShell` will print trait info for | |
3775 | # TerminalInteractiveShell |
|
3775 | # TerminalInteractiveShell | |
3776 | c = configurables[classnames.index(line)] |
|
3776 | c = configurables[classnames.index(line)] | |
3777 | cls = c.__class__ |
|
3777 | cls = c.__class__ | |
3778 | help = cls.class_get_help(c) |
|
3778 | help = cls.class_get_help(c) | |
3779 | # strip leading '--' from cl-args: |
|
3779 | # strip leading '--' from cl-args: | |
3780 | help = re.sub(re.compile(r'^--', re.MULTILINE), '', help) |
|
3780 | help = re.sub(re.compile(r'^--', re.MULTILINE), '', help) | |
3781 | print help |
|
3781 | print help | |
3782 | return |
|
3782 | return | |
3783 | elif '=' not in line: |
|
3783 | elif '=' not in line: | |
3784 | raise UsageError("Invalid config statement: %r, should be Class.trait = value" % line) |
|
3784 | raise UsageError("Invalid config statement: %r, should be Class.trait = value" % line) | |
3785 |
|
3785 | |||
3786 |
|
3786 | |||
3787 | # otherwise, assume we are setting configurables. |
|
3787 | # otherwise, assume we are setting configurables. | |
3788 | # leave quotes on args when splitting, because we want |
|
3788 | # leave quotes on args when splitting, because we want | |
3789 | # unquoted args to eval in user_ns |
|
3789 | # unquoted args to eval in user_ns | |
3790 | cfg = Config() |
|
3790 | cfg = Config() | |
3791 | exec "cfg."+line in locals(), self.user_ns |
|
3791 | exec "cfg."+line in locals(), self.user_ns | |
3792 |
|
3792 | |||
3793 | for configurable in configurables: |
|
3793 | for configurable in configurables: | |
3794 | try: |
|
3794 | try: | |
3795 | configurable.update_config(cfg) |
|
3795 | configurable.update_config(cfg) | |
3796 | except Exception as e: |
|
3796 | except Exception as e: | |
3797 | error(e) |
|
3797 | error(e) | |
3798 |
|
3798 | |||
3799 | # end Magic |
|
3799 | # end Magic |
@@ -1,392 +1,392 b'' | |||||
1 | """Generic testing tools. |
|
1 | """Generic testing tools. | |
2 |
|
2 | |||
3 | In particular, this module exposes a set of top-level assert* functions that |
|
3 | In particular, this module exposes a set of top-level assert* functions that | |
4 | can be used in place of nose.tools.assert* in method generators (the ones in |
|
4 | can be used in place of nose.tools.assert* in method generators (the ones in | |
5 | nose can not, at least as of nose 0.10.4). |
|
5 | nose can not, at least as of nose 0.10.4). | |
6 |
|
6 | |||
7 |
|
7 | |||
8 | Authors |
|
8 | Authors | |
9 | ------- |
|
9 | ------- | |
10 | - Fernando Perez <Fernando.Perez@berkeley.edu> |
|
10 | - Fernando Perez <Fernando.Perez@berkeley.edu> | |
11 | """ |
|
11 | """ | |
12 |
|
12 | |||
13 | from __future__ import absolute_import |
|
13 | from __future__ import absolute_import | |
14 |
|
14 | |||
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 | # Copyright (C) 2009-2011 The IPython Development Team |
|
16 | # Copyright (C) 2009-2011 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 os |
|
26 | import os | |
27 | import re |
|
27 | import re | |
28 | import sys |
|
28 | import sys | |
29 | import tempfile |
|
29 | import tempfile | |
30 |
|
30 | |||
31 | from contextlib import contextmanager |
|
31 | from contextlib import contextmanager | |
32 | from io import StringIO |
|
32 | from io import StringIO | |
33 |
|
33 | |||
34 | try: |
|
34 | try: | |
35 | # These tools are used by parts of the runtime, so we make the nose |
|
35 | # These tools are used by parts of the runtime, so we make the nose | |
36 | # dependency optional at this point. Nose is a hard dependency to run the |
|
36 | # dependency optional at this point. Nose is a hard dependency to run the | |
37 | # test suite, but NOT to use ipython itself. |
|
37 | # test suite, but NOT to use ipython itself. | |
38 | import nose.tools as nt |
|
38 | import nose.tools as nt | |
39 | has_nose = True |
|
39 | has_nose = True | |
40 | except ImportError: |
|
40 | except ImportError: | |
41 | has_nose = False |
|
41 | has_nose = False | |
42 |
|
42 | |||
43 | from IPython.config.loader import Config |
|
43 | from IPython.config.loader import Config | |
44 | from IPython.utils.process import find_cmd, getoutputerror |
|
44 | from IPython.utils.process import find_cmd, getoutputerror | |
45 | from IPython.utils.text import list_strings |
|
45 | from IPython.utils.text import list_strings | |
46 | from IPython.utils.io import temp_pyfile, Tee |
|
46 | from IPython.utils.io import temp_pyfile, Tee | |
47 | from IPython.utils import py3compat |
|
47 | from IPython.utils import py3compat | |
48 |
from IPython.utils.encoding import |
|
48 | from IPython.utils.encoding import DEFAULT_ENCODING | |
49 |
|
49 | |||
50 | from . import decorators as dec |
|
50 | from . import decorators as dec | |
51 | from . import skipdoctest |
|
51 | from . import skipdoctest | |
52 |
|
52 | |||
53 | #----------------------------------------------------------------------------- |
|
53 | #----------------------------------------------------------------------------- | |
54 | # Globals |
|
54 | # Globals | |
55 | #----------------------------------------------------------------------------- |
|
55 | #----------------------------------------------------------------------------- | |
56 |
|
56 | |||
57 | # Make a bunch of nose.tools assert wrappers that can be used in test |
|
57 | # Make a bunch of nose.tools assert wrappers that can be used in test | |
58 | # generators. This will expose an assert* function for each one in nose.tools. |
|
58 | # generators. This will expose an assert* function for each one in nose.tools. | |
59 |
|
59 | |||
60 | _tpl = """ |
|
60 | _tpl = """ | |
61 | def %(name)s(*a,**kw): |
|
61 | def %(name)s(*a,**kw): | |
62 | return nt.%(name)s(*a,**kw) |
|
62 | return nt.%(name)s(*a,**kw) | |
63 | """ |
|
63 | """ | |
64 |
|
64 | |||
65 | if has_nose: |
|
65 | if has_nose: | |
66 | for _x in [a for a in dir(nt) if a.startswith('assert')]: |
|
66 | for _x in [a for a in dir(nt) if a.startswith('assert')]: | |
67 | exec _tpl % dict(name=_x) |
|
67 | exec _tpl % dict(name=_x) | |
68 |
|
68 | |||
69 | #----------------------------------------------------------------------------- |
|
69 | #----------------------------------------------------------------------------- | |
70 | # Functions and classes |
|
70 | # Functions and classes | |
71 | #----------------------------------------------------------------------------- |
|
71 | #----------------------------------------------------------------------------- | |
72 |
|
72 | |||
73 | # The docstring for full_path doctests differently on win32 (different path |
|
73 | # The docstring for full_path doctests differently on win32 (different path | |
74 | # separator) so just skip the doctest there. The example remains informative. |
|
74 | # separator) so just skip the doctest there. The example remains informative. | |
75 | doctest_deco = skipdoctest.skip_doctest if sys.platform == 'win32' else dec.null_deco |
|
75 | doctest_deco = skipdoctest.skip_doctest if sys.platform == 'win32' else dec.null_deco | |
76 |
|
76 | |||
77 | @doctest_deco |
|
77 | @doctest_deco | |
78 | def full_path(startPath,files): |
|
78 | def full_path(startPath,files): | |
79 | """Make full paths for all the listed files, based on startPath. |
|
79 | """Make full paths for all the listed files, based on startPath. | |
80 |
|
80 | |||
81 | Only the base part of startPath is kept, since this routine is typically |
|
81 | Only the base part of startPath is kept, since this routine is typically | |
82 | used with a script's __file__ variable as startPath. The base of startPath |
|
82 | used with a script's __file__ variable as startPath. The base of startPath | |
83 | is then prepended to all the listed files, forming the output list. |
|
83 | is then prepended to all the listed files, forming the output list. | |
84 |
|
84 | |||
85 | Parameters |
|
85 | Parameters | |
86 | ---------- |
|
86 | ---------- | |
87 | startPath : string |
|
87 | startPath : string | |
88 | Initial path to use as the base for the results. This path is split |
|
88 | Initial path to use as the base for the results. This path is split | |
89 | using os.path.split() and only its first component is kept. |
|
89 | using os.path.split() and only its first component is kept. | |
90 |
|
90 | |||
91 | files : string or list |
|
91 | files : string or list | |
92 | One or more files. |
|
92 | One or more files. | |
93 |
|
93 | |||
94 | Examples |
|
94 | Examples | |
95 | -------- |
|
95 | -------- | |
96 |
|
96 | |||
97 | >>> full_path('/foo/bar.py',['a.txt','b.txt']) |
|
97 | >>> full_path('/foo/bar.py',['a.txt','b.txt']) | |
98 | ['/foo/a.txt', '/foo/b.txt'] |
|
98 | ['/foo/a.txt', '/foo/b.txt'] | |
99 |
|
99 | |||
100 | >>> full_path('/foo',['a.txt','b.txt']) |
|
100 | >>> full_path('/foo',['a.txt','b.txt']) | |
101 | ['/a.txt', '/b.txt'] |
|
101 | ['/a.txt', '/b.txt'] | |
102 |
|
102 | |||
103 | If a single file is given, the output is still a list: |
|
103 | If a single file is given, the output is still a list: | |
104 | >>> full_path('/foo','a.txt') |
|
104 | >>> full_path('/foo','a.txt') | |
105 | ['/a.txt'] |
|
105 | ['/a.txt'] | |
106 | """ |
|
106 | """ | |
107 |
|
107 | |||
108 | files = list_strings(files) |
|
108 | files = list_strings(files) | |
109 | base = os.path.split(startPath)[0] |
|
109 | base = os.path.split(startPath)[0] | |
110 | return [ os.path.join(base,f) for f in files ] |
|
110 | return [ os.path.join(base,f) for f in files ] | |
111 |
|
111 | |||
112 |
|
112 | |||
113 | def parse_test_output(txt): |
|
113 | def parse_test_output(txt): | |
114 | """Parse the output of a test run and return errors, failures. |
|
114 | """Parse the output of a test run and return errors, failures. | |
115 |
|
115 | |||
116 | Parameters |
|
116 | Parameters | |
117 | ---------- |
|
117 | ---------- | |
118 | txt : str |
|
118 | txt : str | |
119 | Text output of a test run, assumed to contain a line of one of the |
|
119 | Text output of a test run, assumed to contain a line of one of the | |
120 | following forms:: |
|
120 | following forms:: | |
121 | 'FAILED (errors=1)' |
|
121 | 'FAILED (errors=1)' | |
122 | 'FAILED (failures=1)' |
|
122 | 'FAILED (failures=1)' | |
123 | 'FAILED (errors=1, failures=1)' |
|
123 | 'FAILED (errors=1, failures=1)' | |
124 |
|
124 | |||
125 | Returns |
|
125 | Returns | |
126 | ------- |
|
126 | ------- | |
127 | nerr, nfail: number of errors and failures. |
|
127 | nerr, nfail: number of errors and failures. | |
128 | """ |
|
128 | """ | |
129 |
|
129 | |||
130 | err_m = re.search(r'^FAILED \(errors=(\d+)\)', txt, re.MULTILINE) |
|
130 | err_m = re.search(r'^FAILED \(errors=(\d+)\)', txt, re.MULTILINE) | |
131 | if err_m: |
|
131 | if err_m: | |
132 | nerr = int(err_m.group(1)) |
|
132 | nerr = int(err_m.group(1)) | |
133 | nfail = 0 |
|
133 | nfail = 0 | |
134 | return nerr, nfail |
|
134 | return nerr, nfail | |
135 |
|
135 | |||
136 | fail_m = re.search(r'^FAILED \(failures=(\d+)\)', txt, re.MULTILINE) |
|
136 | fail_m = re.search(r'^FAILED \(failures=(\d+)\)', txt, re.MULTILINE) | |
137 | if fail_m: |
|
137 | if fail_m: | |
138 | nerr = 0 |
|
138 | nerr = 0 | |
139 | nfail = int(fail_m.group(1)) |
|
139 | nfail = int(fail_m.group(1)) | |
140 | return nerr, nfail |
|
140 | return nerr, nfail | |
141 |
|
141 | |||
142 | both_m = re.search(r'^FAILED \(errors=(\d+), failures=(\d+)\)', txt, |
|
142 | both_m = re.search(r'^FAILED \(errors=(\d+), failures=(\d+)\)', txt, | |
143 | re.MULTILINE) |
|
143 | re.MULTILINE) | |
144 | if both_m: |
|
144 | if both_m: | |
145 | nerr = int(both_m.group(1)) |
|
145 | nerr = int(both_m.group(1)) | |
146 | nfail = int(both_m.group(2)) |
|
146 | nfail = int(both_m.group(2)) | |
147 | return nerr, nfail |
|
147 | return nerr, nfail | |
148 |
|
148 | |||
149 | # If the input didn't match any of these forms, assume no error/failures |
|
149 | # If the input didn't match any of these forms, assume no error/failures | |
150 | return 0, 0 |
|
150 | return 0, 0 | |
151 |
|
151 | |||
152 |
|
152 | |||
153 | # So nose doesn't think this is a test |
|
153 | # So nose doesn't think this is a test | |
154 | parse_test_output.__test__ = False |
|
154 | parse_test_output.__test__ = False | |
155 |
|
155 | |||
156 |
|
156 | |||
157 | def default_argv(): |
|
157 | def default_argv(): | |
158 | """Return a valid default argv for creating testing instances of ipython""" |
|
158 | """Return a valid default argv for creating testing instances of ipython""" | |
159 |
|
159 | |||
160 | return ['--quick', # so no config file is loaded |
|
160 | return ['--quick', # so no config file is loaded | |
161 | # Other defaults to minimize side effects on stdout |
|
161 | # Other defaults to minimize side effects on stdout | |
162 | '--colors=NoColor', '--no-term-title','--no-banner', |
|
162 | '--colors=NoColor', '--no-term-title','--no-banner', | |
163 | '--autocall=0'] |
|
163 | '--autocall=0'] | |
164 |
|
164 | |||
165 |
|
165 | |||
166 | def default_config(): |
|
166 | def default_config(): | |
167 | """Return a config object with good defaults for testing.""" |
|
167 | """Return a config object with good defaults for testing.""" | |
168 | config = Config() |
|
168 | config = Config() | |
169 | config.TerminalInteractiveShell.colors = 'NoColor' |
|
169 | config.TerminalInteractiveShell.colors = 'NoColor' | |
170 | config.TerminalTerminalInteractiveShell.term_title = False, |
|
170 | config.TerminalTerminalInteractiveShell.term_title = False, | |
171 | config.TerminalInteractiveShell.autocall = 0 |
|
171 | config.TerminalInteractiveShell.autocall = 0 | |
172 | config.HistoryManager.hist_file = tempfile.mktemp(u'test_hist.sqlite') |
|
172 | config.HistoryManager.hist_file = tempfile.mktemp(u'test_hist.sqlite') | |
173 | config.HistoryManager.db_cache_size = 10000 |
|
173 | config.HistoryManager.db_cache_size = 10000 | |
174 | return config |
|
174 | return config | |
175 |
|
175 | |||
176 |
|
176 | |||
177 | def ipexec(fname, options=None): |
|
177 | def ipexec(fname, options=None): | |
178 | """Utility to call 'ipython filename'. |
|
178 | """Utility to call 'ipython filename'. | |
179 |
|
179 | |||
180 | Starts IPython witha minimal and safe configuration to make startup as fast |
|
180 | Starts IPython witha minimal and safe configuration to make startup as fast | |
181 | as possible. |
|
181 | as possible. | |
182 |
|
182 | |||
183 | Note that this starts IPython in a subprocess! |
|
183 | Note that this starts IPython in a subprocess! | |
184 |
|
184 | |||
185 | Parameters |
|
185 | Parameters | |
186 | ---------- |
|
186 | ---------- | |
187 | fname : str |
|
187 | fname : str | |
188 | Name of file to be executed (should have .py or .ipy extension). |
|
188 | Name of file to be executed (should have .py or .ipy extension). | |
189 |
|
189 | |||
190 | options : optional, list |
|
190 | options : optional, list | |
191 | Extra command-line flags to be passed to IPython. |
|
191 | Extra command-line flags to be passed to IPython. | |
192 |
|
192 | |||
193 | Returns |
|
193 | Returns | |
194 | ------- |
|
194 | ------- | |
195 | (stdout, stderr) of ipython subprocess. |
|
195 | (stdout, stderr) of ipython subprocess. | |
196 | """ |
|
196 | """ | |
197 | if options is None: options = [] |
|
197 | if options is None: options = [] | |
198 |
|
198 | |||
199 | # For these subprocess calls, eliminate all prompt printing so we only see |
|
199 | # For these subprocess calls, eliminate all prompt printing so we only see | |
200 | # output from script execution |
|
200 | # output from script execution | |
201 | prompt_opts = [ '--PromptManager.in_template=""', |
|
201 | prompt_opts = [ '--PromptManager.in_template=""', | |
202 | '--PromptManager.in2_template=""', |
|
202 | '--PromptManager.in2_template=""', | |
203 | '--PromptManager.out_template=""' |
|
203 | '--PromptManager.out_template=""' | |
204 | ] |
|
204 | ] | |
205 | cmdargs = ' '.join(default_argv() + prompt_opts + options) |
|
205 | cmdargs = ' '.join(default_argv() + prompt_opts + options) | |
206 |
|
206 | |||
207 | _ip = get_ipython() |
|
207 | _ip = get_ipython() | |
208 | test_dir = os.path.dirname(__file__) |
|
208 | test_dir = os.path.dirname(__file__) | |
209 |
|
209 | |||
210 | ipython_cmd = find_cmd('ipython3' if py3compat.PY3 else 'ipython') |
|
210 | ipython_cmd = find_cmd('ipython3' if py3compat.PY3 else 'ipython') | |
211 | # Absolute path for filename |
|
211 | # Absolute path for filename | |
212 | full_fname = os.path.join(test_dir, fname) |
|
212 | full_fname = os.path.join(test_dir, fname) | |
213 | full_cmd = '%s %s %s' % (ipython_cmd, cmdargs, full_fname) |
|
213 | full_cmd = '%s %s %s' % (ipython_cmd, cmdargs, full_fname) | |
214 | #print >> sys.stderr, 'FULL CMD:', full_cmd # dbg |
|
214 | #print >> sys.stderr, 'FULL CMD:', full_cmd # dbg | |
215 | out, err = getoutputerror(full_cmd) |
|
215 | out, err = getoutputerror(full_cmd) | |
216 | # `import readline` causes 'ESC[?1034h' to be output sometimes, |
|
216 | # `import readline` causes 'ESC[?1034h' to be output sometimes, | |
217 | # so strip that out before doing comparisons |
|
217 | # so strip that out before doing comparisons | |
218 | if out: |
|
218 | if out: | |
219 | out = re.sub(r'\x1b\[[^h]+h', '', out) |
|
219 | out = re.sub(r'\x1b\[[^h]+h', '', out) | |
220 | return out, err |
|
220 | return out, err | |
221 |
|
221 | |||
222 |
|
222 | |||
223 | def ipexec_validate(fname, expected_out, expected_err='', |
|
223 | def ipexec_validate(fname, expected_out, expected_err='', | |
224 | options=None): |
|
224 | options=None): | |
225 | """Utility to call 'ipython filename' and validate output/error. |
|
225 | """Utility to call 'ipython filename' and validate output/error. | |
226 |
|
226 | |||
227 | This function raises an AssertionError if the validation fails. |
|
227 | This function raises an AssertionError if the validation fails. | |
228 |
|
228 | |||
229 | Note that this starts IPython in a subprocess! |
|
229 | Note that this starts IPython in a subprocess! | |
230 |
|
230 | |||
231 | Parameters |
|
231 | Parameters | |
232 | ---------- |
|
232 | ---------- | |
233 | fname : str |
|
233 | fname : str | |
234 | Name of the file to be executed (should have .py or .ipy extension). |
|
234 | Name of the file to be executed (should have .py or .ipy extension). | |
235 |
|
235 | |||
236 | expected_out : str |
|
236 | expected_out : str | |
237 | Expected stdout of the process. |
|
237 | Expected stdout of the process. | |
238 |
|
238 | |||
239 | expected_err : optional, str |
|
239 | expected_err : optional, str | |
240 | Expected stderr of the process. |
|
240 | Expected stderr of the process. | |
241 |
|
241 | |||
242 | options : optional, list |
|
242 | options : optional, list | |
243 | Extra command-line flags to be passed to IPython. |
|
243 | Extra command-line flags to be passed to IPython. | |
244 |
|
244 | |||
245 | Returns |
|
245 | Returns | |
246 | ------- |
|
246 | ------- | |
247 | None |
|
247 | None | |
248 | """ |
|
248 | """ | |
249 |
|
249 | |||
250 | import nose.tools as nt |
|
250 | import nose.tools as nt | |
251 |
|
251 | |||
252 | out, err = ipexec(fname, options) |
|
252 | out, err = ipexec(fname, options) | |
253 | #print 'OUT', out # dbg |
|
253 | #print 'OUT', out # dbg | |
254 | #print 'ERR', err # dbg |
|
254 | #print 'ERR', err # dbg | |
255 | # If there are any errors, we must check those befor stdout, as they may be |
|
255 | # If there are any errors, we must check those befor stdout, as they may be | |
256 | # more informative than simply having an empty stdout. |
|
256 | # more informative than simply having an empty stdout. | |
257 | if err: |
|
257 | if err: | |
258 | if expected_err: |
|
258 | if expected_err: | |
259 | nt.assert_equals(err.strip(), expected_err.strip()) |
|
259 | nt.assert_equals(err.strip(), expected_err.strip()) | |
260 | else: |
|
260 | else: | |
261 | raise ValueError('Running file %r produced error: %r' % |
|
261 | raise ValueError('Running file %r produced error: %r' % | |
262 | (fname, err)) |
|
262 | (fname, err)) | |
263 | # If no errors or output on stderr was expected, match stdout |
|
263 | # If no errors or output on stderr was expected, match stdout | |
264 | nt.assert_equals(out.strip(), expected_out.strip()) |
|
264 | nt.assert_equals(out.strip(), expected_out.strip()) | |
265 |
|
265 | |||
266 |
|
266 | |||
267 | class TempFileMixin(object): |
|
267 | class TempFileMixin(object): | |
268 | """Utility class to create temporary Python/IPython files. |
|
268 | """Utility class to create temporary Python/IPython files. | |
269 |
|
269 | |||
270 | Meant as a mixin class for test cases.""" |
|
270 | Meant as a mixin class for test cases.""" | |
271 |
|
271 | |||
272 | def mktmp(self, src, ext='.py'): |
|
272 | def mktmp(self, src, ext='.py'): | |
273 | """Make a valid python temp file.""" |
|
273 | """Make a valid python temp file.""" | |
274 | fname, f = temp_pyfile(src, ext) |
|
274 | fname, f = temp_pyfile(src, ext) | |
275 | self.tmpfile = f |
|
275 | self.tmpfile = f | |
276 | self.fname = fname |
|
276 | self.fname = fname | |
277 |
|
277 | |||
278 | def tearDown(self): |
|
278 | def tearDown(self): | |
279 | if hasattr(self, 'tmpfile'): |
|
279 | if hasattr(self, 'tmpfile'): | |
280 | # If the tmpfile wasn't made because of skipped tests, like in |
|
280 | # If the tmpfile wasn't made because of skipped tests, like in | |
281 | # win32, there's nothing to cleanup. |
|
281 | # win32, there's nothing to cleanup. | |
282 | self.tmpfile.close() |
|
282 | self.tmpfile.close() | |
283 | try: |
|
283 | try: | |
284 | os.unlink(self.fname) |
|
284 | os.unlink(self.fname) | |
285 | except: |
|
285 | except: | |
286 | # On Windows, even though we close the file, we still can't |
|
286 | # On Windows, even though we close the file, we still can't | |
287 | # delete it. I have no clue why |
|
287 | # delete it. I have no clue why | |
288 | pass |
|
288 | pass | |
289 |
|
289 | |||
290 | pair_fail_msg = ("Testing {0}\n\n" |
|
290 | pair_fail_msg = ("Testing {0}\n\n" | |
291 | "In:\n" |
|
291 | "In:\n" | |
292 | " {1!r}\n" |
|
292 | " {1!r}\n" | |
293 | "Expected:\n" |
|
293 | "Expected:\n" | |
294 | " {2!r}\n" |
|
294 | " {2!r}\n" | |
295 | "Got:\n" |
|
295 | "Got:\n" | |
296 | " {3!r}\n") |
|
296 | " {3!r}\n") | |
297 | def check_pairs(func, pairs): |
|
297 | def check_pairs(func, pairs): | |
298 | """Utility function for the common case of checking a function with a |
|
298 | """Utility function for the common case of checking a function with a | |
299 | sequence of input/output pairs. |
|
299 | sequence of input/output pairs. | |
300 |
|
300 | |||
301 | Parameters |
|
301 | Parameters | |
302 | ---------- |
|
302 | ---------- | |
303 | func : callable |
|
303 | func : callable | |
304 | The function to be tested. Should accept a single argument. |
|
304 | The function to be tested. Should accept a single argument. | |
305 | pairs : iterable |
|
305 | pairs : iterable | |
306 | A list of (input, expected_output) tuples. |
|
306 | A list of (input, expected_output) tuples. | |
307 |
|
307 | |||
308 | Returns |
|
308 | Returns | |
309 | ------- |
|
309 | ------- | |
310 | None. Raises an AssertionError if any output does not match the expected |
|
310 | None. Raises an AssertionError if any output does not match the expected | |
311 | value. |
|
311 | value. | |
312 | """ |
|
312 | """ | |
313 | name = getattr(func, "func_name", getattr(func, "__name__", "<unknown>")) |
|
313 | name = getattr(func, "func_name", getattr(func, "__name__", "<unknown>")) | |
314 | for inp, expected in pairs: |
|
314 | for inp, expected in pairs: | |
315 | out = func(inp) |
|
315 | out = func(inp) | |
316 | assert out == expected, pair_fail_msg.format(name, inp, expected, out) |
|
316 | assert out == expected, pair_fail_msg.format(name, inp, expected, out) | |
317 |
|
317 | |||
318 |
|
318 | |||
319 | if py3compat.PY3: |
|
319 | if py3compat.PY3: | |
320 | MyStringIO = StringIO |
|
320 | MyStringIO = StringIO | |
321 | else: |
|
321 | else: | |
322 | # In Python 2, stdout/stderr can have either bytes or unicode written to them, |
|
322 | # In Python 2, stdout/stderr can have either bytes or unicode written to them, | |
323 | # so we need a class that can handle both. |
|
323 | # so we need a class that can handle both. | |
324 | class MyStringIO(StringIO): |
|
324 | class MyStringIO(StringIO): | |
325 | def write(self, s): |
|
325 | def write(self, s): | |
326 |
s = py3compat.cast_unicode(s, encoding= |
|
326 | s = py3compat.cast_unicode(s, encoding=DEFAULT_ENCODING) | |
327 | super(MyStringIO, self).write(s) |
|
327 | super(MyStringIO, self).write(s) | |
328 |
|
328 | |||
329 | notprinted_msg = """Did not find {0!r} in printed output (on {1}): |
|
329 | notprinted_msg = """Did not find {0!r} in printed output (on {1}): | |
330 | {2!r}""" |
|
330 | {2!r}""" | |
331 |
|
331 | |||
332 | class AssertPrints(object): |
|
332 | class AssertPrints(object): | |
333 | """Context manager for testing that code prints certain text. |
|
333 | """Context manager for testing that code prints certain text. | |
334 |
|
334 | |||
335 | Examples |
|
335 | Examples | |
336 | -------- |
|
336 | -------- | |
337 | >>> with AssertPrints("abc", suppress=False): |
|
337 | >>> with AssertPrints("abc", suppress=False): | |
338 | ... print "abcd" |
|
338 | ... print "abcd" | |
339 | ... print "def" |
|
339 | ... print "def" | |
340 | ... |
|
340 | ... | |
341 | abcd |
|
341 | abcd | |
342 | def |
|
342 | def | |
343 | """ |
|
343 | """ | |
344 | def __init__(self, s, channel='stdout', suppress=True): |
|
344 | def __init__(self, s, channel='stdout', suppress=True): | |
345 | self.s = s |
|
345 | self.s = s | |
346 | self.channel = channel |
|
346 | self.channel = channel | |
347 | self.suppress = suppress |
|
347 | self.suppress = suppress | |
348 |
|
348 | |||
349 | def __enter__(self): |
|
349 | def __enter__(self): | |
350 | self.orig_stream = getattr(sys, self.channel) |
|
350 | self.orig_stream = getattr(sys, self.channel) | |
351 | self.buffer = MyStringIO() |
|
351 | self.buffer = MyStringIO() | |
352 | self.tee = Tee(self.buffer, channel=self.channel) |
|
352 | self.tee = Tee(self.buffer, channel=self.channel) | |
353 | setattr(sys, self.channel, self.buffer if self.suppress else self.tee) |
|
353 | setattr(sys, self.channel, self.buffer if self.suppress else self.tee) | |
354 |
|
354 | |||
355 | def __exit__(self, etype, value, traceback): |
|
355 | def __exit__(self, etype, value, traceback): | |
356 | self.tee.flush() |
|
356 | self.tee.flush() | |
357 | setattr(sys, self.channel, self.orig_stream) |
|
357 | setattr(sys, self.channel, self.orig_stream) | |
358 | printed = self.buffer.getvalue() |
|
358 | printed = self.buffer.getvalue() | |
359 | assert self.s in printed, notprinted_msg.format(self.s, self.channel, printed) |
|
359 | assert self.s in printed, notprinted_msg.format(self.s, self.channel, printed) | |
360 | return False |
|
360 | return False | |
361 |
|
361 | |||
362 | class AssertNotPrints(AssertPrints): |
|
362 | class AssertNotPrints(AssertPrints): | |
363 | """Context manager for checking that certain output *isn't* produced. |
|
363 | """Context manager for checking that certain output *isn't* produced. | |
364 |
|
364 | |||
365 | Counterpart of AssertPrints""" |
|
365 | Counterpart of AssertPrints""" | |
366 | def __exit__(self, etype, value, traceback): |
|
366 | def __exit__(self, etype, value, traceback): | |
367 | self.tee.flush() |
|
367 | self.tee.flush() | |
368 | setattr(sys, self.channel, self.orig_stream) |
|
368 | setattr(sys, self.channel, self.orig_stream) | |
369 | printed = self.buffer.getvalue() |
|
369 | printed = self.buffer.getvalue() | |
370 | assert self.s not in printed, notprinted_msg.format(self.s, self.channel, printed) |
|
370 | assert self.s not in printed, notprinted_msg.format(self.s, self.channel, printed) | |
371 | return False |
|
371 | return False | |
372 |
|
372 | |||
373 | @contextmanager |
|
373 | @contextmanager | |
374 | def mute_warn(): |
|
374 | def mute_warn(): | |
375 | from IPython.utils import warn |
|
375 | from IPython.utils import warn | |
376 | save_warn = warn.warn |
|
376 | save_warn = warn.warn | |
377 | warn.warn = lambda *a, **kw: None |
|
377 | warn.warn = lambda *a, **kw: None | |
378 | try: |
|
378 | try: | |
379 | yield |
|
379 | yield | |
380 | finally: |
|
380 | finally: | |
381 | warn.warn = save_warn |
|
381 | warn.warn = save_warn | |
382 |
|
382 | |||
383 | @contextmanager |
|
383 | @contextmanager | |
384 | def make_tempfile(name): |
|
384 | def make_tempfile(name): | |
385 | """ Create an empty, named, temporary file for the duration of the context. |
|
385 | """ Create an empty, named, temporary file for the duration of the context. | |
386 | """ |
|
386 | """ | |
387 | f = open(name, 'w') |
|
387 | f = open(name, 'w') | |
388 | f.close() |
|
388 | f.close() | |
389 | try: |
|
389 | try: | |
390 | yield |
|
390 | yield | |
391 | finally: |
|
391 | finally: | |
392 | os.unlink(name) |
|
392 | os.unlink(name) |
@@ -1,198 +1,198 b'' | |||||
1 | """Posix-specific implementation of process utilities. |
|
1 | """Posix-specific implementation of process utilities. | |
2 |
|
2 | |||
3 | This file is only meant to be imported by process.py, not by end-users. |
|
3 | This file is only meant to be imported by process.py, not by end-users. | |
4 | """ |
|
4 | """ | |
5 |
|
5 | |||
6 | #----------------------------------------------------------------------------- |
|
6 | #----------------------------------------------------------------------------- | |
7 | # Copyright (C) 2010-2011 The IPython Development Team |
|
7 | # Copyright (C) 2010-2011 The IPython Development Team | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
10 | # the file COPYING, distributed as part of this software. |
|
10 | # the file COPYING, distributed as part of this software. | |
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 |
|
12 | |||
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 | from __future__ import print_function |
|
16 | from __future__ import print_function | |
17 |
|
17 | |||
18 | # Stdlib |
|
18 | # Stdlib | |
19 | import subprocess as sp |
|
19 | import subprocess as sp | |
20 | import sys |
|
20 | import sys | |
21 |
|
21 | |||
22 | from IPython.external import pexpect |
|
22 | from IPython.external import pexpect | |
23 |
|
23 | |||
24 | # Our own |
|
24 | # Our own | |
25 | from .autoattr import auto_attr |
|
25 | from .autoattr import auto_attr | |
26 | from ._process_common import getoutput, arg_split |
|
26 | from ._process_common import getoutput, arg_split | |
27 | from IPython.utils import text |
|
27 | from IPython.utils import text | |
28 | from IPython.utils import py3compat |
|
28 | from IPython.utils import py3compat | |
29 |
from IPython.utils.encoding import |
|
29 | from IPython.utils.encoding import DEFAULT_ENCODING | |
30 |
|
30 | |||
31 | #----------------------------------------------------------------------------- |
|
31 | #----------------------------------------------------------------------------- | |
32 | # Function definitions |
|
32 | # Function definitions | |
33 | #----------------------------------------------------------------------------- |
|
33 | #----------------------------------------------------------------------------- | |
34 |
|
34 | |||
35 | def _find_cmd(cmd): |
|
35 | def _find_cmd(cmd): | |
36 | """Find the full path to a command using which.""" |
|
36 | """Find the full path to a command using which.""" | |
37 |
|
37 | |||
38 | path = sp.Popen(['/usr/bin/env', 'which', cmd], |
|
38 | path = sp.Popen(['/usr/bin/env', 'which', cmd], | |
39 | stdout=sp.PIPE).communicate()[0] |
|
39 | stdout=sp.PIPE).communicate()[0] | |
40 | return py3compat.bytes_to_str(path) |
|
40 | return py3compat.bytes_to_str(path) | |
41 |
|
41 | |||
42 |
|
42 | |||
43 | class ProcessHandler(object): |
|
43 | class ProcessHandler(object): | |
44 | """Execute subprocesses under the control of pexpect. |
|
44 | """Execute subprocesses under the control of pexpect. | |
45 | """ |
|
45 | """ | |
46 | # Timeout in seconds to wait on each reading of the subprocess' output. |
|
46 | # Timeout in seconds to wait on each reading of the subprocess' output. | |
47 | # This should not be set too low to avoid cpu overusage from our side, |
|
47 | # This should not be set too low to avoid cpu overusage from our side, | |
48 | # since we read in a loop whose period is controlled by this timeout. |
|
48 | # since we read in a loop whose period is controlled by this timeout. | |
49 | read_timeout = 0.05 |
|
49 | read_timeout = 0.05 | |
50 |
|
50 | |||
51 | # Timeout to give a process if we receive SIGINT, between sending the |
|
51 | # Timeout to give a process if we receive SIGINT, between sending the | |
52 | # SIGINT to the process and forcefully terminating it. |
|
52 | # SIGINT to the process and forcefully terminating it. | |
53 | terminate_timeout = 0.2 |
|
53 | terminate_timeout = 0.2 | |
54 |
|
54 | |||
55 | # File object where stdout and stderr of the subprocess will be written |
|
55 | # File object where stdout and stderr of the subprocess will be written | |
56 | logfile = None |
|
56 | logfile = None | |
57 |
|
57 | |||
58 | # Shell to call for subprocesses to execute |
|
58 | # Shell to call for subprocesses to execute | |
59 | sh = None |
|
59 | sh = None | |
60 |
|
60 | |||
61 | @auto_attr |
|
61 | @auto_attr | |
62 | def sh(self): |
|
62 | def sh(self): | |
63 | sh = pexpect.which('sh') |
|
63 | sh = pexpect.which('sh') | |
64 | if sh is None: |
|
64 | if sh is None: | |
65 | raise OSError('"sh" shell not found') |
|
65 | raise OSError('"sh" shell not found') | |
66 | return sh |
|
66 | return sh | |
67 |
|
67 | |||
68 | def __init__(self, logfile=None, read_timeout=None, terminate_timeout=None): |
|
68 | def __init__(self, logfile=None, read_timeout=None, terminate_timeout=None): | |
69 | """Arguments are used for pexpect calls.""" |
|
69 | """Arguments are used for pexpect calls.""" | |
70 | self.read_timeout = (ProcessHandler.read_timeout if read_timeout is |
|
70 | self.read_timeout = (ProcessHandler.read_timeout if read_timeout is | |
71 | None else read_timeout) |
|
71 | None else read_timeout) | |
72 | self.terminate_timeout = (ProcessHandler.terminate_timeout if |
|
72 | self.terminate_timeout = (ProcessHandler.terminate_timeout if | |
73 | terminate_timeout is None else |
|
73 | terminate_timeout is None else | |
74 | terminate_timeout) |
|
74 | terminate_timeout) | |
75 | self.logfile = sys.stdout if logfile is None else logfile |
|
75 | self.logfile = sys.stdout if logfile is None else logfile | |
76 |
|
76 | |||
77 | def getoutput(self, cmd): |
|
77 | def getoutput(self, cmd): | |
78 | """Run a command and return its stdout/stderr as a string. |
|
78 | """Run a command and return its stdout/stderr as a string. | |
79 |
|
79 | |||
80 | Parameters |
|
80 | Parameters | |
81 | ---------- |
|
81 | ---------- | |
82 | cmd : str |
|
82 | cmd : str | |
83 | A command to be executed in the system shell. |
|
83 | A command to be executed in the system shell. | |
84 |
|
84 | |||
85 | Returns |
|
85 | Returns | |
86 | ------- |
|
86 | ------- | |
87 | output : str |
|
87 | output : str | |
88 | A string containing the combination of stdout and stderr from the |
|
88 | A string containing the combination of stdout and stderr from the | |
89 | subprocess, in whatever order the subprocess originally wrote to its |
|
89 | subprocess, in whatever order the subprocess originally wrote to its | |
90 | file descriptors (so the order of the information in this string is the |
|
90 | file descriptors (so the order of the information in this string is the | |
91 | correct order as would be seen if running the command in a terminal). |
|
91 | correct order as would be seen if running the command in a terminal). | |
92 | """ |
|
92 | """ | |
93 | try: |
|
93 | try: | |
94 | return pexpect.run(self.sh, args=['-c', cmd]).replace('\r\n', '\n') |
|
94 | return pexpect.run(self.sh, args=['-c', cmd]).replace('\r\n', '\n') | |
95 | except KeyboardInterrupt: |
|
95 | except KeyboardInterrupt: | |
96 | print('^C', file=sys.stderr, end='') |
|
96 | print('^C', file=sys.stderr, end='') | |
97 |
|
97 | |||
98 | def getoutput_pexpect(self, cmd): |
|
98 | def getoutput_pexpect(self, cmd): | |
99 | """Run a command and return its stdout/stderr as a string. |
|
99 | """Run a command and return its stdout/stderr as a string. | |
100 |
|
100 | |||
101 | Parameters |
|
101 | Parameters | |
102 | ---------- |
|
102 | ---------- | |
103 | cmd : str |
|
103 | cmd : str | |
104 | A command to be executed in the system shell. |
|
104 | A command to be executed in the system shell. | |
105 |
|
105 | |||
106 | Returns |
|
106 | Returns | |
107 | ------- |
|
107 | ------- | |
108 | output : str |
|
108 | output : str | |
109 | A string containing the combination of stdout and stderr from the |
|
109 | A string containing the combination of stdout and stderr from the | |
110 | subprocess, in whatever order the subprocess originally wrote to its |
|
110 | subprocess, in whatever order the subprocess originally wrote to its | |
111 | file descriptors (so the order of the information in this string is the |
|
111 | file descriptors (so the order of the information in this string is the | |
112 | correct order as would be seen if running the command in a terminal). |
|
112 | correct order as would be seen if running the command in a terminal). | |
113 | """ |
|
113 | """ | |
114 | try: |
|
114 | try: | |
115 | return pexpect.run(self.sh, args=['-c', cmd]).replace('\r\n', '\n') |
|
115 | return pexpect.run(self.sh, args=['-c', cmd]).replace('\r\n', '\n') | |
116 | except KeyboardInterrupt: |
|
116 | except KeyboardInterrupt: | |
117 | print('^C', file=sys.stderr, end='') |
|
117 | print('^C', file=sys.stderr, end='') | |
118 |
|
118 | |||
119 | def system(self, cmd): |
|
119 | def system(self, cmd): | |
120 | """Execute a command in a subshell. |
|
120 | """Execute a command in a subshell. | |
121 |
|
121 | |||
122 | Parameters |
|
122 | Parameters | |
123 | ---------- |
|
123 | ---------- | |
124 | cmd : str |
|
124 | cmd : str | |
125 | A command to be executed in the system shell. |
|
125 | A command to be executed in the system shell. | |
126 |
|
126 | |||
127 | Returns |
|
127 | Returns | |
128 | ------- |
|
128 | ------- | |
129 | int : child's exitstatus |
|
129 | int : child's exitstatus | |
130 | """ |
|
130 | """ | |
131 | # Get likely encoding for the output. |
|
131 | # Get likely encoding for the output. | |
132 | enc = getdefaultencoding() |
|
132 | enc = DEFAULT_ENCODING | |
133 |
|
133 | |||
134 | # Patterns to match on the output, for pexpect. We read input and |
|
134 | # Patterns to match on the output, for pexpect. We read input and | |
135 | # allow either a short timeout or EOF |
|
135 | # allow either a short timeout or EOF | |
136 | patterns = [pexpect.TIMEOUT, pexpect.EOF] |
|
136 | patterns = [pexpect.TIMEOUT, pexpect.EOF] | |
137 | # the index of the EOF pattern in the list. |
|
137 | # the index of the EOF pattern in the list. | |
138 | # even though we know it's 1, this call means we don't have to worry if |
|
138 | # even though we know it's 1, this call means we don't have to worry if | |
139 | # we change the above list, and forget to change this value: |
|
139 | # we change the above list, and forget to change this value: | |
140 | EOF_index = patterns.index(pexpect.EOF) |
|
140 | EOF_index = patterns.index(pexpect.EOF) | |
141 | # The size of the output stored so far in the process output buffer. |
|
141 | # The size of the output stored so far in the process output buffer. | |
142 | # Since pexpect only appends to this buffer, each time we print we |
|
142 | # Since pexpect only appends to this buffer, each time we print we | |
143 | # record how far we've printed, so that next time we only print *new* |
|
143 | # record how far we've printed, so that next time we only print *new* | |
144 | # content from the buffer. |
|
144 | # content from the buffer. | |
145 | out_size = 0 |
|
145 | out_size = 0 | |
146 | try: |
|
146 | try: | |
147 | # Since we're not really searching the buffer for text patterns, we |
|
147 | # Since we're not really searching the buffer for text patterns, we | |
148 | # can set pexpect's search window to be tiny and it won't matter. |
|
148 | # can set pexpect's search window to be tiny and it won't matter. | |
149 | # We only search for the 'patterns' timeout or EOF, which aren't in |
|
149 | # We only search for the 'patterns' timeout or EOF, which aren't in | |
150 | # the text itself. |
|
150 | # the text itself. | |
151 | #child = pexpect.spawn(pcmd, searchwindowsize=1) |
|
151 | #child = pexpect.spawn(pcmd, searchwindowsize=1) | |
152 | if hasattr(pexpect, 'spawnb'): |
|
152 | if hasattr(pexpect, 'spawnb'): | |
153 | child = pexpect.spawnb(self.sh, args=['-c', cmd]) # Pexpect-U |
|
153 | child = pexpect.spawnb(self.sh, args=['-c', cmd]) # Pexpect-U | |
154 | else: |
|
154 | else: | |
155 | child = pexpect.spawn(self.sh, args=['-c', cmd]) # Vanilla Pexpect |
|
155 | child = pexpect.spawn(self.sh, args=['-c', cmd]) # Vanilla Pexpect | |
156 | flush = sys.stdout.flush |
|
156 | flush = sys.stdout.flush | |
157 | while True: |
|
157 | while True: | |
158 | # res is the index of the pattern that caused the match, so we |
|
158 | # res is the index of the pattern that caused the match, so we | |
159 | # know whether we've finished (if we matched EOF) or not |
|
159 | # know whether we've finished (if we matched EOF) or not | |
160 | res_idx = child.expect_list(patterns, self.read_timeout) |
|
160 | res_idx = child.expect_list(patterns, self.read_timeout) | |
161 | print(child.before[out_size:].decode(enc, 'replace'), end='') |
|
161 | print(child.before[out_size:].decode(enc, 'replace'), end='') | |
162 | flush() |
|
162 | flush() | |
163 | if res_idx==EOF_index: |
|
163 | if res_idx==EOF_index: | |
164 | break |
|
164 | break | |
165 | # Update the pointer to what we've already printed |
|
165 | # Update the pointer to what we've already printed | |
166 | out_size = len(child.before) |
|
166 | out_size = len(child.before) | |
167 | except KeyboardInterrupt: |
|
167 | except KeyboardInterrupt: | |
168 | # We need to send ^C to the process. The ascii code for '^C' is 3 |
|
168 | # We need to send ^C to the process. The ascii code for '^C' is 3 | |
169 | # (the character is known as ETX for 'End of Text', see |
|
169 | # (the character is known as ETX for 'End of Text', see | |
170 | # curses.ascii.ETX). |
|
170 | # curses.ascii.ETX). | |
171 | child.sendline(chr(3)) |
|
171 | child.sendline(chr(3)) | |
172 | # Read and print any more output the program might produce on its |
|
172 | # Read and print any more output the program might produce on its | |
173 | # way out. |
|
173 | # way out. | |
174 | try: |
|
174 | try: | |
175 | out_size = len(child.before) |
|
175 | out_size = len(child.before) | |
176 | child.expect_list(patterns, self.terminate_timeout) |
|
176 | child.expect_list(patterns, self.terminate_timeout) | |
177 | print(child.before[out_size:].decode(enc, 'replace'), end='') |
|
177 | print(child.before[out_size:].decode(enc, 'replace'), end='') | |
178 | sys.stdout.flush() |
|
178 | sys.stdout.flush() | |
179 | except KeyboardInterrupt: |
|
179 | except KeyboardInterrupt: | |
180 | # Impatient users tend to type it multiple times |
|
180 | # Impatient users tend to type it multiple times | |
181 | pass |
|
181 | pass | |
182 | finally: |
|
182 | finally: | |
183 | # Ensure the subprocess really is terminated |
|
183 | # Ensure the subprocess really is terminated | |
184 | child.terminate(force=True) |
|
184 | child.terminate(force=True) | |
185 | # add isalive check, to ensure exitstatus is set: |
|
185 | # add isalive check, to ensure exitstatus is set: | |
186 | child.isalive() |
|
186 | child.isalive() | |
187 | return child.exitstatus |
|
187 | return child.exitstatus | |
188 |
|
188 | |||
189 |
|
189 | |||
190 | # Make system() with a functional interface for outside use. Note that we use |
|
190 | # Make system() with a functional interface for outside use. Note that we use | |
191 | # getoutput() from the _common utils, which is built on top of popen(). Using |
|
191 | # getoutput() from the _common utils, which is built on top of popen(). Using | |
192 | # pexpect to get subprocess output produces difficult to parse output, since |
|
192 | # pexpect to get subprocess output produces difficult to parse output, since | |
193 | # programs think they are talking to a tty and produce highly formatted output |
|
193 | # programs think they are talking to a tty and produce highly formatted output | |
194 | # (ls is a good example) that makes them hard. |
|
194 | # (ls is a good example) that makes them hard. | |
195 | system = ProcessHandler().system |
|
195 | system = ProcessHandler().system | |
196 |
|
196 | |||
197 |
|
197 | |||
198 |
|
198 |
@@ -1,185 +1,185 b'' | |||||
1 | """Windows-specific implementation of process utilities. |
|
1 | """Windows-specific implementation of process utilities. | |
2 |
|
2 | |||
3 | This file is only meant to be imported by process.py, not by end-users. |
|
3 | This file is only meant to be imported by process.py, not by end-users. | |
4 | """ |
|
4 | """ | |
5 |
|
5 | |||
6 | #----------------------------------------------------------------------------- |
|
6 | #----------------------------------------------------------------------------- | |
7 | # Copyright (C) 2010-2011 The IPython Development Team |
|
7 | # Copyright (C) 2010-2011 The IPython Development Team | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
10 | # the file COPYING, distributed as part of this software. |
|
10 | # the file COPYING, distributed as part of this software. | |
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 |
|
12 | |||
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 | from __future__ import print_function |
|
16 | from __future__ import print_function | |
17 |
|
17 | |||
18 | # stdlib |
|
18 | # stdlib | |
19 | import os |
|
19 | import os | |
20 | import sys |
|
20 | import sys | |
21 | import ctypes |
|
21 | import ctypes | |
22 | import msvcrt |
|
22 | import msvcrt | |
23 |
|
23 | |||
24 | from ctypes import c_int, POINTER |
|
24 | from ctypes import c_int, POINTER | |
25 | from ctypes.wintypes import LPCWSTR, HLOCAL |
|
25 | from ctypes.wintypes import LPCWSTR, HLOCAL | |
26 | from subprocess import STDOUT |
|
26 | from subprocess import STDOUT | |
27 |
|
27 | |||
28 | # our own imports |
|
28 | # our own imports | |
29 | from ._process_common import read_no_interrupt, process_handler, arg_split as py_arg_split |
|
29 | from ._process_common import read_no_interrupt, process_handler, arg_split as py_arg_split | |
30 | from . import py3compat |
|
30 | from . import py3compat | |
31 | from . import text |
|
31 | from . import text | |
32 | from .encoding import getdefaultencoding |
|
32 | from .encoding import DEFAULT_ENCODING | |
33 |
|
33 | |||
34 | #----------------------------------------------------------------------------- |
|
34 | #----------------------------------------------------------------------------- | |
35 | # Function definitions |
|
35 | # Function definitions | |
36 | #----------------------------------------------------------------------------- |
|
36 | #----------------------------------------------------------------------------- | |
37 |
|
37 | |||
38 | class AvoidUNCPath(object): |
|
38 | class AvoidUNCPath(object): | |
39 | """A context manager to protect command execution from UNC paths. |
|
39 | """A context manager to protect command execution from UNC paths. | |
40 |
|
40 | |||
41 | In the Win32 API, commands can't be invoked with the cwd being a UNC path. |
|
41 | In the Win32 API, commands can't be invoked with the cwd being a UNC path. | |
42 | This context manager temporarily changes directory to the 'C:' drive on |
|
42 | This context manager temporarily changes directory to the 'C:' drive on | |
43 | entering, and restores the original working directory on exit. |
|
43 | entering, and restores the original working directory on exit. | |
44 |
|
44 | |||
45 | The context manager returns the starting working directory *if* it made a |
|
45 | The context manager returns the starting working directory *if* it made a | |
46 | change and None otherwise, so that users can apply the necessary adjustment |
|
46 | change and None otherwise, so that users can apply the necessary adjustment | |
47 | to their system calls in the event of a change. |
|
47 | to their system calls in the event of a change. | |
48 |
|
48 | |||
49 | Example |
|
49 | Example | |
50 | ------- |
|
50 | ------- | |
51 | :: |
|
51 | :: | |
52 | cmd = 'dir' |
|
52 | cmd = 'dir' | |
53 | with AvoidUNCPath() as path: |
|
53 | with AvoidUNCPath() as path: | |
54 | if path is not None: |
|
54 | if path is not None: | |
55 | cmd = '"pushd %s &&"%s' % (path, cmd) |
|
55 | cmd = '"pushd %s &&"%s' % (path, cmd) | |
56 | os.system(cmd) |
|
56 | os.system(cmd) | |
57 | """ |
|
57 | """ | |
58 | def __enter__(self): |
|
58 | def __enter__(self): | |
59 | self.path = os.getcwdu() |
|
59 | self.path = os.getcwdu() | |
60 | self.is_unc_path = self.path.startswith(r"\\") |
|
60 | self.is_unc_path = self.path.startswith(r"\\") | |
61 | if self.is_unc_path: |
|
61 | if self.is_unc_path: | |
62 | # change to c drive (as cmd.exe cannot handle UNC addresses) |
|
62 | # change to c drive (as cmd.exe cannot handle UNC addresses) | |
63 | os.chdir("C:") |
|
63 | os.chdir("C:") | |
64 | return self.path |
|
64 | return self.path | |
65 | else: |
|
65 | else: | |
66 | # We return None to signal that there was no change in the working |
|
66 | # We return None to signal that there was no change in the working | |
67 | # directory |
|
67 | # directory | |
68 | return None |
|
68 | return None | |
69 |
|
69 | |||
70 | def __exit__(self, exc_type, exc_value, traceback): |
|
70 | def __exit__(self, exc_type, exc_value, traceback): | |
71 | if self.is_unc_path: |
|
71 | if self.is_unc_path: | |
72 | os.chdir(self.path) |
|
72 | os.chdir(self.path) | |
73 |
|
73 | |||
74 |
|
74 | |||
75 | def _find_cmd(cmd): |
|
75 | def _find_cmd(cmd): | |
76 | """Find the full path to a .bat or .exe using the win32api module.""" |
|
76 | """Find the full path to a .bat or .exe using the win32api module.""" | |
77 | try: |
|
77 | try: | |
78 | from win32api import SearchPath |
|
78 | from win32api import SearchPath | |
79 | except ImportError: |
|
79 | except ImportError: | |
80 | raise ImportError('you need to have pywin32 installed for this to work') |
|
80 | raise ImportError('you need to have pywin32 installed for this to work') | |
81 | else: |
|
81 | else: | |
82 | PATH = os.environ['PATH'] |
|
82 | PATH = os.environ['PATH'] | |
83 | extensions = ['.exe', '.com', '.bat', '.py'] |
|
83 | extensions = ['.exe', '.com', '.bat', '.py'] | |
84 | path = None |
|
84 | path = None | |
85 | for ext in extensions: |
|
85 | for ext in extensions: | |
86 | try: |
|
86 | try: | |
87 | path = SearchPath(PATH, cmd + ext)[0] |
|
87 | path = SearchPath(PATH, cmd + ext)[0] | |
88 | except: |
|
88 | except: | |
89 | pass |
|
89 | pass | |
90 | if path is None: |
|
90 | if path is None: | |
91 | raise OSError("command %r not found" % cmd) |
|
91 | raise OSError("command %r not found" % cmd) | |
92 | else: |
|
92 | else: | |
93 | return path |
|
93 | return path | |
94 |
|
94 | |||
95 |
|
95 | |||
96 | def _system_body(p): |
|
96 | def _system_body(p): | |
97 | """Callback for _system.""" |
|
97 | """Callback for _system.""" | |
98 | enc = getdefaultencoding() |
|
98 | enc = DEFAULT_ENCODING | |
99 | for line in read_no_interrupt(p.stdout).splitlines(): |
|
99 | for line in read_no_interrupt(p.stdout).splitlines(): | |
100 | line = line.decode(enc, 'replace') |
|
100 | line = line.decode(enc, 'replace') | |
101 | print(line, file=sys.stdout) |
|
101 | print(line, file=sys.stdout) | |
102 | for line in read_no_interrupt(p.stderr).splitlines(): |
|
102 | for line in read_no_interrupt(p.stderr).splitlines(): | |
103 | line = line.decode(enc, 'replace') |
|
103 | line = line.decode(enc, 'replace') | |
104 | print(line, file=sys.stderr) |
|
104 | print(line, file=sys.stderr) | |
105 |
|
105 | |||
106 | # Wait to finish for returncode |
|
106 | # Wait to finish for returncode | |
107 | return p.wait() |
|
107 | return p.wait() | |
108 |
|
108 | |||
109 |
|
109 | |||
110 | def system(cmd): |
|
110 | def system(cmd): | |
111 | """Win32 version of os.system() that works with network shares. |
|
111 | """Win32 version of os.system() that works with network shares. | |
112 |
|
112 | |||
113 | Note that this implementation returns None, as meant for use in IPython. |
|
113 | Note that this implementation returns None, as meant for use in IPython. | |
114 |
|
114 | |||
115 | Parameters |
|
115 | Parameters | |
116 | ---------- |
|
116 | ---------- | |
117 | cmd : str |
|
117 | cmd : str | |
118 | A command to be executed in the system shell. |
|
118 | A command to be executed in the system shell. | |
119 |
|
119 | |||
120 | Returns |
|
120 | Returns | |
121 | ------- |
|
121 | ------- | |
122 | None : we explicitly do NOT return the subprocess status code, as this |
|
122 | None : we explicitly do NOT return the subprocess status code, as this | |
123 | utility is meant to be used extensively in IPython, where any return value |
|
123 | utility is meant to be used extensively in IPython, where any return value | |
124 | would trigger :func:`sys.displayhook` calls. |
|
124 | would trigger :func:`sys.displayhook` calls. | |
125 | """ |
|
125 | """ | |
126 | # The controller provides interactivity with both |
|
126 | # The controller provides interactivity with both | |
127 | # stdin and stdout |
|
127 | # stdin and stdout | |
128 | import _process_win32_controller |
|
128 | import _process_win32_controller | |
129 | _process_win32_controller.system(cmd) |
|
129 | _process_win32_controller.system(cmd) | |
130 |
|
130 | |||
131 |
|
131 | |||
132 | def getoutput(cmd): |
|
132 | def getoutput(cmd): | |
133 | """Return standard output of executing cmd in a shell. |
|
133 | """Return standard output of executing cmd in a shell. | |
134 |
|
134 | |||
135 | Accepts the same arguments as os.system(). |
|
135 | Accepts the same arguments as os.system(). | |
136 |
|
136 | |||
137 | Parameters |
|
137 | Parameters | |
138 | ---------- |
|
138 | ---------- | |
139 | cmd : str |
|
139 | cmd : str | |
140 | A command to be executed in the system shell. |
|
140 | A command to be executed in the system shell. | |
141 |
|
141 | |||
142 | Returns |
|
142 | Returns | |
143 | ------- |
|
143 | ------- | |
144 | stdout : str |
|
144 | stdout : str | |
145 | """ |
|
145 | """ | |
146 |
|
146 | |||
147 | with AvoidUNCPath() as path: |
|
147 | with AvoidUNCPath() as path: | |
148 | if path is not None: |
|
148 | if path is not None: | |
149 | cmd = '"pushd %s &&"%s' % (path, cmd) |
|
149 | cmd = '"pushd %s &&"%s' % (path, cmd) | |
150 | out = process_handler(cmd, lambda p: p.communicate()[0], STDOUT) |
|
150 | out = process_handler(cmd, lambda p: p.communicate()[0], STDOUT) | |
151 |
|
151 | |||
152 | if out is None: |
|
152 | if out is None: | |
153 | out = '' |
|
153 | out = '' | |
154 | return out |
|
154 | return out | |
155 |
|
155 | |||
156 | try: |
|
156 | try: | |
157 | CommandLineToArgvW = ctypes.windll.shell32.CommandLineToArgvW |
|
157 | CommandLineToArgvW = ctypes.windll.shell32.CommandLineToArgvW | |
158 | CommandLineToArgvW.arg_types = [LPCWSTR, POINTER(c_int)] |
|
158 | CommandLineToArgvW.arg_types = [LPCWSTR, POINTER(c_int)] | |
159 | CommandLineToArgvW.res_types = [POINTER(LPCWSTR)] |
|
159 | CommandLineToArgvW.res_types = [POINTER(LPCWSTR)] | |
160 | LocalFree = ctypes.windll.kernel32.LocalFree |
|
160 | LocalFree = ctypes.windll.kernel32.LocalFree | |
161 | LocalFree.res_type = HLOCAL |
|
161 | LocalFree.res_type = HLOCAL | |
162 | LocalFree.arg_types = [HLOCAL] |
|
162 | LocalFree.arg_types = [HLOCAL] | |
163 |
|
163 | |||
164 | def arg_split(commandline, posix=False, strict=True): |
|
164 | def arg_split(commandline, posix=False, strict=True): | |
165 | """Split a command line's arguments in a shell-like manner. |
|
165 | """Split a command line's arguments in a shell-like manner. | |
166 |
|
166 | |||
167 | This is a special version for windows that use a ctypes call to CommandLineToArgvW |
|
167 | This is a special version for windows that use a ctypes call to CommandLineToArgvW | |
168 | to do the argv splitting. The posix paramter is ignored. |
|
168 | to do the argv splitting. The posix paramter is ignored. | |
169 |
|
169 | |||
170 | If strict=False, process_common.arg_split(...strict=False) is used instead. |
|
170 | If strict=False, process_common.arg_split(...strict=False) is used instead. | |
171 | """ |
|
171 | """ | |
172 | #CommandLineToArgvW returns path to executable if called with empty string. |
|
172 | #CommandLineToArgvW returns path to executable if called with empty string. | |
173 | if commandline.strip() == "": |
|
173 | if commandline.strip() == "": | |
174 | return [] |
|
174 | return [] | |
175 | if not strict: |
|
175 | if not strict: | |
176 | # not really a cl-arg, fallback on _process_common |
|
176 | # not really a cl-arg, fallback on _process_common | |
177 | return py_arg_split(commandline, posix=posix, strict=strict) |
|
177 | return py_arg_split(commandline, posix=posix, strict=strict) | |
178 | argvn = c_int() |
|
178 | argvn = c_int() | |
179 | result_pointer = CommandLineToArgvW(py3compat.cast_unicode(commandline.lstrip()), ctypes.byref(argvn)) |
|
179 | result_pointer = CommandLineToArgvW(py3compat.cast_unicode(commandline.lstrip()), ctypes.byref(argvn)) | |
180 | result_array_type = LPCWSTR * argvn.value |
|
180 | result_array_type = LPCWSTR * argvn.value | |
181 | result = [arg for arg in result_array_type.from_address(result_pointer)] |
|
181 | result = [arg for arg in result_array_type.from_address(result_pointer)] | |
182 | retval = LocalFree(result_pointer) |
|
182 | retval = LocalFree(result_pointer) | |
183 | return result |
|
183 | return result | |
184 | except AttributeError: |
|
184 | except AttributeError: | |
185 | arg_split = py_arg_split |
|
185 | arg_split = py_arg_split |
@@ -1,54 +1,56 b'' | |||||
1 | # coding: utf-8 |
|
1 | # coding: utf-8 | |
2 | """ |
|
2 | """ | |
3 | Utilities for dealing with text encodings |
|
3 | Utilities for dealing with text encodings | |
4 | """ |
|
4 | """ | |
5 |
|
5 | |||
6 | #----------------------------------------------------------------------------- |
|
6 | #----------------------------------------------------------------------------- | |
7 | # Copyright (C) 2008-2012 The IPython Development Team |
|
7 | # Copyright (C) 2008-2012 The IPython Development Team | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
10 | # the file COPYING, distributed as part of this software. |
|
10 | # the file COPYING, distributed as part of this software. | |
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 |
|
12 | |||
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 | import sys |
|
16 | import sys | |
17 | import locale |
|
17 | import locale | |
18 |
|
18 | |||
19 | # to deal with the possibility of sys.std* not being a stream at all |
|
19 | # to deal with the possibility of sys.std* not being a stream at all | |
20 | def get_stream_enc(stream, default=None): |
|
20 | def get_stream_enc(stream, default=None): | |
21 | """Return the given stream's encoding or a default. |
|
21 | """Return the given stream's encoding or a default. | |
22 |
|
22 | |||
23 | There are cases where sys.std* might not actually be a stream, so |
|
23 | There are cases where sys.std* might not actually be a stream, so | |
24 | check for the encoding attribute prior to returning it, and return |
|
24 | check for the encoding attribute prior to returning it, and return | |
25 | a default if it doesn't exist or evaluates as False. `default' |
|
25 | a default if it doesn't exist or evaluates as False. `default' | |
26 | is None if not provided. |
|
26 | is None if not provided. | |
27 | """ |
|
27 | """ | |
28 | if not hasattr(stream, 'encoding') or not stream.encoding: |
|
28 | if not hasattr(stream, 'encoding') or not stream.encoding: | |
29 | return default |
|
29 | return default | |
30 | else: |
|
30 | else: | |
31 | return stream.encoding |
|
31 | return stream.encoding | |
32 |
|
32 | |||
33 | # Less conservative replacement for sys.getdefaultencoding, that will try |
|
33 | # Less conservative replacement for sys.getdefaultencoding, that will try | |
34 | # to match the environment. |
|
34 | # to match the environment. | |
35 | # Defined here as central function, so if we find better choices, we |
|
35 | # Defined here as central function, so if we find better choices, we | |
36 | # won't need to make changes all over IPython. |
|
36 | # won't need to make changes all over IPython. | |
37 | def getdefaultencoding(): |
|
37 | def getdefaultencoding(): | |
38 | """Return IPython's guess for the default encoding for bytes as text. |
|
38 | """Return IPython's guess for the default encoding for bytes as text. | |
39 |
|
39 | |||
40 | Asks for stdin.encoding first, to match the calling Terminal, but that |
|
40 | Asks for stdin.encoding first, to match the calling Terminal, but that | |
41 | is often None for subprocesses. Fall back on locale.getpreferredencoding() |
|
41 | is often None for subprocesses. Fall back on locale.getpreferredencoding() | |
42 | which should be a sensible platform default (that respects LANG environment), |
|
42 | which should be a sensible platform default (that respects LANG environment), | |
43 | and finally to sys.getdefaultencoding() which is the most conservative option, |
|
43 | and finally to sys.getdefaultencoding() which is the most conservative option, | |
44 | and usually ASCII. |
|
44 | and usually ASCII. | |
45 | """ |
|
45 | """ | |
46 | enc = get_stream_enc(sys.stdin) |
|
46 | enc = get_stream_enc(sys.stdin) | |
47 | if not enc or enc=='ascii': |
|
47 | if not enc or enc=='ascii': | |
48 | try: |
|
48 | try: | |
49 | # There are reports of getpreferredencoding raising errors |
|
49 | # There are reports of getpreferredencoding raising errors | |
50 | # in some cases, which may well be fixed, but let's be conservative here. |
|
50 | # in some cases, which may well be fixed, but let's be conservative here. | |
51 | enc = locale.getpreferredencoding() |
|
51 | enc = locale.getpreferredencoding() | |
52 | except Exception: |
|
52 | except Exception: | |
53 | pass |
|
53 | pass | |
54 | return enc or sys.getdefaultencoding() |
|
54 | return enc or sys.getdefaultencoding() | |
|
55 | ||||
|
56 | DEFAULT_ENCODING = getdefaultencoding() |
@@ -1,166 +1,166 b'' | |||||
1 | """Utilities to manipulate JSON objects. |
|
1 | """Utilities to manipulate JSON objects. | |
2 | """ |
|
2 | """ | |
3 | #----------------------------------------------------------------------------- |
|
3 | #----------------------------------------------------------------------------- | |
4 | # Copyright (C) 2010-2011 The IPython Development Team |
|
4 | # Copyright (C) 2010-2011 The IPython Development Team | |
5 | # |
|
5 | # | |
6 | # Distributed under the terms of the BSD License. The full license is in |
|
6 | # Distributed under the terms of the BSD License. The full license is in | |
7 | # the file COPYING.txt, distributed as part of this software. |
|
7 | # the file COPYING.txt, distributed as part of this software. | |
8 | #----------------------------------------------------------------------------- |
|
8 | #----------------------------------------------------------------------------- | |
9 |
|
9 | |||
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 | # Imports |
|
11 | # Imports | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 | # stdlib |
|
13 | # stdlib | |
14 | import re |
|
14 | import re | |
15 | import sys |
|
15 | import sys | |
16 | import types |
|
16 | import types | |
17 | from datetime import datetime |
|
17 | from datetime import datetime | |
18 |
|
18 | |||
19 | from IPython.utils import py3compat |
|
19 | from IPython.utils import py3compat | |
20 |
from IPython.utils.encoding import |
|
20 | from IPython.utils.encoding import DEFAULT_ENCODING | |
21 | from IPython.utils import text |
|
21 | from IPython.utils import text | |
22 | next_attr_name = '__next__' if py3compat.PY3 else 'next' |
|
22 | next_attr_name = '__next__' if py3compat.PY3 else 'next' | |
23 |
|
23 | |||
24 | #----------------------------------------------------------------------------- |
|
24 | #----------------------------------------------------------------------------- | |
25 | # Globals and constants |
|
25 | # Globals and constants | |
26 | #----------------------------------------------------------------------------- |
|
26 | #----------------------------------------------------------------------------- | |
27 |
|
27 | |||
28 | # timestamp formats |
|
28 | # timestamp formats | |
29 | ISO8601="%Y-%m-%dT%H:%M:%S.%f" |
|
29 | ISO8601="%Y-%m-%dT%H:%M:%S.%f" | |
30 | ISO8601_PAT=re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+$") |
|
30 | ISO8601_PAT=re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+$") | |
31 |
|
31 | |||
32 | #----------------------------------------------------------------------------- |
|
32 | #----------------------------------------------------------------------------- | |
33 | # Classes and functions |
|
33 | # Classes and functions | |
34 | #----------------------------------------------------------------------------- |
|
34 | #----------------------------------------------------------------------------- | |
35 |
|
35 | |||
36 | def rekey(dikt): |
|
36 | def rekey(dikt): | |
37 | """Rekey a dict that has been forced to use str keys where there should be |
|
37 | """Rekey a dict that has been forced to use str keys where there should be | |
38 | ints by json.""" |
|
38 | ints by json.""" | |
39 | for k in dikt.iterkeys(): |
|
39 | for k in dikt.iterkeys(): | |
40 | if isinstance(k, basestring): |
|
40 | if isinstance(k, basestring): | |
41 | ik=fk=None |
|
41 | ik=fk=None | |
42 | try: |
|
42 | try: | |
43 | ik = int(k) |
|
43 | ik = int(k) | |
44 | except ValueError: |
|
44 | except ValueError: | |
45 | try: |
|
45 | try: | |
46 | fk = float(k) |
|
46 | fk = float(k) | |
47 | except ValueError: |
|
47 | except ValueError: | |
48 | continue |
|
48 | continue | |
49 | if ik is not None: |
|
49 | if ik is not None: | |
50 | nk = ik |
|
50 | nk = ik | |
51 | else: |
|
51 | else: | |
52 | nk = fk |
|
52 | nk = fk | |
53 | if nk in dikt: |
|
53 | if nk in dikt: | |
54 | raise KeyError("already have key %r"%nk) |
|
54 | raise KeyError("already have key %r"%nk) | |
55 | dikt[nk] = dikt.pop(k) |
|
55 | dikt[nk] = dikt.pop(k) | |
56 | return dikt |
|
56 | return dikt | |
57 |
|
57 | |||
58 |
|
58 | |||
59 | def extract_dates(obj): |
|
59 | def extract_dates(obj): | |
60 | """extract ISO8601 dates from unpacked JSON""" |
|
60 | """extract ISO8601 dates from unpacked JSON""" | |
61 | if isinstance(obj, dict): |
|
61 | if isinstance(obj, dict): | |
62 | obj = dict(obj) # don't clobber |
|
62 | obj = dict(obj) # don't clobber | |
63 | for k,v in obj.iteritems(): |
|
63 | for k,v in obj.iteritems(): | |
64 | obj[k] = extract_dates(v) |
|
64 | obj[k] = extract_dates(v) | |
65 | elif isinstance(obj, (list, tuple)): |
|
65 | elif isinstance(obj, (list, tuple)): | |
66 | obj = [ extract_dates(o) for o in obj ] |
|
66 | obj = [ extract_dates(o) for o in obj ] | |
67 | elif isinstance(obj, basestring): |
|
67 | elif isinstance(obj, basestring): | |
68 | if ISO8601_PAT.match(obj): |
|
68 | if ISO8601_PAT.match(obj): | |
69 | obj = datetime.strptime(obj, ISO8601) |
|
69 | obj = datetime.strptime(obj, ISO8601) | |
70 | return obj |
|
70 | return obj | |
71 |
|
71 | |||
72 | def squash_dates(obj): |
|
72 | def squash_dates(obj): | |
73 | """squash datetime objects into ISO8601 strings""" |
|
73 | """squash datetime objects into ISO8601 strings""" | |
74 | if isinstance(obj, dict): |
|
74 | if isinstance(obj, dict): | |
75 | obj = dict(obj) # don't clobber |
|
75 | obj = dict(obj) # don't clobber | |
76 | for k,v in obj.iteritems(): |
|
76 | for k,v in obj.iteritems(): | |
77 | obj[k] = squash_dates(v) |
|
77 | obj[k] = squash_dates(v) | |
78 | elif isinstance(obj, (list, tuple)): |
|
78 | elif isinstance(obj, (list, tuple)): | |
79 | obj = [ squash_dates(o) for o in obj ] |
|
79 | obj = [ squash_dates(o) for o in obj ] | |
80 | elif isinstance(obj, datetime): |
|
80 | elif isinstance(obj, datetime): | |
81 | obj = obj.strftime(ISO8601) |
|
81 | obj = obj.strftime(ISO8601) | |
82 | return obj |
|
82 | return obj | |
83 |
|
83 | |||
84 | def date_default(obj): |
|
84 | def date_default(obj): | |
85 | """default function for packing datetime objects in JSON.""" |
|
85 | """default function for packing datetime objects in JSON.""" | |
86 | if isinstance(obj, datetime): |
|
86 | if isinstance(obj, datetime): | |
87 | return obj.strftime(ISO8601) |
|
87 | return obj.strftime(ISO8601) | |
88 | else: |
|
88 | else: | |
89 | raise TypeError("%r is not JSON serializable"%obj) |
|
89 | raise TypeError("%r is not JSON serializable"%obj) | |
90 |
|
90 | |||
91 |
|
91 | |||
92 |
|
92 | |||
93 | def json_clean(obj): |
|
93 | def json_clean(obj): | |
94 | """Clean an object to ensure it's safe to encode in JSON. |
|
94 | """Clean an object to ensure it's safe to encode in JSON. | |
95 |
|
95 | |||
96 | Atomic, immutable objects are returned unmodified. Sets and tuples are |
|
96 | Atomic, immutable objects are returned unmodified. Sets and tuples are | |
97 | converted to lists, lists are copied and dicts are also copied. |
|
97 | converted to lists, lists are copied and dicts are also copied. | |
98 |
|
98 | |||
99 | Note: dicts whose keys could cause collisions upon encoding (such as a dict |
|
99 | Note: dicts whose keys could cause collisions upon encoding (such as a dict | |
100 | with both the number 1 and the string '1' as keys) will cause a ValueError |
|
100 | with both the number 1 and the string '1' as keys) will cause a ValueError | |
101 | to be raised. |
|
101 | to be raised. | |
102 |
|
102 | |||
103 | Parameters |
|
103 | Parameters | |
104 | ---------- |
|
104 | ---------- | |
105 | obj : any python object |
|
105 | obj : any python object | |
106 |
|
106 | |||
107 | Returns |
|
107 | Returns | |
108 | ------- |
|
108 | ------- | |
109 | out : object |
|
109 | out : object | |
110 |
|
110 | |||
111 | A version of the input which will not cause an encoding error when |
|
111 | A version of the input which will not cause an encoding error when | |
112 | encoded as JSON. Note that this function does not *encode* its inputs, |
|
112 | encoded as JSON. Note that this function does not *encode* its inputs, | |
113 | it simply sanitizes it so that there will be no encoding errors later. |
|
113 | it simply sanitizes it so that there will be no encoding errors later. | |
114 |
|
114 | |||
115 | Examples |
|
115 | Examples | |
116 | -------- |
|
116 | -------- | |
117 | >>> json_clean(4) |
|
117 | >>> json_clean(4) | |
118 | 4 |
|
118 | 4 | |
119 | >>> json_clean(range(10)) |
|
119 | >>> json_clean(range(10)) | |
120 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
|
120 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] | |
121 | >>> json_clean(dict(x=1, y=2)) |
|
121 | >>> json_clean(dict(x=1, y=2)) | |
122 | {'y': 2, 'x': 1} |
|
122 | {'y': 2, 'x': 1} | |
123 | >>> json_clean(dict(x=1, y=2, z=[1,2,3])) |
|
123 | >>> json_clean(dict(x=1, y=2, z=[1,2,3])) | |
124 | {'y': 2, 'x': 1, 'z': [1, 2, 3]} |
|
124 | {'y': 2, 'x': 1, 'z': [1, 2, 3]} | |
125 | >>> json_clean(True) |
|
125 | >>> json_clean(True) | |
126 | True |
|
126 | True | |
127 | """ |
|
127 | """ | |
128 | # types that are 'atomic' and ok in json as-is. bool doesn't need to be |
|
128 | # types that are 'atomic' and ok in json as-is. bool doesn't need to be | |
129 | # listed explicitly because bools pass as int instances |
|
129 | # listed explicitly because bools pass as int instances | |
130 | atomic_ok = (unicode, int, float, types.NoneType) |
|
130 | atomic_ok = (unicode, int, float, types.NoneType) | |
131 |
|
131 | |||
132 | # containers that we need to convert into lists |
|
132 | # containers that we need to convert into lists | |
133 | container_to_list = (tuple, set, types.GeneratorType) |
|
133 | container_to_list = (tuple, set, types.GeneratorType) | |
134 |
|
134 | |||
135 | if isinstance(obj, atomic_ok): |
|
135 | if isinstance(obj, atomic_ok): | |
136 | return obj |
|
136 | return obj | |
137 |
|
137 | |||
138 | if isinstance(obj, bytes): |
|
138 | if isinstance(obj, bytes): | |
139 |
return obj.decode( |
|
139 | return obj.decode(DEFAULT_ENCODING, 'replace') | |
140 |
|
140 | |||
141 | if isinstance(obj, container_to_list) or ( |
|
141 | if isinstance(obj, container_to_list) or ( | |
142 | hasattr(obj, '__iter__') and hasattr(obj, next_attr_name)): |
|
142 | hasattr(obj, '__iter__') and hasattr(obj, next_attr_name)): | |
143 | obj = list(obj) |
|
143 | obj = list(obj) | |
144 |
|
144 | |||
145 | if isinstance(obj, list): |
|
145 | if isinstance(obj, list): | |
146 | return [json_clean(x) for x in obj] |
|
146 | return [json_clean(x) for x in obj] | |
147 |
|
147 | |||
148 | if isinstance(obj, dict): |
|
148 | if isinstance(obj, dict): | |
149 | # First, validate that the dict won't lose data in conversion due to |
|
149 | # First, validate that the dict won't lose data in conversion due to | |
150 | # key collisions after stringification. This can happen with keys like |
|
150 | # key collisions after stringification. This can happen with keys like | |
151 | # True and 'true' or 1 and '1', which collide in JSON. |
|
151 | # True and 'true' or 1 and '1', which collide in JSON. | |
152 | nkeys = len(obj) |
|
152 | nkeys = len(obj) | |
153 | nkeys_collapsed = len(set(map(str, obj))) |
|
153 | nkeys_collapsed = len(set(map(str, obj))) | |
154 | if nkeys != nkeys_collapsed: |
|
154 | if nkeys != nkeys_collapsed: | |
155 | raise ValueError('dict can not be safely converted to JSON: ' |
|
155 | raise ValueError('dict can not be safely converted to JSON: ' | |
156 | 'key collision would lead to dropped values') |
|
156 | 'key collision would lead to dropped values') | |
157 | # If all OK, proceed by making the new dict that will be json-safe |
|
157 | # If all OK, proceed by making the new dict that will be json-safe | |
158 | out = {} |
|
158 | out = {} | |
159 | for k,v in obj.iteritems(): |
|
159 | for k,v in obj.iteritems(): | |
160 | out[str(k)] = json_clean(v) |
|
160 | out[str(k)] = json_clean(v) | |
161 | return out |
|
161 | return out | |
162 |
|
162 | |||
163 | # If we get here, we don't know how to handle the object, so we just get |
|
163 | # If we get here, we don't know how to handle the object, so we just get | |
164 | # its repr and return that. This will catch lambdas, open sockets, class |
|
164 | # its repr and return that. This will catch lambdas, open sockets, class | |
165 | # objects, and any other complicated contraption that json can't encode |
|
165 | # objects, and any other complicated contraption that json can't encode | |
166 | return repr(obj) |
|
166 | return repr(obj) |
@@ -1,180 +1,178 b'' | |||||
1 | # coding: utf-8 |
|
1 | # coding: utf-8 | |
2 | """Compatibility tricks for Python 3. Mainly to do with unicode.""" |
|
2 | """Compatibility tricks for Python 3. Mainly to do with unicode.""" | |
3 | import __builtin__ |
|
3 | import __builtin__ | |
4 | import functools |
|
4 | import functools | |
5 | import sys |
|
5 | import sys | |
6 | import re |
|
6 | import re | |
7 | import types |
|
7 | import types | |
8 |
|
8 | |||
9 | from .encoding import getdefaultencoding |
|
9 | from .encoding import DEFAULT_ENCODING | |
10 |
|
||||
11 | default_encoding = getdefaultencoding() |
|
|||
12 |
|
10 | |||
13 | orig_open = open |
|
11 | orig_open = open | |
14 |
|
12 | |||
15 | def no_code(x, encoding=None): |
|
13 | def no_code(x, encoding=None): | |
16 | return x |
|
14 | return x | |
17 |
|
15 | |||
18 | def decode(s, encoding=None): |
|
16 | def decode(s, encoding=None): | |
19 |
encoding = encoding or |
|
17 | encoding = encoding or DEFAULT_ENCODING | |
20 | return s.decode(encoding, "replace") |
|
18 | return s.decode(encoding, "replace") | |
21 |
|
19 | |||
22 | def encode(u, encoding=None): |
|
20 | def encode(u, encoding=None): | |
23 |
encoding = encoding or |
|
21 | encoding = encoding or DEFAULT_ENCODING | |
24 | return u.encode(encoding, "replace") |
|
22 | return u.encode(encoding, "replace") | |
25 |
|
23 | |||
26 |
|
24 | |||
27 | def cast_unicode(s, encoding=None): |
|
25 | def cast_unicode(s, encoding=None): | |
28 | if isinstance(s, bytes): |
|
26 | if isinstance(s, bytes): | |
29 | return decode(s, encoding) |
|
27 | return decode(s, encoding) | |
30 | return s |
|
28 | return s | |
31 |
|
29 | |||
32 | def cast_bytes(s, encoding=None): |
|
30 | def cast_bytes(s, encoding=None): | |
33 | if not isinstance(s, bytes): |
|
31 | if not isinstance(s, bytes): | |
34 | return encode(s, encoding) |
|
32 | return encode(s, encoding) | |
35 | return s |
|
33 | return s | |
36 |
|
34 | |||
37 | def _modify_str_or_docstring(str_change_func): |
|
35 | def _modify_str_or_docstring(str_change_func): | |
38 | @functools.wraps(str_change_func) |
|
36 | @functools.wraps(str_change_func) | |
39 | def wrapper(func_or_str): |
|
37 | def wrapper(func_or_str): | |
40 | if isinstance(func_or_str, basestring): |
|
38 | if isinstance(func_or_str, basestring): | |
41 | func = None |
|
39 | func = None | |
42 | doc = func_or_str |
|
40 | doc = func_or_str | |
43 | else: |
|
41 | else: | |
44 | func = func_or_str |
|
42 | func = func_or_str | |
45 | doc = func.__doc__ |
|
43 | doc = func.__doc__ | |
46 |
|
44 | |||
47 | doc = str_change_func(doc) |
|
45 | doc = str_change_func(doc) | |
48 |
|
46 | |||
49 | if func: |
|
47 | if func: | |
50 | func.__doc__ = doc |
|
48 | func.__doc__ = doc | |
51 | return func |
|
49 | return func | |
52 | return doc |
|
50 | return doc | |
53 | return wrapper |
|
51 | return wrapper | |
54 |
|
52 | |||
55 | if sys.version_info[0] >= 3: |
|
53 | if sys.version_info[0] >= 3: | |
56 | PY3 = True |
|
54 | PY3 = True | |
57 |
|
55 | |||
58 | input = input |
|
56 | input = input | |
59 | builtin_mod_name = "builtins" |
|
57 | builtin_mod_name = "builtins" | |
60 |
|
58 | |||
61 | str_to_unicode = no_code |
|
59 | str_to_unicode = no_code | |
62 | unicode_to_str = no_code |
|
60 | unicode_to_str = no_code | |
63 | str_to_bytes = encode |
|
61 | str_to_bytes = encode | |
64 | bytes_to_str = decode |
|
62 | bytes_to_str = decode | |
65 | cast_bytes_py2 = no_code |
|
63 | cast_bytes_py2 = no_code | |
66 |
|
64 | |||
67 | def isidentifier(s, dotted=False): |
|
65 | def isidentifier(s, dotted=False): | |
68 | if dotted: |
|
66 | if dotted: | |
69 | return all(isidentifier(a) for a in s.split(".")) |
|
67 | return all(isidentifier(a) for a in s.split(".")) | |
70 | return s.isidentifier() |
|
68 | return s.isidentifier() | |
71 |
|
69 | |||
72 | open = orig_open |
|
70 | open = orig_open | |
73 |
|
71 | |||
74 | MethodType = types.MethodType |
|
72 | MethodType = types.MethodType | |
75 |
|
73 | |||
76 | def execfile(fname, glob, loc=None): |
|
74 | def execfile(fname, glob, loc=None): | |
77 | loc = loc if (loc is not None) else glob |
|
75 | loc = loc if (loc is not None) else glob | |
78 | exec compile(open(fname, 'rb').read(), fname, 'exec') in glob, loc |
|
76 | exec compile(open(fname, 'rb').read(), fname, 'exec') in glob, loc | |
79 |
|
77 | |||
80 | # Refactor print statements in doctests. |
|
78 | # Refactor print statements in doctests. | |
81 | _print_statement_re = re.compile(r"\bprint (?P<expr>.*)$", re.MULTILINE) |
|
79 | _print_statement_re = re.compile(r"\bprint (?P<expr>.*)$", re.MULTILINE) | |
82 | def _print_statement_sub(match): |
|
80 | def _print_statement_sub(match): | |
83 | expr = match.groups('expr') |
|
81 | expr = match.groups('expr') | |
84 | return "print(%s)" % expr |
|
82 | return "print(%s)" % expr | |
85 |
|
83 | |||
86 | @_modify_str_or_docstring |
|
84 | @_modify_str_or_docstring | |
87 | def doctest_refactor_print(doc): |
|
85 | def doctest_refactor_print(doc): | |
88 | """Refactor 'print x' statements in a doctest to print(x) style. 2to3 |
|
86 | """Refactor 'print x' statements in a doctest to print(x) style. 2to3 | |
89 | unfortunately doesn't pick up on our doctests. |
|
87 | unfortunately doesn't pick up on our doctests. | |
90 |
|
88 | |||
91 | Can accept a string or a function, so it can be used as a decorator.""" |
|
89 | Can accept a string or a function, so it can be used as a decorator.""" | |
92 | return _print_statement_re.sub(_print_statement_sub, doc) |
|
90 | return _print_statement_re.sub(_print_statement_sub, doc) | |
93 |
|
91 | |||
94 | # Abstract u'abc' syntax: |
|
92 | # Abstract u'abc' syntax: | |
95 | @_modify_str_or_docstring |
|
93 | @_modify_str_or_docstring | |
96 | def u_format(s): |
|
94 | def u_format(s): | |
97 | """"{u}'abc'" --> "'abc'" (Python 3) |
|
95 | """"{u}'abc'" --> "'abc'" (Python 3) | |
98 |
|
96 | |||
99 | Accepts a string or a function, so it can be used as a decorator.""" |
|
97 | Accepts a string or a function, so it can be used as a decorator.""" | |
100 | return s.format(u='') |
|
98 | return s.format(u='') | |
101 |
|
99 | |||
102 | else: |
|
100 | else: | |
103 | PY3 = False |
|
101 | PY3 = False | |
104 |
|
102 | |||
105 | input = raw_input |
|
103 | input = raw_input | |
106 | builtin_mod_name = "__builtin__" |
|
104 | builtin_mod_name = "__builtin__" | |
107 |
|
105 | |||
108 | str_to_unicode = decode |
|
106 | str_to_unicode = decode | |
109 | unicode_to_str = encode |
|
107 | unicode_to_str = encode | |
110 | str_to_bytes = no_code |
|
108 | str_to_bytes = no_code | |
111 | bytes_to_str = no_code |
|
109 | bytes_to_str = no_code | |
112 | cast_bytes_py2 = cast_bytes |
|
110 | cast_bytes_py2 = cast_bytes | |
113 |
|
111 | |||
114 | import re |
|
112 | import re | |
115 | _name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$") |
|
113 | _name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$") | |
116 | def isidentifier(s, dotted=False): |
|
114 | def isidentifier(s, dotted=False): | |
117 | if dotted: |
|
115 | if dotted: | |
118 | return all(isidentifier(a) for a in s.split(".")) |
|
116 | return all(isidentifier(a) for a in s.split(".")) | |
119 | return bool(_name_re.match(s)) |
|
117 | return bool(_name_re.match(s)) | |
120 |
|
118 | |||
121 | class open(object): |
|
119 | class open(object): | |
122 | """Wrapper providing key part of Python 3 open() interface.""" |
|
120 | """Wrapper providing key part of Python 3 open() interface.""" | |
123 | def __init__(self, fname, mode="r", encoding="utf-8"): |
|
121 | def __init__(self, fname, mode="r", encoding="utf-8"): | |
124 | self.f = orig_open(fname, mode) |
|
122 | self.f = orig_open(fname, mode) | |
125 | self.enc = encoding |
|
123 | self.enc = encoding | |
126 |
|
124 | |||
127 | def write(self, s): |
|
125 | def write(self, s): | |
128 | return self.f.write(s.encode(self.enc)) |
|
126 | return self.f.write(s.encode(self.enc)) | |
129 |
|
127 | |||
130 | def read(self, size=-1): |
|
128 | def read(self, size=-1): | |
131 | return self.f.read(size).decode(self.enc) |
|
129 | return self.f.read(size).decode(self.enc) | |
132 |
|
130 | |||
133 | def close(self): |
|
131 | def close(self): | |
134 | return self.f.close() |
|
132 | return self.f.close() | |
135 |
|
133 | |||
136 | def __enter__(self): |
|
134 | def __enter__(self): | |
137 | return self |
|
135 | return self | |
138 |
|
136 | |||
139 | def __exit__(self, etype, value, traceback): |
|
137 | def __exit__(self, etype, value, traceback): | |
140 | self.f.close() |
|
138 | self.f.close() | |
141 |
|
139 | |||
142 | def MethodType(func, instance): |
|
140 | def MethodType(func, instance): | |
143 | return types.MethodType(func, instance, type(instance)) |
|
141 | return types.MethodType(func, instance, type(instance)) | |
144 |
|
142 | |||
145 | # don't override system execfile on 2.x: |
|
143 | # don't override system execfile on 2.x: | |
146 | execfile = execfile |
|
144 | execfile = execfile | |
147 |
|
145 | |||
148 | def doctest_refactor_print(func_or_str): |
|
146 | def doctest_refactor_print(func_or_str): | |
149 | return func_or_str |
|
147 | return func_or_str | |
150 |
|
148 | |||
151 |
|
149 | |||
152 | # Abstract u'abc' syntax: |
|
150 | # Abstract u'abc' syntax: | |
153 | @_modify_str_or_docstring |
|
151 | @_modify_str_or_docstring | |
154 | def u_format(s): |
|
152 | def u_format(s): | |
155 | """"{u}'abc'" --> "u'abc'" (Python 2) |
|
153 | """"{u}'abc'" --> "u'abc'" (Python 2) | |
156 |
|
154 | |||
157 | Accepts a string or a function, so it can be used as a decorator.""" |
|
155 | Accepts a string or a function, so it can be used as a decorator.""" | |
158 | return s.format(u='u') |
|
156 | return s.format(u='u') | |
159 |
|
157 | |||
160 | if sys.platform == 'win32': |
|
158 | if sys.platform == 'win32': | |
161 | def execfile(fname, glob=None, loc=None): |
|
159 | def execfile(fname, glob=None, loc=None): | |
162 | loc = loc if (loc is not None) else glob |
|
160 | loc = loc if (loc is not None) else glob | |
163 | # The rstrip() is necessary b/c trailing whitespace in files will |
|
161 | # The rstrip() is necessary b/c trailing whitespace in files will | |
164 | # cause an IndentationError in Python 2.6 (this was fixed in 2.7, |
|
162 | # cause an IndentationError in Python 2.6 (this was fixed in 2.7, | |
165 | # but we still support 2.6). See issue 1027. |
|
163 | # but we still support 2.6). See issue 1027. | |
166 | scripttext = __builtin__.open(fname).read().rstrip() + '\n' |
|
164 | scripttext = __builtin__.open(fname).read().rstrip() + '\n' | |
167 | # compile converts unicode filename to str assuming |
|
165 | # compile converts unicode filename to str assuming | |
168 | # ascii. Let's do the conversion before calling compile |
|
166 | # ascii. Let's do the conversion before calling compile | |
169 | if isinstance(fname, unicode): |
|
167 | if isinstance(fname, unicode): | |
170 | filename = unicode_to_str(fname) |
|
168 | filename = unicode_to_str(fname) | |
171 | else: |
|
169 | else: | |
172 | filename = fname |
|
170 | filename = fname | |
173 | exec compile(scripttext, filename, 'exec') in glob, loc |
|
171 | exec compile(scripttext, filename, 'exec') in glob, loc | |
174 | else: |
|
172 | else: | |
175 | def execfile(fname, *where): |
|
173 | def execfile(fname, *where): | |
176 | if isinstance(fname, unicode): |
|
174 | if isinstance(fname, unicode): | |
177 | filename = fname.encode(sys.getfilesystemencoding()) |
|
175 | filename = fname.encode(sys.getfilesystemencoding()) | |
178 | else: |
|
176 | else: | |
179 | filename = fname |
|
177 | filename = fname | |
180 | __builtin__.execfile(filename, *where) |
|
178 | __builtin__.execfile(filename, *where) |
General Comments 0
You need to be logged in to leave comments.
Login now