Show More
@@ -1,453 +1,453 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """ |
|
2 | """ | |
3 | An application for IPython. |
|
3 | An application for IPython. | |
4 |
|
4 | |||
5 | All top-level applications should use the classes in this module for |
|
5 | All top-level applications should use the classes in this module for | |
6 | handling configuration and creating componenets. |
|
6 | handling configuration and creating componenets. | |
7 |
|
7 | |||
8 | The job of an :class:`Application` is to create the master configuration |
|
8 | The job of an :class:`Application` is to create the master configuration | |
9 | object and then create the configurable objects, passing the config to them. |
|
9 | object and then create the configurable objects, passing the config to them. | |
10 |
|
10 | |||
11 | Authors: |
|
11 | Authors: | |
12 |
|
12 | |||
13 | * Brian Granger |
|
13 | * Brian Granger | |
14 | * Fernando Perez |
|
14 | * Fernando Perez | |
15 |
|
15 | |||
16 | Notes |
|
16 | Notes | |
17 | ----- |
|
17 | ----- | |
18 | """ |
|
18 | """ | |
19 |
|
19 | |||
20 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
21 | # Copyright (C) 2008-2009 The IPython Development Team |
|
21 | # Copyright (C) 2008-2009 The IPython Development Team | |
22 | # |
|
22 | # | |
23 | # Distributed under the terms of the BSD License. The full license is in |
|
23 | # Distributed under the terms of the BSD License. The full license is in | |
24 | # the file COPYING, distributed as part of this software. |
|
24 | # the file COPYING, distributed as part of this software. | |
25 | #----------------------------------------------------------------------------- |
|
25 | #----------------------------------------------------------------------------- | |
26 |
|
26 | |||
27 | #----------------------------------------------------------------------------- |
|
27 | #----------------------------------------------------------------------------- | |
28 | # Imports |
|
28 | # Imports | |
29 | #----------------------------------------------------------------------------- |
|
29 | #----------------------------------------------------------------------------- | |
30 |
|
30 | |||
31 | import logging |
|
31 | import logging | |
32 | import os |
|
32 | import os | |
33 | import sys |
|
33 | import sys | |
34 |
|
34 | |||
35 | from IPython.core import release, crashhandler |
|
35 | from IPython.core import release, crashhandler | |
36 | from IPython.utils.path import get_ipython_dir, get_ipython_package_dir |
|
36 | from IPython.utils.path import get_ipython_dir, get_ipython_package_dir | |
37 | from IPython.config.loader import ( |
|
37 | from IPython.config.loader import ( | |
38 | PyFileConfigLoader, |
|
38 | PyFileConfigLoader, | |
39 | ArgParseConfigLoader, |
|
39 | ArgParseConfigLoader, | |
40 | Config, |
|
40 | Config, | |
41 | ) |
|
41 | ) | |
42 |
|
42 | |||
43 | #----------------------------------------------------------------------------- |
|
43 | #----------------------------------------------------------------------------- | |
44 | # Classes and functions |
|
44 | # Classes and functions | |
45 | #----------------------------------------------------------------------------- |
|
45 | #----------------------------------------------------------------------------- | |
46 |
|
46 | |||
47 | class ApplicationError(Exception): |
|
47 | class ApplicationError(Exception): | |
48 | pass |
|
48 | pass | |
49 |
|
49 | |||
50 |
|
50 | |||
51 | class BaseAppConfigLoader(ArgParseConfigLoader): |
|
51 | class BaseAppConfigLoader(ArgParseConfigLoader): | |
52 | """Default command line options for IPython based applications.""" |
|
52 | """Default command line options for IPython based applications.""" | |
53 |
|
53 | |||
54 | def _add_ipython_dir(self, parser): |
|
54 | def _add_ipython_dir(self, parser): | |
55 | """Add the --ipython-dir option to the parser.""" |
|
55 | """Add the --ipython-dir option to the parser.""" | |
56 | paa = parser.add_argument |
|
56 | paa = parser.add_argument | |
57 | paa('--ipython-dir', |
|
57 | paa('--ipython-dir', | |
58 | dest='Global.ipython_dir',type=unicode, |
|
58 | dest='Global.ipython_dir',type=unicode, | |
59 | help= |
|
59 | help= | |
60 | """Set to override default location of the IPython directory |
|
60 | """Set to override default location of the IPython directory | |
61 | IPYTHON_DIR, stored as Global.ipython_dir. This can also be |
|
61 | IPYTHON_DIR, stored as Global.ipython_dir. This can also be | |
62 | specified through the environment variable IPYTHON_DIR.""", |
|
62 | specified through the environment variable IPYTHON_DIR.""", | |
63 | metavar='Global.ipython_dir') |
|
63 | metavar='Global.ipython_dir') | |
64 |
|
64 | |||
65 | def _add_log_level(self, parser): |
|
65 | def _add_log_level(self, parser): | |
66 | """Add the --log-level option to the parser.""" |
|
66 | """Add the --log-level option to the parser.""" | |
67 | paa = parser.add_argument |
|
67 | paa = parser.add_argument | |
68 | paa('--log-level', |
|
68 | paa('--log-level', | |
69 | dest="Global.log_level",type=int, |
|
69 | dest="Global.log_level",type=int, | |
70 | help='Set the log level (0,10,20,30,40,50). Default is 30.', |
|
70 | help='Set the log level (0,10,20,30,40,50). Default is 30.', | |
71 | metavar='Global.log_level') |
|
71 | metavar='Global.log_level') | |
72 |
|
72 | |||
73 | def _add_arguments(self): |
|
73 | def _add_arguments(self): | |
74 | self._add_ipython_dir(self.parser) |
|
74 | self._add_ipython_dir(self.parser) | |
75 | self._add_log_level(self.parser) |
|
75 | self._add_log_level(self.parser) | |
76 |
|
76 | |||
77 |
|
77 | |||
78 | class Application(object): |
|
78 | class Application(object): | |
79 | """Load a config, construct configurables and set them running. |
|
79 | """Load a config, construct configurables and set them running. | |
80 |
|
80 | |||
81 | The configuration of an application can be done via three different Config |
|
81 | The configuration of an application can be done via three different Config | |
82 | objects, which are loaded and ultimately merged into a single one used |
|
82 | objects, which are loaded and ultimately merged into a single one used | |
83 | from that point on by the app. These are: |
|
83 | from that point on by the app. These are: | |
84 |
|
84 | |||
85 | 1. default_config: internal defaults, implemented in code. |
|
85 | 1. default_config: internal defaults, implemented in code. | |
86 | 2. file_config: read from the filesystem. |
|
86 | 2. file_config: read from the filesystem. | |
87 | 3. command_line_config: read from the system's command line flags. |
|
87 | 3. command_line_config: read from the system's command line flags. | |
88 |
|
88 | |||
89 | During initialization, 3 is actually read before 2, since at the |
|
89 | During initialization, 3 is actually read before 2, since at the | |
90 | command-line one may override the location of the file to be read. But the |
|
90 | command-line one may override the location of the file to be read. But the | |
91 | above is the order in which the merge is made. |
|
91 | above is the order in which the merge is made. | |
92 | """ |
|
92 | """ | |
93 |
|
93 | |||
94 | name = u'ipython' |
|
94 | name = u'ipython' | |
95 | description = 'IPython: an enhanced interactive Python shell.' |
|
95 | description = 'IPython: an enhanced interactive Python shell.' | |
96 | #: Usage message printed by argparse. If None, auto-generate |
|
96 | #: Usage message printed by argparse. If None, auto-generate | |
97 | usage = None |
|
97 | usage = None | |
98 | #: The command line config loader. Subclass of ArgParseConfigLoader. |
|
98 | #: The command line config loader. Subclass of ArgParseConfigLoader. | |
99 | command_line_loader = BaseAppConfigLoader |
|
99 | command_line_loader = BaseAppConfigLoader | |
100 | #: The name of the config file to load, determined at runtime |
|
100 | #: The name of the config file to load, determined at runtime | |
101 | config_file_name = None |
|
101 | config_file_name = None | |
102 | #: The name of the default config file. Track separately from the actual |
|
102 | #: The name of the default config file. Track separately from the actual | |
103 | #: name because some logic happens only if we aren't using the default. |
|
103 | #: name because some logic happens only if we aren't using the default. | |
104 | default_config_file_name = u'ipython_config.py' |
|
104 | default_config_file_name = u'ipython_config.py' | |
105 | default_log_level = logging.WARN |
|
105 | default_log_level = logging.WARN | |
106 | #: Set by --profile option |
|
106 | #: Set by --profile option | |
107 | profile_name = None |
|
107 | profile_name = None | |
108 | #: User's ipython directory, typically ~/.ipython/ |
|
108 | #: User's ipython directory, typically ~/.ipython or ~/.config/ipython/ | |
109 | ipython_dir = None |
|
109 | ipython_dir = None | |
110 | #: Internal defaults, implemented in code. |
|
110 | #: Internal defaults, implemented in code. | |
111 | default_config = None |
|
111 | default_config = None | |
112 | #: Read from the filesystem. |
|
112 | #: Read from the filesystem. | |
113 | file_config = None |
|
113 | file_config = None | |
114 | #: Read from the system's command line flags. |
|
114 | #: Read from the system's command line flags. | |
115 | command_line_config = None |
|
115 | command_line_config = None | |
116 | #: The final config that will be passed to the main object. |
|
116 | #: The final config that will be passed to the main object. | |
117 | master_config = None |
|
117 | master_config = None | |
118 | #: A reference to the argv to be used (typically ends up being sys.argv[1:]) |
|
118 | #: A reference to the argv to be used (typically ends up being sys.argv[1:]) | |
119 | argv = None |
|
119 | argv = None | |
120 | #: extra arguments computed by the command-line loader |
|
120 | #: extra arguments computed by the command-line loader | |
121 | extra_args = None |
|
121 | extra_args = None | |
122 | #: The class to use as the crash handler. |
|
122 | #: The class to use as the crash handler. | |
123 | crash_handler_class = crashhandler.CrashHandler |
|
123 | crash_handler_class = crashhandler.CrashHandler | |
124 |
|
124 | |||
125 | # Private attributes |
|
125 | # Private attributes | |
126 | _exiting = False |
|
126 | _exiting = False | |
127 | _initialized = False |
|
127 | _initialized = False | |
128 |
|
128 | |||
129 | def __init__(self, argv=None): |
|
129 | def __init__(self, argv=None): | |
130 | self.argv = sys.argv[1:] if argv is None else argv |
|
130 | self.argv = sys.argv[1:] if argv is None else argv | |
131 | self.init_logger() |
|
131 | self.init_logger() | |
132 |
|
132 | |||
133 | def init_logger(self): |
|
133 | def init_logger(self): | |
134 | self.log = logging.getLogger(self.__class__.__name__) |
|
134 | self.log = logging.getLogger(self.__class__.__name__) | |
135 | # This is used as the default until the command line arguments are read. |
|
135 | # This is used as the default until the command line arguments are read. | |
136 | self.log.setLevel(self.default_log_level) |
|
136 | self.log.setLevel(self.default_log_level) | |
137 | self._log_handler = logging.StreamHandler() |
|
137 | self._log_handler = logging.StreamHandler() | |
138 | self._log_formatter = logging.Formatter("[%(name)s] %(message)s") |
|
138 | self._log_formatter = logging.Formatter("[%(name)s] %(message)s") | |
139 | self._log_handler.setFormatter(self._log_formatter) |
|
139 | self._log_handler.setFormatter(self._log_formatter) | |
140 | self.log.addHandler(self._log_handler) |
|
140 | self.log.addHandler(self._log_handler) | |
141 |
|
141 | |||
142 | def _set_log_level(self, level): |
|
142 | def _set_log_level(self, level): | |
143 | self.log.setLevel(level) |
|
143 | self.log.setLevel(level) | |
144 |
|
144 | |||
145 | def _get_log_level(self): |
|
145 | def _get_log_level(self): | |
146 | return self.log.level |
|
146 | return self.log.level | |
147 |
|
147 | |||
148 | log_level = property(_get_log_level, _set_log_level) |
|
148 | log_level = property(_get_log_level, _set_log_level) | |
149 |
|
149 | |||
150 | def initialize(self): |
|
150 | def initialize(self): | |
151 | """Initialize the application. |
|
151 | """Initialize the application. | |
152 |
|
152 | |||
153 | Loads all configuration information and sets all application state, but |
|
153 | Loads all configuration information and sets all application state, but | |
154 | does not start any relevant processing (typically some kind of event |
|
154 | does not start any relevant processing (typically some kind of event | |
155 | loop). |
|
155 | loop). | |
156 |
|
156 | |||
157 | Once this method has been called, the application is flagged as |
|
157 | Once this method has been called, the application is flagged as | |
158 | initialized and the method becomes a no-op.""" |
|
158 | initialized and the method becomes a no-op.""" | |
159 |
|
159 | |||
160 | if self._initialized: |
|
160 | if self._initialized: | |
161 | return |
|
161 | return | |
162 |
|
162 | |||
163 | # The first part is protected with an 'attempt' wrapper, that will log |
|
163 | # The first part is protected with an 'attempt' wrapper, that will log | |
164 | # failures with the basic system traceback machinery. Once our crash |
|
164 | # failures with the basic system traceback machinery. Once our crash | |
165 | # handler is in place, we can let any subsequent exception propagate, |
|
165 | # handler is in place, we can let any subsequent exception propagate, | |
166 | # as our handler will log it with much better detail than the default. |
|
166 | # as our handler will log it with much better detail than the default. | |
167 | self.attempt(self.create_crash_handler) |
|
167 | self.attempt(self.create_crash_handler) | |
168 |
|
168 | |||
169 | # Configuration phase |
|
169 | # Configuration phase | |
170 | # Default config (internally hardwired in application code) |
|
170 | # Default config (internally hardwired in application code) | |
171 | self.create_default_config() |
|
171 | self.create_default_config() | |
172 | self.log_default_config() |
|
172 | self.log_default_config() | |
173 | self.set_default_config_log_level() |
|
173 | self.set_default_config_log_level() | |
174 |
|
174 | |||
175 | # Command-line config |
|
175 | # Command-line config | |
176 | self.pre_load_command_line_config() |
|
176 | self.pre_load_command_line_config() | |
177 | self.load_command_line_config() |
|
177 | self.load_command_line_config() | |
178 | self.set_command_line_config_log_level() |
|
178 | self.set_command_line_config_log_level() | |
179 | self.post_load_command_line_config() |
|
179 | self.post_load_command_line_config() | |
180 | self.log_command_line_config() |
|
180 | self.log_command_line_config() | |
181 |
|
181 | |||
182 | # Find resources needed for filesystem access, using information from |
|
182 | # Find resources needed for filesystem access, using information from | |
183 | # the above two |
|
183 | # the above two | |
184 | self.find_ipython_dir() |
|
184 | self.find_ipython_dir() | |
185 | self.find_resources() |
|
185 | self.find_resources() | |
186 | self.find_config_file_name() |
|
186 | self.find_config_file_name() | |
187 | self.find_config_file_paths() |
|
187 | self.find_config_file_paths() | |
188 |
|
188 | |||
189 | # File-based config |
|
189 | # File-based config | |
190 | self.pre_load_file_config() |
|
190 | self.pre_load_file_config() | |
191 | self.load_file_config() |
|
191 | self.load_file_config() | |
192 | self.set_file_config_log_level() |
|
192 | self.set_file_config_log_level() | |
193 | self.post_load_file_config() |
|
193 | self.post_load_file_config() | |
194 | self.log_file_config() |
|
194 | self.log_file_config() | |
195 |
|
195 | |||
196 | # Merge all config objects into a single one the app can then use |
|
196 | # Merge all config objects into a single one the app can then use | |
197 | self.merge_configs() |
|
197 | self.merge_configs() | |
198 | self.log_master_config() |
|
198 | self.log_master_config() | |
199 |
|
199 | |||
200 | # Construction phase |
|
200 | # Construction phase | |
201 | self.pre_construct() |
|
201 | self.pre_construct() | |
202 | self.construct() |
|
202 | self.construct() | |
203 | self.post_construct() |
|
203 | self.post_construct() | |
204 |
|
204 | |||
205 | # Done, flag as such and |
|
205 | # Done, flag as such and | |
206 | self._initialized = True |
|
206 | self._initialized = True | |
207 |
|
207 | |||
208 | def start(self): |
|
208 | def start(self): | |
209 | """Start the application.""" |
|
209 | """Start the application.""" | |
210 | self.initialize() |
|
210 | self.initialize() | |
211 | self.start_app() |
|
211 | self.start_app() | |
212 |
|
212 | |||
213 | #------------------------------------------------------------------------- |
|
213 | #------------------------------------------------------------------------- | |
214 | # Various stages of Application creation |
|
214 | # Various stages of Application creation | |
215 | #------------------------------------------------------------------------- |
|
215 | #------------------------------------------------------------------------- | |
216 |
|
216 | |||
217 | def create_crash_handler(self): |
|
217 | def create_crash_handler(self): | |
218 | """Create a crash handler, typically setting sys.excepthook to it.""" |
|
218 | """Create a crash handler, typically setting sys.excepthook to it.""" | |
219 | self.crash_handler = self.crash_handler_class(self) |
|
219 | self.crash_handler = self.crash_handler_class(self) | |
220 | sys.excepthook = self.crash_handler |
|
220 | sys.excepthook = self.crash_handler | |
221 |
|
221 | |||
222 | def create_default_config(self): |
|
222 | def create_default_config(self): | |
223 | """Create defaults that can't be set elsewhere. |
|
223 | """Create defaults that can't be set elsewhere. | |
224 |
|
224 | |||
225 | For the most part, we try to set default in the class attributes |
|
225 | For the most part, we try to set default in the class attributes | |
226 | of Configurables. But, defaults the top-level Application (which is |
|
226 | of Configurables. But, defaults the top-level Application (which is | |
227 | not a HasTraits or Configurables) are not set in this way. Instead |
|
227 | not a HasTraits or Configurables) are not set in this way. Instead | |
228 | we set them here. The Global section is for variables like this that |
|
228 | we set them here. The Global section is for variables like this that | |
229 | don't belong to a particular configurable. |
|
229 | don't belong to a particular configurable. | |
230 | """ |
|
230 | """ | |
231 | c = Config() |
|
231 | c = Config() | |
232 | c.Global.ipython_dir = get_ipython_dir() |
|
232 | c.Global.ipython_dir = get_ipython_dir() | |
233 | c.Global.log_level = self.log_level |
|
233 | c.Global.log_level = self.log_level | |
234 | self.default_config = c |
|
234 | self.default_config = c | |
235 |
|
235 | |||
236 | def log_default_config(self): |
|
236 | def log_default_config(self): | |
237 | self.log.debug('Default config loaded:') |
|
237 | self.log.debug('Default config loaded:') | |
238 | self.log.debug(repr(self.default_config)) |
|
238 | self.log.debug(repr(self.default_config)) | |
239 |
|
239 | |||
240 | def set_default_config_log_level(self): |
|
240 | def set_default_config_log_level(self): | |
241 | try: |
|
241 | try: | |
242 | self.log_level = self.default_config.Global.log_level |
|
242 | self.log_level = self.default_config.Global.log_level | |
243 | except AttributeError: |
|
243 | except AttributeError: | |
244 | # Fallback to the default_log_level class attribute |
|
244 | # Fallback to the default_log_level class attribute | |
245 | pass |
|
245 | pass | |
246 |
|
246 | |||
247 | def create_command_line_config(self): |
|
247 | def create_command_line_config(self): | |
248 | """Create and return a command line config loader.""" |
|
248 | """Create and return a command line config loader.""" | |
249 | return self.command_line_loader( |
|
249 | return self.command_line_loader( | |
250 | self.argv, |
|
250 | self.argv, | |
251 | description=self.description, |
|
251 | description=self.description, | |
252 | version=release.version, |
|
252 | version=release.version, | |
253 | usage=self.usage |
|
253 | usage=self.usage | |
254 | ) |
|
254 | ) | |
255 |
|
255 | |||
256 | def pre_load_command_line_config(self): |
|
256 | def pre_load_command_line_config(self): | |
257 | """Do actions just before loading the command line config.""" |
|
257 | """Do actions just before loading the command line config.""" | |
258 | pass |
|
258 | pass | |
259 |
|
259 | |||
260 | def load_command_line_config(self): |
|
260 | def load_command_line_config(self): | |
261 | """Load the command line config.""" |
|
261 | """Load the command line config.""" | |
262 | loader = self.create_command_line_config() |
|
262 | loader = self.create_command_line_config() | |
263 | self.command_line_config = loader.load_config() |
|
263 | self.command_line_config = loader.load_config() | |
264 | self.extra_args = loader.get_extra_args() |
|
264 | self.extra_args = loader.get_extra_args() | |
265 |
|
265 | |||
266 | def set_command_line_config_log_level(self): |
|
266 | def set_command_line_config_log_level(self): | |
267 | try: |
|
267 | try: | |
268 | self.log_level = self.command_line_config.Global.log_level |
|
268 | self.log_level = self.command_line_config.Global.log_level | |
269 | except AttributeError: |
|
269 | except AttributeError: | |
270 | pass |
|
270 | pass | |
271 |
|
271 | |||
272 | def post_load_command_line_config(self): |
|
272 | def post_load_command_line_config(self): | |
273 | """Do actions just after loading the command line config.""" |
|
273 | """Do actions just after loading the command line config.""" | |
274 | pass |
|
274 | pass | |
275 |
|
275 | |||
276 | def log_command_line_config(self): |
|
276 | def log_command_line_config(self): | |
277 | self.log.debug("Command line config loaded:") |
|
277 | self.log.debug("Command line config loaded:") | |
278 | self.log.debug(repr(self.command_line_config)) |
|
278 | self.log.debug(repr(self.command_line_config)) | |
279 |
|
279 | |||
280 | def find_ipython_dir(self): |
|
280 | def find_ipython_dir(self): | |
281 | """Set the IPython directory. |
|
281 | """Set the IPython directory. | |
282 |
|
282 | |||
283 | This sets ``self.ipython_dir``, but the actual value that is passed to |
|
283 | This sets ``self.ipython_dir``, but the actual value that is passed to | |
284 | the application is kept in either ``self.default_config`` or |
|
284 | the application is kept in either ``self.default_config`` or | |
285 | ``self.command_line_config``. This also adds ``self.ipython_dir`` to |
|
285 | ``self.command_line_config``. This also adds ``self.ipython_dir`` to | |
286 | ``sys.path`` so config files there can be referenced by other config |
|
286 | ``sys.path`` so config files there can be referenced by other config | |
287 | files. |
|
287 | files. | |
288 | """ |
|
288 | """ | |
289 |
|
289 | |||
290 | try: |
|
290 | try: | |
291 | self.ipython_dir = self.command_line_config.Global.ipython_dir |
|
291 | self.ipython_dir = self.command_line_config.Global.ipython_dir | |
292 | except AttributeError: |
|
292 | except AttributeError: | |
293 | self.ipython_dir = self.default_config.Global.ipython_dir |
|
293 | self.ipython_dir = self.default_config.Global.ipython_dir | |
294 | sys.path.append(os.path.abspath(self.ipython_dir)) |
|
294 | sys.path.append(os.path.abspath(self.ipython_dir)) | |
295 | if not os.path.isdir(self.ipython_dir): |
|
295 | if not os.path.isdir(self.ipython_dir): | |
296 | os.makedirs(self.ipython_dir, mode=0777) |
|
296 | os.makedirs(self.ipython_dir, mode=0777) | |
297 | self.log.debug("IPYTHON_DIR set to: %s" % self.ipython_dir) |
|
297 | self.log.debug("IPYTHON_DIR set to: %s" % self.ipython_dir) | |
298 |
|
298 | |||
299 | def find_resources(self): |
|
299 | def find_resources(self): | |
300 | """Find other resources that need to be in place. |
|
300 | """Find other resources that need to be in place. | |
301 |
|
301 | |||
302 | Things like cluster directories need to be in place to find the |
|
302 | Things like cluster directories need to be in place to find the | |
303 | config file. These happen right after the IPython directory has |
|
303 | config file. These happen right after the IPython directory has | |
304 | been set. |
|
304 | been set. | |
305 | """ |
|
305 | """ | |
306 | pass |
|
306 | pass | |
307 |
|
307 | |||
308 | def find_config_file_name(self): |
|
308 | def find_config_file_name(self): | |
309 | """Find the config file name for this application. |
|
309 | """Find the config file name for this application. | |
310 |
|
310 | |||
311 | This must set ``self.config_file_name`` to the filename of the |
|
311 | This must set ``self.config_file_name`` to the filename of the | |
312 | config file to use (just the filename). The search paths for the |
|
312 | config file to use (just the filename). The search paths for the | |
313 | config file are set in :meth:`find_config_file_paths` and then passed |
|
313 | config file are set in :meth:`find_config_file_paths` and then passed | |
314 | to the config file loader where they are resolved to an absolute path. |
|
314 | to the config file loader where they are resolved to an absolute path. | |
315 |
|
315 | |||
316 | If a profile has been set at the command line, this will resolve it. |
|
316 | If a profile has been set at the command line, this will resolve it. | |
317 | """ |
|
317 | """ | |
318 | try: |
|
318 | try: | |
319 | self.config_file_name = self.command_line_config.Global.config_file |
|
319 | self.config_file_name = self.command_line_config.Global.config_file | |
320 | except AttributeError: |
|
320 | except AttributeError: | |
321 | pass |
|
321 | pass | |
322 | else: |
|
322 | else: | |
323 | return |
|
323 | return | |
324 |
|
324 | |||
325 | try: |
|
325 | try: | |
326 | self.profile_name = self.command_line_config.Global.profile |
|
326 | self.profile_name = self.command_line_config.Global.profile | |
327 | except AttributeError: |
|
327 | except AttributeError: | |
328 | # Just use the default as there is no profile |
|
328 | # Just use the default as there is no profile | |
329 | self.config_file_name = self.default_config_file_name |
|
329 | self.config_file_name = self.default_config_file_name | |
330 | else: |
|
330 | else: | |
331 | # Use the default config file name and profile name if set |
|
331 | # Use the default config file name and profile name if set | |
332 | # to determine the used config file name. |
|
332 | # to determine the used config file name. | |
333 | name_parts = self.default_config_file_name.split('.') |
|
333 | name_parts = self.default_config_file_name.split('.') | |
334 | name_parts.insert(1, u'_' + self.profile_name + u'.') |
|
334 | name_parts.insert(1, u'_' + self.profile_name + u'.') | |
335 | self.config_file_name = ''.join(name_parts) |
|
335 | self.config_file_name = ''.join(name_parts) | |
336 |
|
336 | |||
337 | def find_config_file_paths(self): |
|
337 | def find_config_file_paths(self): | |
338 | """Set the search paths for resolving the config file. |
|
338 | """Set the search paths for resolving the config file. | |
339 |
|
339 | |||
340 | This must set ``self.config_file_paths`` to a sequence of search |
|
340 | This must set ``self.config_file_paths`` to a sequence of search | |
341 | paths to pass to the config file loader. |
|
341 | paths to pass to the config file loader. | |
342 | """ |
|
342 | """ | |
343 | # Include our own profiles directory last, so that users can still find |
|
343 | # Include our own profiles directory last, so that users can still find | |
344 | # our shipped copies of builtin profiles even if they don't have them |
|
344 | # our shipped copies of builtin profiles even if they don't have them | |
345 | # in their local ipython directory. |
|
345 | # in their local ipython directory. | |
346 | prof_dir = os.path.join(get_ipython_package_dir(), 'config', 'profile') |
|
346 | prof_dir = os.path.join(get_ipython_package_dir(), 'config', 'profile') | |
347 | self.config_file_paths = (os.getcwd(), self.ipython_dir, prof_dir) |
|
347 | self.config_file_paths = (os.getcwd(), self.ipython_dir, prof_dir) | |
348 |
|
348 | |||
349 | def pre_load_file_config(self): |
|
349 | def pre_load_file_config(self): | |
350 | """Do actions before the config file is loaded.""" |
|
350 | """Do actions before the config file is loaded.""" | |
351 | pass |
|
351 | pass | |
352 |
|
352 | |||
353 | def load_file_config(self): |
|
353 | def load_file_config(self): | |
354 | """Load the config file. |
|
354 | """Load the config file. | |
355 |
|
355 | |||
356 | This tries to load the config file from disk. If successful, the |
|
356 | This tries to load the config file from disk. If successful, the | |
357 | ``CONFIG_FILE`` config variable is set to the resolved config file |
|
357 | ``CONFIG_FILE`` config variable is set to the resolved config file | |
358 | location. If not successful, an empty config is used. |
|
358 | location. If not successful, an empty config is used. | |
359 | """ |
|
359 | """ | |
360 | self.log.debug("Attempting to load config file: %s" % |
|
360 | self.log.debug("Attempting to load config file: %s" % | |
361 | self.config_file_name) |
|
361 | self.config_file_name) | |
362 | loader = PyFileConfigLoader(self.config_file_name, |
|
362 | loader = PyFileConfigLoader(self.config_file_name, | |
363 | path=self.config_file_paths) |
|
363 | path=self.config_file_paths) | |
364 | try: |
|
364 | try: | |
365 | self.file_config = loader.load_config() |
|
365 | self.file_config = loader.load_config() | |
366 | self.file_config.Global.config_file = loader.full_filename |
|
366 | self.file_config.Global.config_file = loader.full_filename | |
367 | except IOError: |
|
367 | except IOError: | |
368 | # Only warn if the default config file was NOT being used. |
|
368 | # Only warn if the default config file was NOT being used. | |
369 | if not self.config_file_name==self.default_config_file_name: |
|
369 | if not self.config_file_name==self.default_config_file_name: | |
370 | self.log.warn("Config file not found, skipping: %s" % |
|
370 | self.log.warn("Config file not found, skipping: %s" % | |
371 | self.config_file_name, exc_info=True) |
|
371 | self.config_file_name, exc_info=True) | |
372 | self.file_config = Config() |
|
372 | self.file_config = Config() | |
373 | except: |
|
373 | except: | |
374 | self.log.warn("Error loading config file: %s" % |
|
374 | self.log.warn("Error loading config file: %s" % | |
375 | self.config_file_name, exc_info=True) |
|
375 | self.config_file_name, exc_info=True) | |
376 | self.file_config = Config() |
|
376 | self.file_config = Config() | |
377 |
|
377 | |||
378 | def set_file_config_log_level(self): |
|
378 | def set_file_config_log_level(self): | |
379 | # We need to keeep self.log_level updated. But we only use the value |
|
379 | # We need to keeep self.log_level updated. But we only use the value | |
380 | # of the file_config if a value was not specified at the command |
|
380 | # of the file_config if a value was not specified at the command | |
381 | # line, because the command line overrides everything. |
|
381 | # line, because the command line overrides everything. | |
382 | if not hasattr(self.command_line_config.Global, 'log_level'): |
|
382 | if not hasattr(self.command_line_config.Global, 'log_level'): | |
383 | try: |
|
383 | try: | |
384 | self.log_level = self.file_config.Global.log_level |
|
384 | self.log_level = self.file_config.Global.log_level | |
385 | except AttributeError: |
|
385 | except AttributeError: | |
386 | pass # Use existing value |
|
386 | pass # Use existing value | |
387 |
|
387 | |||
388 | def post_load_file_config(self): |
|
388 | def post_load_file_config(self): | |
389 | """Do actions after the config file is loaded.""" |
|
389 | """Do actions after the config file is loaded.""" | |
390 | pass |
|
390 | pass | |
391 |
|
391 | |||
392 | def log_file_config(self): |
|
392 | def log_file_config(self): | |
393 | if hasattr(self.file_config.Global, 'config_file'): |
|
393 | if hasattr(self.file_config.Global, 'config_file'): | |
394 | self.log.debug("Config file loaded: %s" % |
|
394 | self.log.debug("Config file loaded: %s" % | |
395 | self.file_config.Global.config_file) |
|
395 | self.file_config.Global.config_file) | |
396 | self.log.debug(repr(self.file_config)) |
|
396 | self.log.debug(repr(self.file_config)) | |
397 |
|
397 | |||
398 | def merge_configs(self): |
|
398 | def merge_configs(self): | |
399 | """Merge the default, command line and file config objects.""" |
|
399 | """Merge the default, command line and file config objects.""" | |
400 | config = Config() |
|
400 | config = Config() | |
401 | config._merge(self.default_config) |
|
401 | config._merge(self.default_config) | |
402 | config._merge(self.file_config) |
|
402 | config._merge(self.file_config) | |
403 | config._merge(self.command_line_config) |
|
403 | config._merge(self.command_line_config) | |
404 |
|
404 | |||
405 | # XXX fperez - propose to Brian we rename master_config to simply |
|
405 | # XXX fperez - propose to Brian we rename master_config to simply | |
406 | # config, I think this is going to be heavily used in examples and |
|
406 | # config, I think this is going to be heavily used in examples and | |
407 | # application code and the name is shorter/easier to find/remember. |
|
407 | # application code and the name is shorter/easier to find/remember. | |
408 | # For now, just alias it... |
|
408 | # For now, just alias it... | |
409 | self.master_config = config |
|
409 | self.master_config = config | |
410 | self.config = config |
|
410 | self.config = config | |
411 |
|
411 | |||
412 | def log_master_config(self): |
|
412 | def log_master_config(self): | |
413 | self.log.debug("Master config created:") |
|
413 | self.log.debug("Master config created:") | |
414 | self.log.debug(repr(self.master_config)) |
|
414 | self.log.debug(repr(self.master_config)) | |
415 |
|
415 | |||
416 | def pre_construct(self): |
|
416 | def pre_construct(self): | |
417 | """Do actions after the config has been built, but before construct.""" |
|
417 | """Do actions after the config has been built, but before construct.""" | |
418 | pass |
|
418 | pass | |
419 |
|
419 | |||
420 | def construct(self): |
|
420 | def construct(self): | |
421 | """Construct the main objects that make up this app.""" |
|
421 | """Construct the main objects that make up this app.""" | |
422 | self.log.debug("Constructing main objects for application") |
|
422 | self.log.debug("Constructing main objects for application") | |
423 |
|
423 | |||
424 | def post_construct(self): |
|
424 | def post_construct(self): | |
425 | """Do actions after construct, but before starting the app.""" |
|
425 | """Do actions after construct, but before starting the app.""" | |
426 | pass |
|
426 | pass | |
427 |
|
427 | |||
428 | def start_app(self): |
|
428 | def start_app(self): | |
429 | """Actually start the app.""" |
|
429 | """Actually start the app.""" | |
430 | self.log.debug("Starting application") |
|
430 | self.log.debug("Starting application") | |
431 |
|
431 | |||
432 | #------------------------------------------------------------------------- |
|
432 | #------------------------------------------------------------------------- | |
433 | # Utility methods |
|
433 | # Utility methods | |
434 | #------------------------------------------------------------------------- |
|
434 | #------------------------------------------------------------------------- | |
435 |
|
435 | |||
436 | def exit(self, exit_status=0): |
|
436 | def exit(self, exit_status=0): | |
437 | if self._exiting: |
|
437 | if self._exiting: | |
438 | pass |
|
438 | pass | |
439 | else: |
|
439 | else: | |
440 | self.log.debug("Exiting application: %s" % self.name) |
|
440 | self.log.debug("Exiting application: %s" % self.name) | |
441 | self._exiting = True |
|
441 | self._exiting = True | |
442 | sys.exit(exit_status) |
|
442 | sys.exit(exit_status) | |
443 |
|
443 | |||
444 | def attempt(self, func): |
|
444 | def attempt(self, func): | |
445 | try: |
|
445 | try: | |
446 | func() |
|
446 | func() | |
447 | except SystemExit: |
|
447 | except SystemExit: | |
448 | raise |
|
448 | raise | |
449 | except: |
|
449 | except: | |
450 | self.log.critical("Aborting application: %s" % self.name, |
|
450 | self.log.critical("Aborting application: %s" % self.name, | |
451 | exc_info=True) |
|
451 | exc_info=True) | |
452 | self.exit(0) |
|
452 | self.exit(0) | |
453 |
|
453 |
@@ -1,3510 +1,3510 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-2009 The IPython Development Team |
|
8 | # Copyright (C) 2008-2009 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__ |
|
18 | import __builtin__ | |
19 | import __future__ |
|
19 | import __future__ | |
20 | import bdb |
|
20 | import bdb | |
21 | import inspect |
|
21 | import inspect | |
22 | import os |
|
22 | import os | |
23 | import sys |
|
23 | import sys | |
24 | import shutil |
|
24 | import shutil | |
25 | import re |
|
25 | import re | |
26 | import time |
|
26 | import time | |
27 | import textwrap |
|
27 | import textwrap | |
28 | import types |
|
28 | import types | |
29 | from cStringIO import StringIO |
|
29 | from cStringIO import StringIO | |
30 | from getopt import getopt,GetoptError |
|
30 | from getopt import getopt,GetoptError | |
31 | from pprint import pformat |
|
31 | from pprint import pformat | |
32 |
|
32 | |||
33 | # cProfile was added in Python2.5 |
|
33 | # cProfile was added in Python2.5 | |
34 | try: |
|
34 | try: | |
35 | import cProfile as profile |
|
35 | import cProfile as profile | |
36 | import pstats |
|
36 | import pstats | |
37 | except ImportError: |
|
37 | except ImportError: | |
38 | # profile isn't bundled by default in Debian for license reasons |
|
38 | # profile isn't bundled by default in Debian for license reasons | |
39 | try: |
|
39 | try: | |
40 | import profile,pstats |
|
40 | import profile,pstats | |
41 | except ImportError: |
|
41 | except ImportError: | |
42 | profile = pstats = None |
|
42 | profile = pstats = None | |
43 |
|
43 | |||
44 | import IPython |
|
44 | import IPython | |
45 | from IPython.core import debugger, oinspect |
|
45 | from IPython.core import debugger, oinspect | |
46 | from IPython.core.error import TryNext |
|
46 | from IPython.core.error import TryNext | |
47 | from IPython.core.error import UsageError |
|
47 | from IPython.core.error import UsageError | |
48 | from IPython.core.fakemodule import FakeModule |
|
48 | from IPython.core.fakemodule import FakeModule | |
49 | from IPython.core.macro import Macro |
|
49 | from IPython.core.macro import Macro | |
50 | from IPython.core import page |
|
50 | from IPython.core import page | |
51 | from IPython.core.prefilter import ESC_MAGIC |
|
51 | from IPython.core.prefilter import ESC_MAGIC | |
52 | from IPython.lib.pylabtools import mpl_runner |
|
52 | from IPython.lib.pylabtools import mpl_runner | |
53 | from IPython.external.Itpl import itpl, printpl |
|
53 | from IPython.external.Itpl import itpl, printpl | |
54 | from IPython.testing import decorators as testdec |
|
54 | from IPython.testing import decorators as testdec | |
55 | from IPython.utils.io import file_read, nlprint |
|
55 | from IPython.utils.io import file_read, nlprint | |
56 | import IPython.utils.io |
|
56 | import IPython.utils.io | |
57 | from IPython.utils.path import get_py_filename |
|
57 | from IPython.utils.path import get_py_filename | |
58 | from IPython.utils.process import arg_split, abbrev_cwd |
|
58 | from IPython.utils.process import arg_split, abbrev_cwd | |
59 | from IPython.utils.terminal import set_term_title |
|
59 | from IPython.utils.terminal import set_term_title | |
60 | from IPython.utils.text import LSString, SList, StringTypes, format_screen |
|
60 | from IPython.utils.text import LSString, SList, StringTypes, format_screen | |
61 | from IPython.utils.timing import clock, clock2 |
|
61 | from IPython.utils.timing import clock, clock2 | |
62 | from IPython.utils.warn import warn, error |
|
62 | from IPython.utils.warn import warn, error | |
63 | from IPython.utils.ipstruct import Struct |
|
63 | from IPython.utils.ipstruct import Struct | |
64 | import IPython.utils.generics |
|
64 | import IPython.utils.generics | |
65 |
|
65 | |||
66 | #----------------------------------------------------------------------------- |
|
66 | #----------------------------------------------------------------------------- | |
67 | # Utility functions |
|
67 | # Utility functions | |
68 | #----------------------------------------------------------------------------- |
|
68 | #----------------------------------------------------------------------------- | |
69 |
|
69 | |||
70 | def on_off(tag): |
|
70 | def on_off(tag): | |
71 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
71 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
72 | return ['OFF','ON'][tag] |
|
72 | return ['OFF','ON'][tag] | |
73 |
|
73 | |||
74 | class Bunch: pass |
|
74 | class Bunch: pass | |
75 |
|
75 | |||
76 | def compress_dhist(dh): |
|
76 | def compress_dhist(dh): | |
77 | head, tail = dh[:-10], dh[-10:] |
|
77 | head, tail = dh[:-10], dh[-10:] | |
78 |
|
78 | |||
79 | newhead = [] |
|
79 | newhead = [] | |
80 | done = set() |
|
80 | done = set() | |
81 | for h in head: |
|
81 | for h in head: | |
82 | if h in done: |
|
82 | if h in done: | |
83 | continue |
|
83 | continue | |
84 | newhead.append(h) |
|
84 | newhead.append(h) | |
85 | done.add(h) |
|
85 | done.add(h) | |
86 |
|
86 | |||
87 | return newhead + tail |
|
87 | return newhead + tail | |
88 |
|
88 | |||
89 |
|
89 | |||
90 | #*************************************************************************** |
|
90 | #*************************************************************************** | |
91 | # Main class implementing Magic functionality |
|
91 | # Main class implementing Magic functionality | |
92 |
|
92 | |||
93 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors |
|
93 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors | |
94 | # on construction of the main InteractiveShell object. Something odd is going |
|
94 | # on construction of the main InteractiveShell object. Something odd is going | |
95 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but |
|
95 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but | |
96 | # eventually this needs to be clarified. |
|
96 | # eventually this needs to be clarified. | |
97 | # BG: This is because InteractiveShell inherits from this, but is itself a |
|
97 | # BG: This is because InteractiveShell inherits from this, but is itself a | |
98 | # Configurable. This messes up the MRO in some way. The fix is that we need to |
|
98 | # Configurable. This messes up the MRO in some way. The fix is that we need to | |
99 | # make Magic a configurable that InteractiveShell does not subclass. |
|
99 | # make Magic a configurable that InteractiveShell does not subclass. | |
100 |
|
100 | |||
101 | class Magic: |
|
101 | class Magic: | |
102 | """Magic functions for InteractiveShell. |
|
102 | """Magic functions for InteractiveShell. | |
103 |
|
103 | |||
104 | Shell functions which can be reached as %function_name. All magic |
|
104 | Shell functions which can be reached as %function_name. All magic | |
105 | functions should accept a string, which they can parse for their own |
|
105 | functions should accept a string, which they can parse for their own | |
106 | needs. This can make some functions easier to type, eg `%cd ../` |
|
106 | needs. This can make some functions easier to type, eg `%cd ../` | |
107 | vs. `%cd("../")` |
|
107 | vs. `%cd("../")` | |
108 |
|
108 | |||
109 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
109 | ALL definitions MUST begin with the prefix magic_. The user won't need it | |
110 | at the command line, but it is is needed in the definition. """ |
|
110 | at the command line, but it is is needed in the definition. """ | |
111 |
|
111 | |||
112 | # class globals |
|
112 | # class globals | |
113 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
113 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', | |
114 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
114 | 'Automagic is ON, % prefix NOT needed for magic functions.'] | |
115 |
|
115 | |||
116 | #...................................................................... |
|
116 | #...................................................................... | |
117 | # some utility functions |
|
117 | # some utility functions | |
118 |
|
118 | |||
119 | def __init__(self,shell): |
|
119 | def __init__(self,shell): | |
120 |
|
120 | |||
121 | self.options_table = {} |
|
121 | self.options_table = {} | |
122 | if profile is None: |
|
122 | if profile is None: | |
123 | self.magic_prun = self.profile_missing_notice |
|
123 | self.magic_prun = self.profile_missing_notice | |
124 | self.shell = shell |
|
124 | self.shell = shell | |
125 |
|
125 | |||
126 | # namespace for holding state we may need |
|
126 | # namespace for holding state we may need | |
127 | self._magic_state = Bunch() |
|
127 | self._magic_state = Bunch() | |
128 |
|
128 | |||
129 | def profile_missing_notice(self, *args, **kwargs): |
|
129 | def profile_missing_notice(self, *args, **kwargs): | |
130 | error("""\ |
|
130 | error("""\ | |
131 | The profile module could not be found. It has been removed from the standard |
|
131 | The profile module could not be found. It has been removed from the standard | |
132 | python packages because of its non-free license. To use profiling, install the |
|
132 | python packages because of its non-free license. To use profiling, install the | |
133 | python-profiler package from non-free.""") |
|
133 | python-profiler package from non-free.""") | |
134 |
|
134 | |||
135 | def default_option(self,fn,optstr): |
|
135 | def default_option(self,fn,optstr): | |
136 | """Make an entry in the options_table for fn, with value optstr""" |
|
136 | """Make an entry in the options_table for fn, with value optstr""" | |
137 |
|
137 | |||
138 | if fn not in self.lsmagic(): |
|
138 | if fn not in self.lsmagic(): | |
139 | error("%s is not a magic function" % fn) |
|
139 | error("%s is not a magic function" % fn) | |
140 | self.options_table[fn] = optstr |
|
140 | self.options_table[fn] = optstr | |
141 |
|
141 | |||
142 | def lsmagic(self): |
|
142 | def lsmagic(self): | |
143 | """Return a list of currently available magic functions. |
|
143 | """Return a list of currently available magic functions. | |
144 |
|
144 | |||
145 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
145 | Gives a list of the bare names after mangling (['ls','cd', ...], not | |
146 | ['magic_ls','magic_cd',...]""" |
|
146 | ['magic_ls','magic_cd',...]""" | |
147 |
|
147 | |||
148 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
148 | # FIXME. This needs a cleanup, in the way the magics list is built. | |
149 |
|
149 | |||
150 | # magics in class definition |
|
150 | # magics in class definition | |
151 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
151 | class_magic = lambda fn: fn.startswith('magic_') and \ | |
152 | callable(Magic.__dict__[fn]) |
|
152 | callable(Magic.__dict__[fn]) | |
153 | # in instance namespace (run-time user additions) |
|
153 | # in instance namespace (run-time user additions) | |
154 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
154 | inst_magic = lambda fn: fn.startswith('magic_') and \ | |
155 | callable(self.__dict__[fn]) |
|
155 | callable(self.__dict__[fn]) | |
156 | # and bound magics by user (so they can access self): |
|
156 | # and bound magics by user (so they can access self): | |
157 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
157 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ | |
158 | callable(self.__class__.__dict__[fn]) |
|
158 | callable(self.__class__.__dict__[fn]) | |
159 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
159 | magics = filter(class_magic,Magic.__dict__.keys()) + \ | |
160 | filter(inst_magic,self.__dict__.keys()) + \ |
|
160 | filter(inst_magic,self.__dict__.keys()) + \ | |
161 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
161 | filter(inst_bound_magic,self.__class__.__dict__.keys()) | |
162 | out = [] |
|
162 | out = [] | |
163 | for fn in set(magics): |
|
163 | for fn in set(magics): | |
164 | out.append(fn.replace('magic_','',1)) |
|
164 | out.append(fn.replace('magic_','',1)) | |
165 | out.sort() |
|
165 | out.sort() | |
166 | return out |
|
166 | return out | |
167 |
|
167 | |||
168 | def extract_input_slices(self,slices,raw=False): |
|
168 | def extract_input_slices(self,slices,raw=False): | |
169 | """Return as a string a set of input history slices. |
|
169 | """Return as a string a set of input history slices. | |
170 |
|
170 | |||
171 | Inputs: |
|
171 | Inputs: | |
172 |
|
172 | |||
173 | - slices: the set of slices is given as a list of strings (like |
|
173 | - slices: the set of slices is given as a list of strings (like | |
174 | ['1','4:8','9'], since this function is for use by magic functions |
|
174 | ['1','4:8','9'], since this function is for use by magic functions | |
175 | which get their arguments as strings. |
|
175 | which get their arguments as strings. | |
176 |
|
176 | |||
177 | Optional inputs: |
|
177 | Optional inputs: | |
178 |
|
178 | |||
179 | - raw(False): by default, the processed input is used. If this is |
|
179 | - raw(False): by default, the processed input is used. If this is | |
180 | true, the raw input history is used instead. |
|
180 | true, the raw input history is used instead. | |
181 |
|
181 | |||
182 | Note that slices can be called with two notations: |
|
182 | Note that slices can be called with two notations: | |
183 |
|
183 | |||
184 | N:M -> standard python form, means including items N...(M-1). |
|
184 | N:M -> standard python form, means including items N...(M-1). | |
185 |
|
185 | |||
186 | N-M -> include items N..M (closed endpoint).""" |
|
186 | N-M -> include items N..M (closed endpoint).""" | |
187 |
|
187 | |||
188 | if raw: |
|
188 | if raw: | |
189 | hist = self.shell.history_manager.input_hist_raw |
|
189 | hist = self.shell.history_manager.input_hist_raw | |
190 | else: |
|
190 | else: | |
191 | hist = self.shell.history_manager.input_hist_parsed |
|
191 | hist = self.shell.history_manager.input_hist_parsed | |
192 |
|
192 | |||
193 | cmds = [] |
|
193 | cmds = [] | |
194 | for chunk in slices: |
|
194 | for chunk in slices: | |
195 | if ':' in chunk: |
|
195 | if ':' in chunk: | |
196 | ini,fin = map(int,chunk.split(':')) |
|
196 | ini,fin = map(int,chunk.split(':')) | |
197 | elif '-' in chunk: |
|
197 | elif '-' in chunk: | |
198 | ini,fin = map(int,chunk.split('-')) |
|
198 | ini,fin = map(int,chunk.split('-')) | |
199 | fin += 1 |
|
199 | fin += 1 | |
200 | else: |
|
200 | else: | |
201 | ini = int(chunk) |
|
201 | ini = int(chunk) | |
202 | fin = ini+1 |
|
202 | fin = ini+1 | |
203 | cmds.append(''.join(hist[ini:fin])) |
|
203 | cmds.append(''.join(hist[ini:fin])) | |
204 | return cmds |
|
204 | return cmds | |
205 |
|
205 | |||
206 | def arg_err(self,func): |
|
206 | def arg_err(self,func): | |
207 | """Print docstring if incorrect arguments were passed""" |
|
207 | """Print docstring if incorrect arguments were passed""" | |
208 | print 'Error in arguments:' |
|
208 | print 'Error in arguments:' | |
209 | print oinspect.getdoc(func) |
|
209 | print oinspect.getdoc(func) | |
210 |
|
210 | |||
211 | def format_latex(self,strng): |
|
211 | def format_latex(self,strng): | |
212 | """Format a string for latex inclusion.""" |
|
212 | """Format a string for latex inclusion.""" | |
213 |
|
213 | |||
214 | # Characters that need to be escaped for latex: |
|
214 | # Characters that need to be escaped for latex: | |
215 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
215 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) | |
216 | # Magic command names as headers: |
|
216 | # Magic command names as headers: | |
217 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
217 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, | |
218 | re.MULTILINE) |
|
218 | re.MULTILINE) | |
219 | # Magic commands |
|
219 | # Magic commands | |
220 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
220 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, | |
221 | re.MULTILINE) |
|
221 | re.MULTILINE) | |
222 | # Paragraph continue |
|
222 | # Paragraph continue | |
223 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
223 | par_re = re.compile(r'\\$',re.MULTILINE) | |
224 |
|
224 | |||
225 | # The "\n" symbol |
|
225 | # The "\n" symbol | |
226 | newline_re = re.compile(r'\\n') |
|
226 | newline_re = re.compile(r'\\n') | |
227 |
|
227 | |||
228 | # Now build the string for output: |
|
228 | # Now build the string for output: | |
229 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
229 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) | |
230 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
230 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', | |
231 | strng) |
|
231 | strng) | |
232 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
232 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) | |
233 | strng = par_re.sub(r'\\\\',strng) |
|
233 | strng = par_re.sub(r'\\\\',strng) | |
234 | strng = escape_re.sub(r'\\\1',strng) |
|
234 | strng = escape_re.sub(r'\\\1',strng) | |
235 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
235 | strng = newline_re.sub(r'\\textbackslash{}n',strng) | |
236 | return strng |
|
236 | return strng | |
237 |
|
237 | |||
238 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
238 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): | |
239 | """Parse options passed to an argument string. |
|
239 | """Parse options passed to an argument string. | |
240 |
|
240 | |||
241 | The interface is similar to that of getopt(), but it returns back a |
|
241 | The interface is similar to that of getopt(), but it returns back a | |
242 | Struct with the options as keys and the stripped argument string still |
|
242 | Struct with the options as keys and the stripped argument string still | |
243 | as a string. |
|
243 | as a string. | |
244 |
|
244 | |||
245 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
245 | arg_str is quoted as a true sys.argv vector by using shlex.split. | |
246 | This allows us to easily expand variables, glob files, quote |
|
246 | This allows us to easily expand variables, glob files, quote | |
247 | arguments, etc. |
|
247 | arguments, etc. | |
248 |
|
248 | |||
249 | Options: |
|
249 | Options: | |
250 | -mode: default 'string'. If given as 'list', the argument string is |
|
250 | -mode: default 'string'. If given as 'list', the argument string is | |
251 | returned as a list (split on whitespace) instead of a string. |
|
251 | returned as a list (split on whitespace) instead of a string. | |
252 |
|
252 | |||
253 | -list_all: put all option values in lists. Normally only options |
|
253 | -list_all: put all option values in lists. Normally only options | |
254 | appearing more than once are put in a list. |
|
254 | appearing more than once are put in a list. | |
255 |
|
255 | |||
256 | -posix (True): whether to split the input line in POSIX mode or not, |
|
256 | -posix (True): whether to split the input line in POSIX mode or not, | |
257 | as per the conventions outlined in the shlex module from the |
|
257 | as per the conventions outlined in the shlex module from the | |
258 | standard library.""" |
|
258 | standard library.""" | |
259 |
|
259 | |||
260 | # inject default options at the beginning of the input line |
|
260 | # inject default options at the beginning of the input line | |
261 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
261 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') | |
262 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
262 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
263 |
|
263 | |||
264 | mode = kw.get('mode','string') |
|
264 | mode = kw.get('mode','string') | |
265 | if mode not in ['string','list']: |
|
265 | if mode not in ['string','list']: | |
266 | raise ValueError,'incorrect mode given: %s' % mode |
|
266 | raise ValueError,'incorrect mode given: %s' % mode | |
267 | # Get options |
|
267 | # Get options | |
268 | list_all = kw.get('list_all',0) |
|
268 | list_all = kw.get('list_all',0) | |
269 | posix = kw.get('posix', os.name == 'posix') |
|
269 | posix = kw.get('posix', os.name == 'posix') | |
270 |
|
270 | |||
271 | # Check if we have more than one argument to warrant extra processing: |
|
271 | # Check if we have more than one argument to warrant extra processing: | |
272 | odict = {} # Dictionary with options |
|
272 | odict = {} # Dictionary with options | |
273 | args = arg_str.split() |
|
273 | args = arg_str.split() | |
274 | if len(args) >= 1: |
|
274 | if len(args) >= 1: | |
275 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
275 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
276 | # need to look for options |
|
276 | # need to look for options | |
277 | argv = arg_split(arg_str,posix) |
|
277 | argv = arg_split(arg_str,posix) | |
278 | # Do regular option processing |
|
278 | # Do regular option processing | |
279 | try: |
|
279 | try: | |
280 | opts,args = getopt(argv,opt_str,*long_opts) |
|
280 | opts,args = getopt(argv,opt_str,*long_opts) | |
281 | except GetoptError,e: |
|
281 | except GetoptError,e: | |
282 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
282 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, | |
283 | " ".join(long_opts))) |
|
283 | " ".join(long_opts))) | |
284 | for o,a in opts: |
|
284 | for o,a in opts: | |
285 | if o.startswith('--'): |
|
285 | if o.startswith('--'): | |
286 | o = o[2:] |
|
286 | o = o[2:] | |
287 | else: |
|
287 | else: | |
288 | o = o[1:] |
|
288 | o = o[1:] | |
289 | try: |
|
289 | try: | |
290 | odict[o].append(a) |
|
290 | odict[o].append(a) | |
291 | except AttributeError: |
|
291 | except AttributeError: | |
292 | odict[o] = [odict[o],a] |
|
292 | odict[o] = [odict[o],a] | |
293 | except KeyError: |
|
293 | except KeyError: | |
294 | if list_all: |
|
294 | if list_all: | |
295 | odict[o] = [a] |
|
295 | odict[o] = [a] | |
296 | else: |
|
296 | else: | |
297 | odict[o] = a |
|
297 | odict[o] = a | |
298 |
|
298 | |||
299 | # Prepare opts,args for return |
|
299 | # Prepare opts,args for return | |
300 | opts = Struct(odict) |
|
300 | opts = Struct(odict) | |
301 | if mode == 'string': |
|
301 | if mode == 'string': | |
302 | args = ' '.join(args) |
|
302 | args = ' '.join(args) | |
303 |
|
303 | |||
304 | return opts,args |
|
304 | return opts,args | |
305 |
|
305 | |||
306 | #...................................................................... |
|
306 | #...................................................................... | |
307 | # And now the actual magic functions |
|
307 | # And now the actual magic functions | |
308 |
|
308 | |||
309 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
309 | # Functions for IPython shell work (vars,funcs, config, etc) | |
310 | def magic_lsmagic(self, parameter_s = ''): |
|
310 | def magic_lsmagic(self, parameter_s = ''): | |
311 | """List currently available magic functions.""" |
|
311 | """List currently available magic functions.""" | |
312 | mesc = ESC_MAGIC |
|
312 | mesc = ESC_MAGIC | |
313 | print 'Available magic functions:\n'+mesc+\ |
|
313 | print 'Available magic functions:\n'+mesc+\ | |
314 | (' '+mesc).join(self.lsmagic()) |
|
314 | (' '+mesc).join(self.lsmagic()) | |
315 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
315 | print '\n' + Magic.auto_status[self.shell.automagic] | |
316 | return None |
|
316 | return None | |
317 |
|
317 | |||
318 | def magic_magic(self, parameter_s = ''): |
|
318 | def magic_magic(self, parameter_s = ''): | |
319 | """Print information about the magic function system. |
|
319 | """Print information about the magic function system. | |
320 |
|
320 | |||
321 | Supported formats: -latex, -brief, -rest |
|
321 | Supported formats: -latex, -brief, -rest | |
322 | """ |
|
322 | """ | |
323 |
|
323 | |||
324 | mode = '' |
|
324 | mode = '' | |
325 | try: |
|
325 | try: | |
326 | if parameter_s.split()[0] == '-latex': |
|
326 | if parameter_s.split()[0] == '-latex': | |
327 | mode = 'latex' |
|
327 | mode = 'latex' | |
328 | if parameter_s.split()[0] == '-brief': |
|
328 | if parameter_s.split()[0] == '-brief': | |
329 | mode = 'brief' |
|
329 | mode = 'brief' | |
330 | if parameter_s.split()[0] == '-rest': |
|
330 | if parameter_s.split()[0] == '-rest': | |
331 | mode = 'rest' |
|
331 | mode = 'rest' | |
332 | rest_docs = [] |
|
332 | rest_docs = [] | |
333 | except: |
|
333 | except: | |
334 | pass |
|
334 | pass | |
335 |
|
335 | |||
336 | magic_docs = [] |
|
336 | magic_docs = [] | |
337 | for fname in self.lsmagic(): |
|
337 | for fname in self.lsmagic(): | |
338 | mname = 'magic_' + fname |
|
338 | mname = 'magic_' + fname | |
339 | for space in (Magic,self,self.__class__): |
|
339 | for space in (Magic,self,self.__class__): | |
340 | try: |
|
340 | try: | |
341 | fn = space.__dict__[mname] |
|
341 | fn = space.__dict__[mname] | |
342 | except KeyError: |
|
342 | except KeyError: | |
343 | pass |
|
343 | pass | |
344 | else: |
|
344 | else: | |
345 | break |
|
345 | break | |
346 | if mode == 'brief': |
|
346 | if mode == 'brief': | |
347 | # only first line |
|
347 | # only first line | |
348 | if fn.__doc__: |
|
348 | if fn.__doc__: | |
349 | fndoc = fn.__doc__.split('\n',1)[0] |
|
349 | fndoc = fn.__doc__.split('\n',1)[0] | |
350 | else: |
|
350 | else: | |
351 | fndoc = 'No documentation' |
|
351 | fndoc = 'No documentation' | |
352 | else: |
|
352 | else: | |
353 | if fn.__doc__: |
|
353 | if fn.__doc__: | |
354 | fndoc = fn.__doc__.rstrip() |
|
354 | fndoc = fn.__doc__.rstrip() | |
355 | else: |
|
355 | else: | |
356 | fndoc = 'No documentation' |
|
356 | fndoc = 'No documentation' | |
357 |
|
357 | |||
358 |
|
358 | |||
359 | if mode == 'rest': |
|
359 | if mode == 'rest': | |
360 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, |
|
360 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, | |
361 | fname,fndoc)) |
|
361 | fname,fndoc)) | |
362 |
|
362 | |||
363 | else: |
|
363 | else: | |
364 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, |
|
364 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, | |
365 | fname,fndoc)) |
|
365 | fname,fndoc)) | |
366 |
|
366 | |||
367 | magic_docs = ''.join(magic_docs) |
|
367 | magic_docs = ''.join(magic_docs) | |
368 |
|
368 | |||
369 | if mode == 'rest': |
|
369 | if mode == 'rest': | |
370 | return "".join(rest_docs) |
|
370 | return "".join(rest_docs) | |
371 |
|
371 | |||
372 | if mode == 'latex': |
|
372 | if mode == 'latex': | |
373 | print self.format_latex(magic_docs) |
|
373 | print self.format_latex(magic_docs) | |
374 | return |
|
374 | return | |
375 | else: |
|
375 | else: | |
376 | magic_docs = format_screen(magic_docs) |
|
376 | magic_docs = format_screen(magic_docs) | |
377 | if mode == 'brief': |
|
377 | if mode == 'brief': | |
378 | return magic_docs |
|
378 | return magic_docs | |
379 |
|
379 | |||
380 | outmsg = """ |
|
380 | outmsg = """ | |
381 | IPython's 'magic' functions |
|
381 | IPython's 'magic' functions | |
382 | =========================== |
|
382 | =========================== | |
383 |
|
383 | |||
384 | The magic function system provides a series of functions which allow you to |
|
384 | The magic function system provides a series of functions which allow you to | |
385 | control the behavior of IPython itself, plus a lot of system-type |
|
385 | control the behavior of IPython itself, plus a lot of system-type | |
386 | features. All these functions are prefixed with a % character, but parameters |
|
386 | features. All these functions are prefixed with a % character, but parameters | |
387 | are given without parentheses or quotes. |
|
387 | are given without parentheses or quotes. | |
388 |
|
388 | |||
389 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
389 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
390 | %automagic function), you don't need to type in the % explicitly. By default, |
|
390 | %automagic function), you don't need to type in the % explicitly. By default, | |
391 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
391 | IPython ships with automagic on, so you should only rarely need the % escape. | |
392 |
|
392 | |||
393 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
393 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
394 | to 'mydir', if it exists. |
|
394 | to 'mydir', if it exists. | |
395 |
|
395 | |||
396 | You can define your own magic functions to extend the system. See the supplied |
|
396 | You can define your own magic functions to extend the system. See the supplied | |
397 | ipythonrc and example-magic.py files for details (in your ipython |
|
397 | ipythonrc and example-magic.py files for details (in your ipython | |
398 | configuration directory, typically $HOME/.ipython/). |
|
398 | configuration directory, typically $HOME/.config/ipython on Linux or $HOME/.ipython elsewhere). | |
399 |
|
399 | |||
400 | You can also define your own aliased names for magic functions. In your |
|
400 | You can also define your own aliased names for magic functions. In your | |
401 | ipythonrc file, placing a line like: |
|
401 | ipythonrc file, placing a line like: | |
402 |
|
402 | |||
403 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
403 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile | |
404 |
|
404 | |||
405 | will define %pf as a new name for %profile. |
|
405 | will define %pf as a new name for %profile. | |
406 |
|
406 | |||
407 | You can also call magics in code using the magic() function, which IPython |
|
407 | You can also call magics in code using the magic() function, which IPython | |
408 | automatically adds to the builtin namespace. Type 'magic?' for details. |
|
408 | automatically adds to the builtin namespace. Type 'magic?' for details. | |
409 |
|
409 | |||
410 | For a list of the available magic functions, use %lsmagic. For a description |
|
410 | For a list of the available magic functions, use %lsmagic. For a description | |
411 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
411 | of any of them, type %magic_name?, e.g. '%cd?'. | |
412 |
|
412 | |||
413 | Currently the magic system has the following functions:\n""" |
|
413 | Currently the magic system has the following functions:\n""" | |
414 |
|
414 | |||
415 | mesc = ESC_MAGIC |
|
415 | mesc = ESC_MAGIC | |
416 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
416 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" | |
417 | "\n\n%s%s\n\n%s" % (outmsg, |
|
417 | "\n\n%s%s\n\n%s" % (outmsg, | |
418 | magic_docs,mesc,mesc, |
|
418 | magic_docs,mesc,mesc, | |
419 | (' '+mesc).join(self.lsmagic()), |
|
419 | (' '+mesc).join(self.lsmagic()), | |
420 | Magic.auto_status[self.shell.automagic] ) ) |
|
420 | Magic.auto_status[self.shell.automagic] ) ) | |
421 | page.page(outmsg) |
|
421 | page.page(outmsg) | |
422 |
|
422 | |||
423 | def magic_automagic(self, parameter_s = ''): |
|
423 | def magic_automagic(self, parameter_s = ''): | |
424 | """Make magic functions callable without having to type the initial %. |
|
424 | """Make magic functions callable without having to type the initial %. | |
425 |
|
425 | |||
426 | Without argumentsl toggles on/off (when off, you must call it as |
|
426 | Without argumentsl toggles on/off (when off, you must call it as | |
427 | %automagic, of course). With arguments it sets the value, and you can |
|
427 | %automagic, of course). With arguments it sets the value, and you can | |
428 | use any of (case insensitive): |
|
428 | use any of (case insensitive): | |
429 |
|
429 | |||
430 | - on,1,True: to activate |
|
430 | - on,1,True: to activate | |
431 |
|
431 | |||
432 | - off,0,False: to deactivate. |
|
432 | - off,0,False: to deactivate. | |
433 |
|
433 | |||
434 | Note that magic functions have lowest priority, so if there's a |
|
434 | Note that magic functions have lowest priority, so if there's a | |
435 | variable whose name collides with that of a magic fn, automagic won't |
|
435 | variable whose name collides with that of a magic fn, automagic won't | |
436 | work for that function (you get the variable instead). However, if you |
|
436 | work for that function (you get the variable instead). However, if you | |
437 | delete the variable (del var), the previously shadowed magic function |
|
437 | delete the variable (del var), the previously shadowed magic function | |
438 | becomes visible to automagic again.""" |
|
438 | becomes visible to automagic again.""" | |
439 |
|
439 | |||
440 | arg = parameter_s.lower() |
|
440 | arg = parameter_s.lower() | |
441 | if parameter_s in ('on','1','true'): |
|
441 | if parameter_s in ('on','1','true'): | |
442 | self.shell.automagic = True |
|
442 | self.shell.automagic = True | |
443 | elif parameter_s in ('off','0','false'): |
|
443 | elif parameter_s in ('off','0','false'): | |
444 | self.shell.automagic = False |
|
444 | self.shell.automagic = False | |
445 | else: |
|
445 | else: | |
446 | self.shell.automagic = not self.shell.automagic |
|
446 | self.shell.automagic = not self.shell.automagic | |
447 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
447 | print '\n' + Magic.auto_status[self.shell.automagic] | |
448 |
|
448 | |||
449 | @testdec.skip_doctest |
|
449 | @testdec.skip_doctest | |
450 | def magic_autocall(self, parameter_s = ''): |
|
450 | def magic_autocall(self, parameter_s = ''): | |
451 | """Make functions callable without having to type parentheses. |
|
451 | """Make functions callable without having to type parentheses. | |
452 |
|
452 | |||
453 | Usage: |
|
453 | Usage: | |
454 |
|
454 | |||
455 | %autocall [mode] |
|
455 | %autocall [mode] | |
456 |
|
456 | |||
457 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
457 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the | |
458 | value is toggled on and off (remembering the previous state). |
|
458 | value is toggled on and off (remembering the previous state). | |
459 |
|
459 | |||
460 | In more detail, these values mean: |
|
460 | In more detail, these values mean: | |
461 |
|
461 | |||
462 | 0 -> fully disabled |
|
462 | 0 -> fully disabled | |
463 |
|
463 | |||
464 | 1 -> active, but do not apply if there are no arguments on the line. |
|
464 | 1 -> active, but do not apply if there are no arguments on the line. | |
465 |
|
465 | |||
466 | In this mode, you get: |
|
466 | In this mode, you get: | |
467 |
|
467 | |||
468 | In [1]: callable |
|
468 | In [1]: callable | |
469 | Out[1]: <built-in function callable> |
|
469 | Out[1]: <built-in function callable> | |
470 |
|
470 | |||
471 | In [2]: callable 'hello' |
|
471 | In [2]: callable 'hello' | |
472 | ------> callable('hello') |
|
472 | ------> callable('hello') | |
473 | Out[2]: False |
|
473 | Out[2]: False | |
474 |
|
474 | |||
475 | 2 -> Active always. Even if no arguments are present, the callable |
|
475 | 2 -> Active always. Even if no arguments are present, the callable | |
476 | object is called: |
|
476 | object is called: | |
477 |
|
477 | |||
478 | In [2]: float |
|
478 | In [2]: float | |
479 | ------> float() |
|
479 | ------> float() | |
480 | Out[2]: 0.0 |
|
480 | Out[2]: 0.0 | |
481 |
|
481 | |||
482 | Note that even with autocall off, you can still use '/' at the start of |
|
482 | Note that even with autocall off, you can still use '/' at the start of | |
483 | a line to treat the first argument on the command line as a function |
|
483 | a line to treat the first argument on the command line as a function | |
484 | and add parentheses to it: |
|
484 | and add parentheses to it: | |
485 |
|
485 | |||
486 | In [8]: /str 43 |
|
486 | In [8]: /str 43 | |
487 | ------> str(43) |
|
487 | ------> str(43) | |
488 | Out[8]: '43' |
|
488 | Out[8]: '43' | |
489 |
|
489 | |||
490 | # all-random (note for auto-testing) |
|
490 | # all-random (note for auto-testing) | |
491 | """ |
|
491 | """ | |
492 |
|
492 | |||
493 | if parameter_s: |
|
493 | if parameter_s: | |
494 | arg = int(parameter_s) |
|
494 | arg = int(parameter_s) | |
495 | else: |
|
495 | else: | |
496 | arg = 'toggle' |
|
496 | arg = 'toggle' | |
497 |
|
497 | |||
498 | if not arg in (0,1,2,'toggle'): |
|
498 | if not arg in (0,1,2,'toggle'): | |
499 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
499 | error('Valid modes: (0->Off, 1->Smart, 2->Full') | |
500 | return |
|
500 | return | |
501 |
|
501 | |||
502 | if arg in (0,1,2): |
|
502 | if arg in (0,1,2): | |
503 | self.shell.autocall = arg |
|
503 | self.shell.autocall = arg | |
504 | else: # toggle |
|
504 | else: # toggle | |
505 | if self.shell.autocall: |
|
505 | if self.shell.autocall: | |
506 | self._magic_state.autocall_save = self.shell.autocall |
|
506 | self._magic_state.autocall_save = self.shell.autocall | |
507 | self.shell.autocall = 0 |
|
507 | self.shell.autocall = 0 | |
508 | else: |
|
508 | else: | |
509 | try: |
|
509 | try: | |
510 | self.shell.autocall = self._magic_state.autocall_save |
|
510 | self.shell.autocall = self._magic_state.autocall_save | |
511 | except AttributeError: |
|
511 | except AttributeError: | |
512 | self.shell.autocall = self._magic_state.autocall_save = 1 |
|
512 | self.shell.autocall = self._magic_state.autocall_save = 1 | |
513 |
|
513 | |||
514 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] |
|
514 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] | |
515 |
|
515 | |||
516 |
|
516 | |||
517 | def magic_page(self, parameter_s=''): |
|
517 | def magic_page(self, parameter_s=''): | |
518 | """Pretty print the object and display it through a pager. |
|
518 | """Pretty print the object and display it through a pager. | |
519 |
|
519 | |||
520 | %page [options] OBJECT |
|
520 | %page [options] OBJECT | |
521 |
|
521 | |||
522 | If no object is given, use _ (last output). |
|
522 | If no object is given, use _ (last output). | |
523 |
|
523 | |||
524 | Options: |
|
524 | Options: | |
525 |
|
525 | |||
526 | -r: page str(object), don't pretty-print it.""" |
|
526 | -r: page str(object), don't pretty-print it.""" | |
527 |
|
527 | |||
528 | # After a function contributed by Olivier Aubert, slightly modified. |
|
528 | # After a function contributed by Olivier Aubert, slightly modified. | |
529 |
|
529 | |||
530 | # Process options/args |
|
530 | # Process options/args | |
531 | opts,args = self.parse_options(parameter_s,'r') |
|
531 | opts,args = self.parse_options(parameter_s,'r') | |
532 | raw = 'r' in opts |
|
532 | raw = 'r' in opts | |
533 |
|
533 | |||
534 | oname = args and args or '_' |
|
534 | oname = args and args or '_' | |
535 | info = self._ofind(oname) |
|
535 | info = self._ofind(oname) | |
536 | if info['found']: |
|
536 | if info['found']: | |
537 | txt = (raw and str or pformat)( info['obj'] ) |
|
537 | txt = (raw and str or pformat)( info['obj'] ) | |
538 | page.page(txt) |
|
538 | page.page(txt) | |
539 | else: |
|
539 | else: | |
540 | print 'Object `%s` not found' % oname |
|
540 | print 'Object `%s` not found' % oname | |
541 |
|
541 | |||
542 | def magic_profile(self, parameter_s=''): |
|
542 | def magic_profile(self, parameter_s=''): | |
543 | """Print your currently active IPython profile.""" |
|
543 | """Print your currently active IPython profile.""" | |
544 | if self.shell.profile: |
|
544 | if self.shell.profile: | |
545 | printpl('Current IPython profile: $self.shell.profile.') |
|
545 | printpl('Current IPython profile: $self.shell.profile.') | |
546 | else: |
|
546 | else: | |
547 | print 'No profile active.' |
|
547 | print 'No profile active.' | |
548 |
|
548 | |||
549 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
549 | def magic_pinfo(self, parameter_s='', namespaces=None): | |
550 | """Provide detailed information about an object. |
|
550 | """Provide detailed information about an object. | |
551 |
|
551 | |||
552 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
552 | '%pinfo object' is just a synonym for object? or ?object.""" | |
553 |
|
553 | |||
554 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
554 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
555 |
|
555 | |||
556 |
|
556 | |||
557 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
557 | # detail_level: 0 -> obj? , 1 -> obj?? | |
558 | detail_level = 0 |
|
558 | detail_level = 0 | |
559 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
559 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
560 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
560 | # happen if the user types 'pinfo foo?' at the cmd line. | |
561 | pinfo,qmark1,oname,qmark2 = \ |
|
561 | pinfo,qmark1,oname,qmark2 = \ | |
562 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
562 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
563 | if pinfo or qmark1 or qmark2: |
|
563 | if pinfo or qmark1 or qmark2: | |
564 | detail_level = 1 |
|
564 | detail_level = 1 | |
565 | if "*" in oname: |
|
565 | if "*" in oname: | |
566 | self.magic_psearch(oname) |
|
566 | self.magic_psearch(oname) | |
567 | else: |
|
567 | else: | |
568 | self.shell._inspect('pinfo', oname, detail_level=detail_level, |
|
568 | self.shell._inspect('pinfo', oname, detail_level=detail_level, | |
569 | namespaces=namespaces) |
|
569 | namespaces=namespaces) | |
570 |
|
570 | |||
571 | def magic_pinfo2(self, parameter_s='', namespaces=None): |
|
571 | def magic_pinfo2(self, parameter_s='', namespaces=None): | |
572 | """Provide extra detailed information about an object. |
|
572 | """Provide extra detailed information about an object. | |
573 |
|
573 | |||
574 | '%pinfo2 object' is just a synonym for object?? or ??object.""" |
|
574 | '%pinfo2 object' is just a synonym for object?? or ??object.""" | |
575 | self.shell._inspect('pinfo', parameter_s, detail_level=1, |
|
575 | self.shell._inspect('pinfo', parameter_s, detail_level=1, | |
576 | namespaces=namespaces) |
|
576 | namespaces=namespaces) | |
577 |
|
577 | |||
578 | @testdec.skip_doctest |
|
578 | @testdec.skip_doctest | |
579 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
579 | def magic_pdef(self, parameter_s='', namespaces=None): | |
580 | """Print the definition header for any callable object. |
|
580 | """Print the definition header for any callable object. | |
581 |
|
581 | |||
582 | If the object is a class, print the constructor information. |
|
582 | If the object is a class, print the constructor information. | |
583 |
|
583 | |||
584 | Examples |
|
584 | Examples | |
585 | -------- |
|
585 | -------- | |
586 | :: |
|
586 | :: | |
587 |
|
587 | |||
588 | In [3]: %pdef urllib.urlopen |
|
588 | In [3]: %pdef urllib.urlopen | |
589 | urllib.urlopen(url, data=None, proxies=None) |
|
589 | urllib.urlopen(url, data=None, proxies=None) | |
590 | """ |
|
590 | """ | |
591 | self._inspect('pdef',parameter_s, namespaces) |
|
591 | self._inspect('pdef',parameter_s, namespaces) | |
592 |
|
592 | |||
593 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
593 | def magic_pdoc(self, parameter_s='', namespaces=None): | |
594 | """Print the docstring for an object. |
|
594 | """Print the docstring for an object. | |
595 |
|
595 | |||
596 | If the given object is a class, it will print both the class and the |
|
596 | If the given object is a class, it will print both the class and the | |
597 | constructor docstrings.""" |
|
597 | constructor docstrings.""" | |
598 | self._inspect('pdoc',parameter_s, namespaces) |
|
598 | self._inspect('pdoc',parameter_s, namespaces) | |
599 |
|
599 | |||
600 | def magic_psource(self, parameter_s='', namespaces=None): |
|
600 | def magic_psource(self, parameter_s='', namespaces=None): | |
601 | """Print (or run through pager) the source code for an object.""" |
|
601 | """Print (or run through pager) the source code for an object.""" | |
602 | self._inspect('psource',parameter_s, namespaces) |
|
602 | self._inspect('psource',parameter_s, namespaces) | |
603 |
|
603 | |||
604 | def magic_pfile(self, parameter_s=''): |
|
604 | def magic_pfile(self, parameter_s=''): | |
605 | """Print (or run through pager) the file where an object is defined. |
|
605 | """Print (or run through pager) the file where an object is defined. | |
606 |
|
606 | |||
607 | The file opens at the line where the object definition begins. IPython |
|
607 | The file opens at the line where the object definition begins. IPython | |
608 | will honor the environment variable PAGER if set, and otherwise will |
|
608 | will honor the environment variable PAGER if set, and otherwise will | |
609 | do its best to print the file in a convenient form. |
|
609 | do its best to print the file in a convenient form. | |
610 |
|
610 | |||
611 | If the given argument is not an object currently defined, IPython will |
|
611 | If the given argument is not an object currently defined, IPython will | |
612 | try to interpret it as a filename (automatically adding a .py extension |
|
612 | try to interpret it as a filename (automatically adding a .py extension | |
613 | if needed). You can thus use %pfile as a syntax highlighting code |
|
613 | if needed). You can thus use %pfile as a syntax highlighting code | |
614 | viewer.""" |
|
614 | viewer.""" | |
615 |
|
615 | |||
616 | # first interpret argument as an object name |
|
616 | # first interpret argument as an object name | |
617 | out = self._inspect('pfile',parameter_s) |
|
617 | out = self._inspect('pfile',parameter_s) | |
618 | # if not, try the input as a filename |
|
618 | # if not, try the input as a filename | |
619 | if out == 'not found': |
|
619 | if out == 'not found': | |
620 | try: |
|
620 | try: | |
621 | filename = get_py_filename(parameter_s) |
|
621 | filename = get_py_filename(parameter_s) | |
622 | except IOError,msg: |
|
622 | except IOError,msg: | |
623 | print msg |
|
623 | print msg | |
624 | return |
|
624 | return | |
625 | page.page(self.shell.inspector.format(file(filename).read())) |
|
625 | page.page(self.shell.inspector.format(file(filename).read())) | |
626 |
|
626 | |||
627 | def magic_psearch(self, parameter_s=''): |
|
627 | def magic_psearch(self, parameter_s=''): | |
628 | """Search for object in namespaces by wildcard. |
|
628 | """Search for object in namespaces by wildcard. | |
629 |
|
629 | |||
630 | %psearch [options] PATTERN [OBJECT TYPE] |
|
630 | %psearch [options] PATTERN [OBJECT TYPE] | |
631 |
|
631 | |||
632 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
632 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
633 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
633 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
634 | rest of the command line must be unchanged (options come first), so |
|
634 | rest of the command line must be unchanged (options come first), so | |
635 | for example the following forms are equivalent |
|
635 | for example the following forms are equivalent | |
636 |
|
636 | |||
637 | %psearch -i a* function |
|
637 | %psearch -i a* function | |
638 | -i a* function? |
|
638 | -i a* function? | |
639 | ?-i a* function |
|
639 | ?-i a* function | |
640 |
|
640 | |||
641 | Arguments: |
|
641 | Arguments: | |
642 |
|
642 | |||
643 | PATTERN |
|
643 | PATTERN | |
644 |
|
644 | |||
645 | where PATTERN is a string containing * as a wildcard similar to its |
|
645 | where PATTERN is a string containing * as a wildcard similar to its | |
646 | use in a shell. The pattern is matched in all namespaces on the |
|
646 | use in a shell. The pattern is matched in all namespaces on the | |
647 | search path. By default objects starting with a single _ are not |
|
647 | search path. By default objects starting with a single _ are not | |
648 | matched, many IPython generated objects have a single |
|
648 | matched, many IPython generated objects have a single | |
649 | underscore. The default is case insensitive matching. Matching is |
|
649 | underscore. The default is case insensitive matching. Matching is | |
650 | also done on the attributes of objects and not only on the objects |
|
650 | also done on the attributes of objects and not only on the objects | |
651 | in a module. |
|
651 | in a module. | |
652 |
|
652 | |||
653 | [OBJECT TYPE] |
|
653 | [OBJECT TYPE] | |
654 |
|
654 | |||
655 | Is the name of a python type from the types module. The name is |
|
655 | Is the name of a python type from the types module. The name is | |
656 | given in lowercase without the ending type, ex. StringType is |
|
656 | given in lowercase without the ending type, ex. StringType is | |
657 | written string. By adding a type here only objects matching the |
|
657 | written string. By adding a type here only objects matching the | |
658 | given type are matched. Using all here makes the pattern match all |
|
658 | given type are matched. Using all here makes the pattern match all | |
659 | types (this is the default). |
|
659 | types (this is the default). | |
660 |
|
660 | |||
661 | Options: |
|
661 | Options: | |
662 |
|
662 | |||
663 | -a: makes the pattern match even objects whose names start with a |
|
663 | -a: makes the pattern match even objects whose names start with a | |
664 | single underscore. These names are normally ommitted from the |
|
664 | single underscore. These names are normally ommitted from the | |
665 | search. |
|
665 | search. | |
666 |
|
666 | |||
667 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
667 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
668 | these options is given, the default is read from your ipythonrc |
|
668 | these options is given, the default is read from your ipythonrc | |
669 | file. The option name which sets this value is |
|
669 | file. The option name which sets this value is | |
670 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
670 | 'wildcards_case_sensitive'. If this option is not specified in your | |
671 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
671 | ipythonrc file, IPython's internal default is to do a case sensitive | |
672 | search. |
|
672 | search. | |
673 |
|
673 | |||
674 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
674 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
675 | specifiy can be searched in any of the following namespaces: |
|
675 | specifiy can be searched in any of the following namespaces: | |
676 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
676 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
677 | 'builtin' and 'user' are the search defaults. Note that you should |
|
677 | 'builtin' and 'user' are the search defaults. Note that you should | |
678 | not use quotes when specifying namespaces. |
|
678 | not use quotes when specifying namespaces. | |
679 |
|
679 | |||
680 | 'Builtin' contains the python module builtin, 'user' contains all |
|
680 | 'Builtin' contains the python module builtin, 'user' contains all | |
681 | user data, 'alias' only contain the shell aliases and no python |
|
681 | user data, 'alias' only contain the shell aliases and no python | |
682 | objects, 'internal' contains objects used by IPython. The |
|
682 | objects, 'internal' contains objects used by IPython. The | |
683 | 'user_global' namespace is only used by embedded IPython instances, |
|
683 | 'user_global' namespace is only used by embedded IPython instances, | |
684 | and it contains module-level globals. You can add namespaces to the |
|
684 | and it contains module-level globals. You can add namespaces to the | |
685 | search with -s or exclude them with -e (these options can be given |
|
685 | search with -s or exclude them with -e (these options can be given | |
686 | more than once). |
|
686 | more than once). | |
687 |
|
687 | |||
688 | Examples: |
|
688 | Examples: | |
689 |
|
689 | |||
690 | %psearch a* -> objects beginning with an a |
|
690 | %psearch a* -> objects beginning with an a | |
691 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
691 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
692 | %psearch a* function -> all functions beginning with an a |
|
692 | %psearch a* function -> all functions beginning with an a | |
693 | %psearch re.e* -> objects beginning with an e in module re |
|
693 | %psearch re.e* -> objects beginning with an e in module re | |
694 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
694 | %psearch r*.e* -> objects that start with e in modules starting in r | |
695 | %psearch r*.* string -> all strings in modules beginning with r |
|
695 | %psearch r*.* string -> all strings in modules beginning with r | |
696 |
|
696 | |||
697 | Case sensitve search: |
|
697 | Case sensitve search: | |
698 |
|
698 | |||
699 | %psearch -c a* list all object beginning with lower case a |
|
699 | %psearch -c a* list all object beginning with lower case a | |
700 |
|
700 | |||
701 | Show objects beginning with a single _: |
|
701 | Show objects beginning with a single _: | |
702 |
|
702 | |||
703 | %psearch -a _* list objects beginning with a single underscore""" |
|
703 | %psearch -a _* list objects beginning with a single underscore""" | |
704 | try: |
|
704 | try: | |
705 | parameter_s = parameter_s.encode('ascii') |
|
705 | parameter_s = parameter_s.encode('ascii') | |
706 | except UnicodeEncodeError: |
|
706 | except UnicodeEncodeError: | |
707 | print 'Python identifiers can only contain ascii characters.' |
|
707 | print 'Python identifiers can only contain ascii characters.' | |
708 | return |
|
708 | return | |
709 |
|
709 | |||
710 | # default namespaces to be searched |
|
710 | # default namespaces to be searched | |
711 | def_search = ['user','builtin'] |
|
711 | def_search = ['user','builtin'] | |
712 |
|
712 | |||
713 | # Process options/args |
|
713 | # Process options/args | |
714 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
714 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
715 | opt = opts.get |
|
715 | opt = opts.get | |
716 | shell = self.shell |
|
716 | shell = self.shell | |
717 | psearch = shell.inspector.psearch |
|
717 | psearch = shell.inspector.psearch | |
718 |
|
718 | |||
719 | # select case options |
|
719 | # select case options | |
720 | if opts.has_key('i'): |
|
720 | if opts.has_key('i'): | |
721 | ignore_case = True |
|
721 | ignore_case = True | |
722 | elif opts.has_key('c'): |
|
722 | elif opts.has_key('c'): | |
723 | ignore_case = False |
|
723 | ignore_case = False | |
724 | else: |
|
724 | else: | |
725 | ignore_case = not shell.wildcards_case_sensitive |
|
725 | ignore_case = not shell.wildcards_case_sensitive | |
726 |
|
726 | |||
727 | # Build list of namespaces to search from user options |
|
727 | # Build list of namespaces to search from user options | |
728 | def_search.extend(opt('s',[])) |
|
728 | def_search.extend(opt('s',[])) | |
729 | ns_exclude = ns_exclude=opt('e',[]) |
|
729 | ns_exclude = ns_exclude=opt('e',[]) | |
730 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
730 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
731 |
|
731 | |||
732 | # Call the actual search |
|
732 | # Call the actual search | |
733 | try: |
|
733 | try: | |
734 | psearch(args,shell.ns_table,ns_search, |
|
734 | psearch(args,shell.ns_table,ns_search, | |
735 | show_all=opt('a'),ignore_case=ignore_case) |
|
735 | show_all=opt('a'),ignore_case=ignore_case) | |
736 | except: |
|
736 | except: | |
737 | shell.showtraceback() |
|
737 | shell.showtraceback() | |
738 |
|
738 | |||
739 | @testdec.skip_doctest |
|
739 | @testdec.skip_doctest | |
740 | def magic_who_ls(self, parameter_s=''): |
|
740 | def magic_who_ls(self, parameter_s=''): | |
741 | """Return a sorted list of all interactive variables. |
|
741 | """Return a sorted list of all interactive variables. | |
742 |
|
742 | |||
743 | If arguments are given, only variables of types matching these |
|
743 | If arguments are given, only variables of types matching these | |
744 | arguments are returned. |
|
744 | arguments are returned. | |
745 |
|
745 | |||
746 | Examples |
|
746 | Examples | |
747 | -------- |
|
747 | -------- | |
748 |
|
748 | |||
749 | Define two variables and list them with who_ls:: |
|
749 | Define two variables and list them with who_ls:: | |
750 |
|
750 | |||
751 | In [1]: alpha = 123 |
|
751 | In [1]: alpha = 123 | |
752 |
|
752 | |||
753 | In [2]: beta = 'test' |
|
753 | In [2]: beta = 'test' | |
754 |
|
754 | |||
755 | In [3]: %who_ls |
|
755 | In [3]: %who_ls | |
756 | Out[3]: ['alpha', 'beta'] |
|
756 | Out[3]: ['alpha', 'beta'] | |
757 |
|
757 | |||
758 | In [4]: %who_ls int |
|
758 | In [4]: %who_ls int | |
759 | Out[4]: ['alpha'] |
|
759 | Out[4]: ['alpha'] | |
760 |
|
760 | |||
761 | In [5]: %who_ls str |
|
761 | In [5]: %who_ls str | |
762 | Out[5]: ['beta'] |
|
762 | Out[5]: ['beta'] | |
763 | """ |
|
763 | """ | |
764 |
|
764 | |||
765 | user_ns = self.shell.user_ns |
|
765 | user_ns = self.shell.user_ns | |
766 | internal_ns = self.shell.internal_ns |
|
766 | internal_ns = self.shell.internal_ns | |
767 | user_ns_hidden = self.shell.user_ns_hidden |
|
767 | user_ns_hidden = self.shell.user_ns_hidden | |
768 | out = [ i for i in user_ns |
|
768 | out = [ i for i in user_ns | |
769 | if not i.startswith('_') \ |
|
769 | if not i.startswith('_') \ | |
770 | and not (i in internal_ns or i in user_ns_hidden) ] |
|
770 | and not (i in internal_ns or i in user_ns_hidden) ] | |
771 |
|
771 | |||
772 | typelist = parameter_s.split() |
|
772 | typelist = parameter_s.split() | |
773 | if typelist: |
|
773 | if typelist: | |
774 | typeset = set(typelist) |
|
774 | typeset = set(typelist) | |
775 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] |
|
775 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] | |
776 |
|
776 | |||
777 | out.sort() |
|
777 | out.sort() | |
778 | return out |
|
778 | return out | |
779 |
|
779 | |||
780 | @testdec.skip_doctest |
|
780 | @testdec.skip_doctest | |
781 | def magic_who(self, parameter_s=''): |
|
781 | def magic_who(self, parameter_s=''): | |
782 | """Print all interactive variables, with some minimal formatting. |
|
782 | """Print all interactive variables, with some minimal formatting. | |
783 |
|
783 | |||
784 | If any arguments are given, only variables whose type matches one of |
|
784 | If any arguments are given, only variables whose type matches one of | |
785 | these are printed. For example: |
|
785 | these are printed. For example: | |
786 |
|
786 | |||
787 | %who function str |
|
787 | %who function str | |
788 |
|
788 | |||
789 | will only list functions and strings, excluding all other types of |
|
789 | will only list functions and strings, excluding all other types of | |
790 | variables. To find the proper type names, simply use type(var) at a |
|
790 | variables. To find the proper type names, simply use type(var) at a | |
791 | command line to see how python prints type names. For example: |
|
791 | command line to see how python prints type names. For example: | |
792 |
|
792 | |||
793 | In [1]: type('hello')\\ |
|
793 | In [1]: type('hello')\\ | |
794 | Out[1]: <type 'str'> |
|
794 | Out[1]: <type 'str'> | |
795 |
|
795 | |||
796 | indicates that the type name for strings is 'str'. |
|
796 | indicates that the type name for strings is 'str'. | |
797 |
|
797 | |||
798 | %who always excludes executed names loaded through your configuration |
|
798 | %who always excludes executed names loaded through your configuration | |
799 | file and things which are internal to IPython. |
|
799 | file and things which are internal to IPython. | |
800 |
|
800 | |||
801 | This is deliberate, as typically you may load many modules and the |
|
801 | This is deliberate, as typically you may load many modules and the | |
802 | purpose of %who is to show you only what you've manually defined. |
|
802 | purpose of %who is to show you only what you've manually defined. | |
803 |
|
803 | |||
804 | Examples |
|
804 | Examples | |
805 | -------- |
|
805 | -------- | |
806 |
|
806 | |||
807 | Define two variables and list them with who:: |
|
807 | Define two variables and list them with who:: | |
808 |
|
808 | |||
809 | In [1]: alpha = 123 |
|
809 | In [1]: alpha = 123 | |
810 |
|
810 | |||
811 | In [2]: beta = 'test' |
|
811 | In [2]: beta = 'test' | |
812 |
|
812 | |||
813 | In [3]: %who |
|
813 | In [3]: %who | |
814 | alpha beta |
|
814 | alpha beta | |
815 |
|
815 | |||
816 | In [4]: %who int |
|
816 | In [4]: %who int | |
817 | alpha |
|
817 | alpha | |
818 |
|
818 | |||
819 | In [5]: %who str |
|
819 | In [5]: %who str | |
820 | beta |
|
820 | beta | |
821 | """ |
|
821 | """ | |
822 |
|
822 | |||
823 | varlist = self.magic_who_ls(parameter_s) |
|
823 | varlist = self.magic_who_ls(parameter_s) | |
824 | if not varlist: |
|
824 | if not varlist: | |
825 | if parameter_s: |
|
825 | if parameter_s: | |
826 | print 'No variables match your requested type.' |
|
826 | print 'No variables match your requested type.' | |
827 | else: |
|
827 | else: | |
828 | print 'Interactive namespace is empty.' |
|
828 | print 'Interactive namespace is empty.' | |
829 | return |
|
829 | return | |
830 |
|
830 | |||
831 | # if we have variables, move on... |
|
831 | # if we have variables, move on... | |
832 | count = 0 |
|
832 | count = 0 | |
833 | for i in varlist: |
|
833 | for i in varlist: | |
834 | print i+'\t', |
|
834 | print i+'\t', | |
835 | count += 1 |
|
835 | count += 1 | |
836 | if count > 8: |
|
836 | if count > 8: | |
837 | count = 0 |
|
837 | count = 0 | |
838 |
|
838 | |||
839 |
|
839 | |||
840 |
|
840 | |||
841 | @testdec.skip_doctest |
|
841 | @testdec.skip_doctest | |
842 | def magic_whos(self, parameter_s=''): |
|
842 | def magic_whos(self, parameter_s=''): | |
843 | """Like %who, but gives some extra information about each variable. |
|
843 | """Like %who, but gives some extra information about each variable. | |
844 |
|
844 | |||
845 | The same type filtering of %who can be applied here. |
|
845 | The same type filtering of %who can be applied here. | |
846 |
|
846 | |||
847 | For all variables, the type is printed. Additionally it prints: |
|
847 | For all variables, the type is printed. Additionally it prints: | |
848 |
|
848 | |||
849 | - For {},[],(): their length. |
|
849 | - For {},[],(): their length. | |
850 |
|
850 | |||
851 | - For numpy and Numeric arrays, a summary with shape, number of |
|
851 | - For numpy and Numeric arrays, a summary with shape, number of | |
852 | elements, typecode and size in memory. |
|
852 | elements, typecode and size in memory. | |
853 |
|
853 | |||
854 | - Everything else: a string representation, snipping their middle if |
|
854 | - Everything else: a string representation, snipping their middle if | |
855 | too long. |
|
855 | too long. | |
856 |
|
856 | |||
857 | Examples |
|
857 | Examples | |
858 | -------- |
|
858 | -------- | |
859 |
|
859 | |||
860 | Define two variables and list them with whos:: |
|
860 | Define two variables and list them with whos:: | |
861 |
|
861 | |||
862 | In [1]: alpha = 123 |
|
862 | In [1]: alpha = 123 | |
863 |
|
863 | |||
864 | In [2]: beta = 'test' |
|
864 | In [2]: beta = 'test' | |
865 |
|
865 | |||
866 | In [3]: %whos |
|
866 | In [3]: %whos | |
867 | Variable Type Data/Info |
|
867 | Variable Type Data/Info | |
868 | -------------------------------- |
|
868 | -------------------------------- | |
869 | alpha int 123 |
|
869 | alpha int 123 | |
870 | beta str test |
|
870 | beta str test | |
871 | """ |
|
871 | """ | |
872 |
|
872 | |||
873 | varnames = self.magic_who_ls(parameter_s) |
|
873 | varnames = self.magic_who_ls(parameter_s) | |
874 | if not varnames: |
|
874 | if not varnames: | |
875 | if parameter_s: |
|
875 | if parameter_s: | |
876 | print 'No variables match your requested type.' |
|
876 | print 'No variables match your requested type.' | |
877 | else: |
|
877 | else: | |
878 | print 'Interactive namespace is empty.' |
|
878 | print 'Interactive namespace is empty.' | |
879 | return |
|
879 | return | |
880 |
|
880 | |||
881 | # if we have variables, move on... |
|
881 | # if we have variables, move on... | |
882 |
|
882 | |||
883 | # for these types, show len() instead of data: |
|
883 | # for these types, show len() instead of data: | |
884 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
884 | seq_types = [types.DictType,types.ListType,types.TupleType] | |
885 |
|
885 | |||
886 | # for numpy/Numeric arrays, display summary info |
|
886 | # for numpy/Numeric arrays, display summary info | |
887 | try: |
|
887 | try: | |
888 | import numpy |
|
888 | import numpy | |
889 | except ImportError: |
|
889 | except ImportError: | |
890 | ndarray_type = None |
|
890 | ndarray_type = None | |
891 | else: |
|
891 | else: | |
892 | ndarray_type = numpy.ndarray.__name__ |
|
892 | ndarray_type = numpy.ndarray.__name__ | |
893 | try: |
|
893 | try: | |
894 | import Numeric |
|
894 | import Numeric | |
895 | except ImportError: |
|
895 | except ImportError: | |
896 | array_type = None |
|
896 | array_type = None | |
897 | else: |
|
897 | else: | |
898 | array_type = Numeric.ArrayType.__name__ |
|
898 | array_type = Numeric.ArrayType.__name__ | |
899 |
|
899 | |||
900 | # Find all variable names and types so we can figure out column sizes |
|
900 | # Find all variable names and types so we can figure out column sizes | |
901 | def get_vars(i): |
|
901 | def get_vars(i): | |
902 | return self.shell.user_ns[i] |
|
902 | return self.shell.user_ns[i] | |
903 |
|
903 | |||
904 | # some types are well known and can be shorter |
|
904 | # some types are well known and can be shorter | |
905 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
905 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} | |
906 | def type_name(v): |
|
906 | def type_name(v): | |
907 | tn = type(v).__name__ |
|
907 | tn = type(v).__name__ | |
908 | return abbrevs.get(tn,tn) |
|
908 | return abbrevs.get(tn,tn) | |
909 |
|
909 | |||
910 | varlist = map(get_vars,varnames) |
|
910 | varlist = map(get_vars,varnames) | |
911 |
|
911 | |||
912 | typelist = [] |
|
912 | typelist = [] | |
913 | for vv in varlist: |
|
913 | for vv in varlist: | |
914 | tt = type_name(vv) |
|
914 | tt = type_name(vv) | |
915 |
|
915 | |||
916 | if tt=='instance': |
|
916 | if tt=='instance': | |
917 | typelist.append( abbrevs.get(str(vv.__class__), |
|
917 | typelist.append( abbrevs.get(str(vv.__class__), | |
918 | str(vv.__class__))) |
|
918 | str(vv.__class__))) | |
919 | else: |
|
919 | else: | |
920 | typelist.append(tt) |
|
920 | typelist.append(tt) | |
921 |
|
921 | |||
922 | # column labels and # of spaces as separator |
|
922 | # column labels and # of spaces as separator | |
923 | varlabel = 'Variable' |
|
923 | varlabel = 'Variable' | |
924 | typelabel = 'Type' |
|
924 | typelabel = 'Type' | |
925 | datalabel = 'Data/Info' |
|
925 | datalabel = 'Data/Info' | |
926 | colsep = 3 |
|
926 | colsep = 3 | |
927 | # variable format strings |
|
927 | # variable format strings | |
928 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
928 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" | |
929 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
929 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' | |
930 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
930 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
931 | # find the size of the columns to format the output nicely |
|
931 | # find the size of the columns to format the output nicely | |
932 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
932 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
933 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
933 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
934 | # table header |
|
934 | # table header | |
935 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
935 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
936 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
936 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
937 | # and the table itself |
|
937 | # and the table itself | |
938 | kb = 1024 |
|
938 | kb = 1024 | |
939 | Mb = 1048576 # kb**2 |
|
939 | Mb = 1048576 # kb**2 | |
940 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
940 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
941 | print itpl(vformat), |
|
941 | print itpl(vformat), | |
942 | if vtype in seq_types: |
|
942 | if vtype in seq_types: | |
943 | print len(var) |
|
943 | print len(var) | |
944 | elif vtype in [array_type,ndarray_type]: |
|
944 | elif vtype in [array_type,ndarray_type]: | |
945 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
945 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
946 | if vtype==ndarray_type: |
|
946 | if vtype==ndarray_type: | |
947 | # numpy |
|
947 | # numpy | |
948 | vsize = var.size |
|
948 | vsize = var.size | |
949 | vbytes = vsize*var.itemsize |
|
949 | vbytes = vsize*var.itemsize | |
950 | vdtype = var.dtype |
|
950 | vdtype = var.dtype | |
951 | else: |
|
951 | else: | |
952 | # Numeric |
|
952 | # Numeric | |
953 | vsize = Numeric.size(var) |
|
953 | vsize = Numeric.size(var) | |
954 | vbytes = vsize*var.itemsize() |
|
954 | vbytes = vsize*var.itemsize() | |
955 | vdtype = var.typecode() |
|
955 | vdtype = var.typecode() | |
956 |
|
956 | |||
957 | if vbytes < 100000: |
|
957 | if vbytes < 100000: | |
958 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
958 | print aformat % (vshape,vsize,vdtype,vbytes) | |
959 | else: |
|
959 | else: | |
960 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
960 | print aformat % (vshape,vsize,vdtype,vbytes), | |
961 | if vbytes < Mb: |
|
961 | if vbytes < Mb: | |
962 | print '(%s kb)' % (vbytes/kb,) |
|
962 | print '(%s kb)' % (vbytes/kb,) | |
963 | else: |
|
963 | else: | |
964 | print '(%s Mb)' % (vbytes/Mb,) |
|
964 | print '(%s Mb)' % (vbytes/Mb,) | |
965 | else: |
|
965 | else: | |
966 | try: |
|
966 | try: | |
967 | vstr = str(var) |
|
967 | vstr = str(var) | |
968 | except UnicodeEncodeError: |
|
968 | except UnicodeEncodeError: | |
969 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
969 | vstr = unicode(var).encode(sys.getdefaultencoding(), | |
970 | 'backslashreplace') |
|
970 | 'backslashreplace') | |
971 | vstr = vstr.replace('\n','\\n') |
|
971 | vstr = vstr.replace('\n','\\n') | |
972 | if len(vstr) < 50: |
|
972 | if len(vstr) < 50: | |
973 | print vstr |
|
973 | print vstr | |
974 | else: |
|
974 | else: | |
975 | printpl(vfmt_short) |
|
975 | printpl(vfmt_short) | |
976 |
|
976 | |||
977 | def magic_reset(self, parameter_s=''): |
|
977 | def magic_reset(self, parameter_s=''): | |
978 | """Resets the namespace by removing all names defined by the user. |
|
978 | """Resets the namespace by removing all names defined by the user. | |
979 |
|
979 | |||
980 | Input/Output history are left around in case you need them. |
|
980 | Input/Output history are left around in case you need them. | |
981 |
|
981 | |||
982 | Parameters |
|
982 | Parameters | |
983 | ---------- |
|
983 | ---------- | |
984 | -y : force reset without asking for confirmation. |
|
984 | -y : force reset without asking for confirmation. | |
985 |
|
985 | |||
986 | Examples |
|
986 | Examples | |
987 | -------- |
|
987 | -------- | |
988 | In [6]: a = 1 |
|
988 | In [6]: a = 1 | |
989 |
|
989 | |||
990 | In [7]: a |
|
990 | In [7]: a | |
991 | Out[7]: 1 |
|
991 | Out[7]: 1 | |
992 |
|
992 | |||
993 | In [8]: 'a' in _ip.user_ns |
|
993 | In [8]: 'a' in _ip.user_ns | |
994 | Out[8]: True |
|
994 | Out[8]: True | |
995 |
|
995 | |||
996 | In [9]: %reset -f |
|
996 | In [9]: %reset -f | |
997 |
|
997 | |||
998 | In [10]: 'a' in _ip.user_ns |
|
998 | In [10]: 'a' in _ip.user_ns | |
999 | Out[10]: False |
|
999 | Out[10]: False | |
1000 | """ |
|
1000 | """ | |
1001 |
|
1001 | |||
1002 | if parameter_s == '-f': |
|
1002 | if parameter_s == '-f': | |
1003 | ans = True |
|
1003 | ans = True | |
1004 | else: |
|
1004 | else: | |
1005 | ans = self.shell.ask_yes_no( |
|
1005 | ans = self.shell.ask_yes_no( | |
1006 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1006 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
1007 | if not ans: |
|
1007 | if not ans: | |
1008 | print 'Nothing done.' |
|
1008 | print 'Nothing done.' | |
1009 | return |
|
1009 | return | |
1010 | user_ns = self.shell.user_ns |
|
1010 | user_ns = self.shell.user_ns | |
1011 | for i in self.magic_who_ls(): |
|
1011 | for i in self.magic_who_ls(): | |
1012 | del(user_ns[i]) |
|
1012 | del(user_ns[i]) | |
1013 |
|
1013 | |||
1014 | # Also flush the private list of module references kept for script |
|
1014 | # Also flush the private list of module references kept for script | |
1015 | # execution protection |
|
1015 | # execution protection | |
1016 | self.shell.clear_main_mod_cache() |
|
1016 | self.shell.clear_main_mod_cache() | |
1017 |
|
1017 | |||
1018 | def magic_reset_selective(self, parameter_s=''): |
|
1018 | def magic_reset_selective(self, parameter_s=''): | |
1019 | """Resets the namespace by removing names defined by the user. |
|
1019 | """Resets the namespace by removing names defined by the user. | |
1020 |
|
1020 | |||
1021 | Input/Output history are left around in case you need them. |
|
1021 | Input/Output history are left around in case you need them. | |
1022 |
|
1022 | |||
1023 | %reset_selective [-f] regex |
|
1023 | %reset_selective [-f] regex | |
1024 |
|
1024 | |||
1025 | No action is taken if regex is not included |
|
1025 | No action is taken if regex is not included | |
1026 |
|
1026 | |||
1027 | Options |
|
1027 | Options | |
1028 | -f : force reset without asking for confirmation. |
|
1028 | -f : force reset without asking for confirmation. | |
1029 |
|
1029 | |||
1030 | Examples |
|
1030 | Examples | |
1031 | -------- |
|
1031 | -------- | |
1032 |
|
1032 | |||
1033 | We first fully reset the namespace so your output looks identical to |
|
1033 | We first fully reset the namespace so your output looks identical to | |
1034 | this example for pedagogical reasons; in practice you do not need a |
|
1034 | this example for pedagogical reasons; in practice you do not need a | |
1035 | full reset. |
|
1035 | full reset. | |
1036 |
|
1036 | |||
1037 | In [1]: %reset -f |
|
1037 | In [1]: %reset -f | |
1038 |
|
1038 | |||
1039 | Now, with a clean namespace we can make a few variables and use |
|
1039 | Now, with a clean namespace we can make a few variables and use | |
1040 | %reset_selective to only delete names that match our regexp: |
|
1040 | %reset_selective to only delete names that match our regexp: | |
1041 |
|
1041 | |||
1042 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 |
|
1042 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 | |
1043 |
|
1043 | |||
1044 | In [3]: who_ls |
|
1044 | In [3]: who_ls | |
1045 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] |
|
1045 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] | |
1046 |
|
1046 | |||
1047 | In [4]: %reset_selective -f b[2-3]m |
|
1047 | In [4]: %reset_selective -f b[2-3]m | |
1048 |
|
1048 | |||
1049 | In [5]: who_ls |
|
1049 | In [5]: who_ls | |
1050 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
1050 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
1051 |
|
1051 | |||
1052 | In [6]: %reset_selective -f d |
|
1052 | In [6]: %reset_selective -f d | |
1053 |
|
1053 | |||
1054 | In [7]: who_ls |
|
1054 | In [7]: who_ls | |
1055 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
1055 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
1056 |
|
1056 | |||
1057 | In [8]: %reset_selective -f c |
|
1057 | In [8]: %reset_selective -f c | |
1058 |
|
1058 | |||
1059 | In [9]: who_ls |
|
1059 | In [9]: who_ls | |
1060 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] |
|
1060 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] | |
1061 |
|
1061 | |||
1062 | In [10]: %reset_selective -f b |
|
1062 | In [10]: %reset_selective -f b | |
1063 |
|
1063 | |||
1064 | In [11]: who_ls |
|
1064 | In [11]: who_ls | |
1065 | Out[11]: ['a'] |
|
1065 | Out[11]: ['a'] | |
1066 | """ |
|
1066 | """ | |
1067 |
|
1067 | |||
1068 | opts, regex = self.parse_options(parameter_s,'f') |
|
1068 | opts, regex = self.parse_options(parameter_s,'f') | |
1069 |
|
1069 | |||
1070 | if opts.has_key('f'): |
|
1070 | if opts.has_key('f'): | |
1071 | ans = True |
|
1071 | ans = True | |
1072 | else: |
|
1072 | else: | |
1073 | ans = self.shell.ask_yes_no( |
|
1073 | ans = self.shell.ask_yes_no( | |
1074 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1074 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
1075 | if not ans: |
|
1075 | if not ans: | |
1076 | print 'Nothing done.' |
|
1076 | print 'Nothing done.' | |
1077 | return |
|
1077 | return | |
1078 | user_ns = self.shell.user_ns |
|
1078 | user_ns = self.shell.user_ns | |
1079 | if not regex: |
|
1079 | if not regex: | |
1080 | print 'No regex pattern specified. Nothing done.' |
|
1080 | print 'No regex pattern specified. Nothing done.' | |
1081 | return |
|
1081 | return | |
1082 | else: |
|
1082 | else: | |
1083 | try: |
|
1083 | try: | |
1084 | m = re.compile(regex) |
|
1084 | m = re.compile(regex) | |
1085 | except TypeError: |
|
1085 | except TypeError: | |
1086 | raise TypeError('regex must be a string or compiled pattern') |
|
1086 | raise TypeError('regex must be a string or compiled pattern') | |
1087 | for i in self.magic_who_ls(): |
|
1087 | for i in self.magic_who_ls(): | |
1088 | if m.search(i): |
|
1088 | if m.search(i): | |
1089 | del(user_ns[i]) |
|
1089 | del(user_ns[i]) | |
1090 |
|
1090 | |||
1091 | def magic_logstart(self,parameter_s=''): |
|
1091 | def magic_logstart(self,parameter_s=''): | |
1092 | """Start logging anywhere in a session. |
|
1092 | """Start logging anywhere in a session. | |
1093 |
|
1093 | |||
1094 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1094 | %logstart [-o|-r|-t] [log_name [log_mode]] | |
1095 |
|
1095 | |||
1096 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1096 | If no name is given, it defaults to a file named 'ipython_log.py' in your | |
1097 | current directory, in 'rotate' mode (see below). |
|
1097 | current directory, in 'rotate' mode (see below). | |
1098 |
|
1098 | |||
1099 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1099 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
1100 | history up to that point and then continues logging. |
|
1100 | history up to that point and then continues logging. | |
1101 |
|
1101 | |||
1102 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1102 | %logstart takes a second optional parameter: logging mode. This can be one | |
1103 | of (note that the modes are given unquoted):\\ |
|
1103 | of (note that the modes are given unquoted):\\ | |
1104 | append: well, that says it.\\ |
|
1104 | append: well, that says it.\\ | |
1105 | backup: rename (if exists) to name~ and start name.\\ |
|
1105 | backup: rename (if exists) to name~ and start name.\\ | |
1106 | global: single logfile in your home dir, appended to.\\ |
|
1106 | global: single logfile in your home dir, appended to.\\ | |
1107 | over : overwrite existing log.\\ |
|
1107 | over : overwrite existing log.\\ | |
1108 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1108 | rotate: create rotating logs name.1~, name.2~, etc. | |
1109 |
|
1109 | |||
1110 | Options: |
|
1110 | Options: | |
1111 |
|
1111 | |||
1112 | -o: log also IPython's output. In this mode, all commands which |
|
1112 | -o: log also IPython's output. In this mode, all commands which | |
1113 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1113 | generate an Out[NN] prompt are recorded to the logfile, right after | |
1114 | their corresponding input line. The output lines are always |
|
1114 | their corresponding input line. The output lines are always | |
1115 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1115 | prepended with a '#[Out]# ' marker, so that the log remains valid | |
1116 | Python code. |
|
1116 | Python code. | |
1117 |
|
1117 | |||
1118 | Since this marker is always the same, filtering only the output from |
|
1118 | Since this marker is always the same, filtering only the output from | |
1119 | a log is very easy, using for example a simple awk call: |
|
1119 | a log is very easy, using for example a simple awk call: | |
1120 |
|
1120 | |||
1121 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1121 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py | |
1122 |
|
1122 | |||
1123 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1123 | -r: log 'raw' input. Normally, IPython's logs contain the processed | |
1124 | input, so that user lines are logged in their final form, converted |
|
1124 | input, so that user lines are logged in their final form, converted | |
1125 | into valid Python. For example, %Exit is logged as |
|
1125 | into valid Python. For example, %Exit is logged as | |
1126 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1126 | '_ip.magic("Exit"). If the -r flag is given, all input is logged | |
1127 | exactly as typed, with no transformations applied. |
|
1127 | exactly as typed, with no transformations applied. | |
1128 |
|
1128 | |||
1129 | -t: put timestamps before each input line logged (these are put in |
|
1129 | -t: put timestamps before each input line logged (these are put in | |
1130 | comments).""" |
|
1130 | comments).""" | |
1131 |
|
1131 | |||
1132 | opts,par = self.parse_options(parameter_s,'ort') |
|
1132 | opts,par = self.parse_options(parameter_s,'ort') | |
1133 | log_output = 'o' in opts |
|
1133 | log_output = 'o' in opts | |
1134 | log_raw_input = 'r' in opts |
|
1134 | log_raw_input = 'r' in opts | |
1135 | timestamp = 't' in opts |
|
1135 | timestamp = 't' in opts | |
1136 |
|
1136 | |||
1137 | logger = self.shell.logger |
|
1137 | logger = self.shell.logger | |
1138 |
|
1138 | |||
1139 | # if no args are given, the defaults set in the logger constructor by |
|
1139 | # if no args are given, the defaults set in the logger constructor by | |
1140 | # ipytohn remain valid |
|
1140 | # ipytohn remain valid | |
1141 | if par: |
|
1141 | if par: | |
1142 | try: |
|
1142 | try: | |
1143 | logfname,logmode = par.split() |
|
1143 | logfname,logmode = par.split() | |
1144 | except: |
|
1144 | except: | |
1145 | logfname = par |
|
1145 | logfname = par | |
1146 | logmode = 'backup' |
|
1146 | logmode = 'backup' | |
1147 | else: |
|
1147 | else: | |
1148 | logfname = logger.logfname |
|
1148 | logfname = logger.logfname | |
1149 | logmode = logger.logmode |
|
1149 | logmode = logger.logmode | |
1150 | # put logfname into rc struct as if it had been called on the command |
|
1150 | # put logfname into rc struct as if it had been called on the command | |
1151 | # line, so it ends up saved in the log header Save it in case we need |
|
1151 | # line, so it ends up saved in the log header Save it in case we need | |
1152 | # to restore it... |
|
1152 | # to restore it... | |
1153 | old_logfile = self.shell.logfile |
|
1153 | old_logfile = self.shell.logfile | |
1154 | if logfname: |
|
1154 | if logfname: | |
1155 | logfname = os.path.expanduser(logfname) |
|
1155 | logfname = os.path.expanduser(logfname) | |
1156 | self.shell.logfile = logfname |
|
1156 | self.shell.logfile = logfname | |
1157 |
|
1157 | |||
1158 | loghead = '# IPython log file\n\n' |
|
1158 | loghead = '# IPython log file\n\n' | |
1159 | try: |
|
1159 | try: | |
1160 | started = logger.logstart(logfname,loghead,logmode, |
|
1160 | started = logger.logstart(logfname,loghead,logmode, | |
1161 | log_output,timestamp,log_raw_input) |
|
1161 | log_output,timestamp,log_raw_input) | |
1162 | except: |
|
1162 | except: | |
1163 | self.shell.logfile = old_logfile |
|
1163 | self.shell.logfile = old_logfile | |
1164 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1164 | warn("Couldn't start log: %s" % sys.exc_info()[1]) | |
1165 | else: |
|
1165 | else: | |
1166 | # log input history up to this point, optionally interleaving |
|
1166 | # log input history up to this point, optionally interleaving | |
1167 | # output if requested |
|
1167 | # output if requested | |
1168 |
|
1168 | |||
1169 | if timestamp: |
|
1169 | if timestamp: | |
1170 | # disable timestamping for the previous history, since we've |
|
1170 | # disable timestamping for the previous history, since we've | |
1171 | # lost those already (no time machine here). |
|
1171 | # lost those already (no time machine here). | |
1172 | logger.timestamp = False |
|
1172 | logger.timestamp = False | |
1173 |
|
1173 | |||
1174 | if log_raw_input: |
|
1174 | if log_raw_input: | |
1175 | input_hist = self.shell.history_manager.input_hist_raw |
|
1175 | input_hist = self.shell.history_manager.input_hist_raw | |
1176 | else: |
|
1176 | else: | |
1177 | input_hist = self.shell.history_manager.input_hist_parsed |
|
1177 | input_hist = self.shell.history_manager.input_hist_parsed | |
1178 |
|
1178 | |||
1179 | if log_output: |
|
1179 | if log_output: | |
1180 | log_write = logger.log_write |
|
1180 | log_write = logger.log_write | |
1181 | output_hist = self.shell.history_manager.output_hist |
|
1181 | output_hist = self.shell.history_manager.output_hist | |
1182 | for n in range(1,len(input_hist)-1): |
|
1182 | for n in range(1,len(input_hist)-1): | |
1183 | log_write(input_hist[n].rstrip()) |
|
1183 | log_write(input_hist[n].rstrip()) | |
1184 | if n in output_hist: |
|
1184 | if n in output_hist: | |
1185 | log_write(repr(output_hist[n]),'output') |
|
1185 | log_write(repr(output_hist[n]),'output') | |
1186 | else: |
|
1186 | else: | |
1187 | logger.log_write(''.join(input_hist[1:])) |
|
1187 | logger.log_write(''.join(input_hist[1:])) | |
1188 | if timestamp: |
|
1188 | if timestamp: | |
1189 | # re-enable timestamping |
|
1189 | # re-enable timestamping | |
1190 | logger.timestamp = True |
|
1190 | logger.timestamp = True | |
1191 |
|
1191 | |||
1192 | print ('Activating auto-logging. ' |
|
1192 | print ('Activating auto-logging. ' | |
1193 | 'Current session state plus future input saved.') |
|
1193 | 'Current session state plus future input saved.') | |
1194 | logger.logstate() |
|
1194 | logger.logstate() | |
1195 |
|
1195 | |||
1196 | def magic_logstop(self,parameter_s=''): |
|
1196 | def magic_logstop(self,parameter_s=''): | |
1197 | """Fully stop logging and close log file. |
|
1197 | """Fully stop logging and close log file. | |
1198 |
|
1198 | |||
1199 | In order to start logging again, a new %logstart call needs to be made, |
|
1199 | In order to start logging again, a new %logstart call needs to be made, | |
1200 | possibly (though not necessarily) with a new filename, mode and other |
|
1200 | possibly (though not necessarily) with a new filename, mode and other | |
1201 | options.""" |
|
1201 | options.""" | |
1202 | self.logger.logstop() |
|
1202 | self.logger.logstop() | |
1203 |
|
1203 | |||
1204 | def magic_logoff(self,parameter_s=''): |
|
1204 | def magic_logoff(self,parameter_s=''): | |
1205 | """Temporarily stop logging. |
|
1205 | """Temporarily stop logging. | |
1206 |
|
1206 | |||
1207 | You must have previously started logging.""" |
|
1207 | You must have previously started logging.""" | |
1208 | self.shell.logger.switch_log(0) |
|
1208 | self.shell.logger.switch_log(0) | |
1209 |
|
1209 | |||
1210 | def magic_logon(self,parameter_s=''): |
|
1210 | def magic_logon(self,parameter_s=''): | |
1211 | """Restart logging. |
|
1211 | """Restart logging. | |
1212 |
|
1212 | |||
1213 | This function is for restarting logging which you've temporarily |
|
1213 | This function is for restarting logging which you've temporarily | |
1214 | stopped with %logoff. For starting logging for the first time, you |
|
1214 | stopped with %logoff. For starting logging for the first time, you | |
1215 | must use the %logstart function, which allows you to specify an |
|
1215 | must use the %logstart function, which allows you to specify an | |
1216 | optional log filename.""" |
|
1216 | optional log filename.""" | |
1217 |
|
1217 | |||
1218 | self.shell.logger.switch_log(1) |
|
1218 | self.shell.logger.switch_log(1) | |
1219 |
|
1219 | |||
1220 | def magic_logstate(self,parameter_s=''): |
|
1220 | def magic_logstate(self,parameter_s=''): | |
1221 | """Print the status of the logging system.""" |
|
1221 | """Print the status of the logging system.""" | |
1222 |
|
1222 | |||
1223 | self.shell.logger.logstate() |
|
1223 | self.shell.logger.logstate() | |
1224 |
|
1224 | |||
1225 | def magic_pdb(self, parameter_s=''): |
|
1225 | def magic_pdb(self, parameter_s=''): | |
1226 | """Control the automatic calling of the pdb interactive debugger. |
|
1226 | """Control the automatic calling of the pdb interactive debugger. | |
1227 |
|
1227 | |||
1228 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1228 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
1229 | argument it works as a toggle. |
|
1229 | argument it works as a toggle. | |
1230 |
|
1230 | |||
1231 | When an exception is triggered, IPython can optionally call the |
|
1231 | When an exception is triggered, IPython can optionally call the | |
1232 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1232 | interactive pdb debugger after the traceback printout. %pdb toggles | |
1233 | this feature on and off. |
|
1233 | this feature on and off. | |
1234 |
|
1234 | |||
1235 | The initial state of this feature is set in your ipythonrc |
|
1235 | The initial state of this feature is set in your ipythonrc | |
1236 | configuration file (the variable is called 'pdb'). |
|
1236 | configuration file (the variable is called 'pdb'). | |
1237 |
|
1237 | |||
1238 | If you want to just activate the debugger AFTER an exception has fired, |
|
1238 | If you want to just activate the debugger AFTER an exception has fired, | |
1239 | without having to type '%pdb on' and rerunning your code, you can use |
|
1239 | without having to type '%pdb on' and rerunning your code, you can use | |
1240 | the %debug magic.""" |
|
1240 | the %debug magic.""" | |
1241 |
|
1241 | |||
1242 | par = parameter_s.strip().lower() |
|
1242 | par = parameter_s.strip().lower() | |
1243 |
|
1243 | |||
1244 | if par: |
|
1244 | if par: | |
1245 | try: |
|
1245 | try: | |
1246 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1246 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
1247 | except KeyError: |
|
1247 | except KeyError: | |
1248 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1248 | print ('Incorrect argument. Use on/1, off/0, ' | |
1249 | 'or nothing for a toggle.') |
|
1249 | 'or nothing for a toggle.') | |
1250 | return |
|
1250 | return | |
1251 | else: |
|
1251 | else: | |
1252 | # toggle |
|
1252 | # toggle | |
1253 | new_pdb = not self.shell.call_pdb |
|
1253 | new_pdb = not self.shell.call_pdb | |
1254 |
|
1254 | |||
1255 | # set on the shell |
|
1255 | # set on the shell | |
1256 | self.shell.call_pdb = new_pdb |
|
1256 | self.shell.call_pdb = new_pdb | |
1257 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1257 | print 'Automatic pdb calling has been turned',on_off(new_pdb) | |
1258 |
|
1258 | |||
1259 | def magic_debug(self, parameter_s=''): |
|
1259 | def magic_debug(self, parameter_s=''): | |
1260 | """Activate the interactive debugger in post-mortem mode. |
|
1260 | """Activate the interactive debugger in post-mortem mode. | |
1261 |
|
1261 | |||
1262 | If an exception has just occurred, this lets you inspect its stack |
|
1262 | If an exception has just occurred, this lets you inspect its stack | |
1263 | frames interactively. Note that this will always work only on the last |
|
1263 | frames interactively. Note that this will always work only on the last | |
1264 | traceback that occurred, so you must call this quickly after an |
|
1264 | traceback that occurred, so you must call this quickly after an | |
1265 | exception that you wish to inspect has fired, because if another one |
|
1265 | exception that you wish to inspect has fired, because if another one | |
1266 | occurs, it clobbers the previous one. |
|
1266 | occurs, it clobbers the previous one. | |
1267 |
|
1267 | |||
1268 | If you want IPython to automatically do this on every exception, see |
|
1268 | If you want IPython to automatically do this on every exception, see | |
1269 | the %pdb magic for more details. |
|
1269 | the %pdb magic for more details. | |
1270 | """ |
|
1270 | """ | |
1271 | self.shell.debugger(force=True) |
|
1271 | self.shell.debugger(force=True) | |
1272 |
|
1272 | |||
1273 | @testdec.skip_doctest |
|
1273 | @testdec.skip_doctest | |
1274 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1274 | def magic_prun(self, parameter_s ='',user_mode=1, | |
1275 | opts=None,arg_lst=None,prog_ns=None): |
|
1275 | opts=None,arg_lst=None,prog_ns=None): | |
1276 |
|
1276 | |||
1277 | """Run a statement through the python code profiler. |
|
1277 | """Run a statement through the python code profiler. | |
1278 |
|
1278 | |||
1279 | Usage: |
|
1279 | Usage: | |
1280 | %prun [options] statement |
|
1280 | %prun [options] statement | |
1281 |
|
1281 | |||
1282 | The given statement (which doesn't require quote marks) is run via the |
|
1282 | The given statement (which doesn't require quote marks) is run via the | |
1283 | python profiler in a manner similar to the profile.run() function. |
|
1283 | python profiler in a manner similar to the profile.run() function. | |
1284 | Namespaces are internally managed to work correctly; profile.run |
|
1284 | Namespaces are internally managed to work correctly; profile.run | |
1285 | cannot be used in IPython because it makes certain assumptions about |
|
1285 | cannot be used in IPython because it makes certain assumptions about | |
1286 | namespaces which do not hold under IPython. |
|
1286 | namespaces which do not hold under IPython. | |
1287 |
|
1287 | |||
1288 | Options: |
|
1288 | Options: | |
1289 |
|
1289 | |||
1290 | -l <limit>: you can place restrictions on what or how much of the |
|
1290 | -l <limit>: you can place restrictions on what or how much of the | |
1291 | profile gets printed. The limit value can be: |
|
1291 | profile gets printed. The limit value can be: | |
1292 |
|
1292 | |||
1293 | * A string: only information for function names containing this string |
|
1293 | * A string: only information for function names containing this string | |
1294 | is printed. |
|
1294 | is printed. | |
1295 |
|
1295 | |||
1296 | * An integer: only these many lines are printed. |
|
1296 | * An integer: only these many lines are printed. | |
1297 |
|
1297 | |||
1298 | * A float (between 0 and 1): this fraction of the report is printed |
|
1298 | * A float (between 0 and 1): this fraction of the report is printed | |
1299 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1299 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
1300 |
|
1300 | |||
1301 | You can combine several limits with repeated use of the option. For |
|
1301 | You can combine several limits with repeated use of the option. For | |
1302 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1302 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
1303 | information about class constructors. |
|
1303 | information about class constructors. | |
1304 |
|
1304 | |||
1305 | -r: return the pstats.Stats object generated by the profiling. This |
|
1305 | -r: return the pstats.Stats object generated by the profiling. This | |
1306 | object has all the information about the profile in it, and you can |
|
1306 | object has all the information about the profile in it, and you can | |
1307 | later use it for further analysis or in other functions. |
|
1307 | later use it for further analysis or in other functions. | |
1308 |
|
1308 | |||
1309 | -s <key>: sort profile by given key. You can provide more than one key |
|
1309 | -s <key>: sort profile by given key. You can provide more than one key | |
1310 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1310 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1311 | default sorting key is 'time'. |
|
1311 | default sorting key is 'time'. | |
1312 |
|
1312 | |||
1313 | The following is copied verbatim from the profile documentation |
|
1313 | The following is copied verbatim from the profile documentation | |
1314 | referenced below: |
|
1314 | referenced below: | |
1315 |
|
1315 | |||
1316 | When more than one key is provided, additional keys are used as |
|
1316 | When more than one key is provided, additional keys are used as | |
1317 | secondary criteria when the there is equality in all keys selected |
|
1317 | secondary criteria when the there is equality in all keys selected | |
1318 | before them. |
|
1318 | before them. | |
1319 |
|
1319 | |||
1320 | Abbreviations can be used for any key names, as long as the |
|
1320 | Abbreviations can be used for any key names, as long as the | |
1321 | abbreviation is unambiguous. The following are the keys currently |
|
1321 | abbreviation is unambiguous. The following are the keys currently | |
1322 | defined: |
|
1322 | defined: | |
1323 |
|
1323 | |||
1324 | Valid Arg Meaning |
|
1324 | Valid Arg Meaning | |
1325 | "calls" call count |
|
1325 | "calls" call count | |
1326 | "cumulative" cumulative time |
|
1326 | "cumulative" cumulative time | |
1327 | "file" file name |
|
1327 | "file" file name | |
1328 | "module" file name |
|
1328 | "module" file name | |
1329 | "pcalls" primitive call count |
|
1329 | "pcalls" primitive call count | |
1330 | "line" line number |
|
1330 | "line" line number | |
1331 | "name" function name |
|
1331 | "name" function name | |
1332 | "nfl" name/file/line |
|
1332 | "nfl" name/file/line | |
1333 | "stdname" standard name |
|
1333 | "stdname" standard name | |
1334 | "time" internal time |
|
1334 | "time" internal time | |
1335 |
|
1335 | |||
1336 | Note that all sorts on statistics are in descending order (placing |
|
1336 | Note that all sorts on statistics are in descending order (placing | |
1337 | most time consuming items first), where as name, file, and line number |
|
1337 | most time consuming items first), where as name, file, and line number | |
1338 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1338 | searches are in ascending order (i.e., alphabetical). The subtle | |
1339 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1339 | distinction between "nfl" and "stdname" is that the standard name is a | |
1340 | sort of the name as printed, which means that the embedded line |
|
1340 | sort of the name as printed, which means that the embedded line | |
1341 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1341 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1342 | would (if the file names were the same) appear in the string order |
|
1342 | would (if the file names were the same) appear in the string order | |
1343 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1343 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1344 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1344 | line numbers. In fact, sort_stats("nfl") is the same as | |
1345 | sort_stats("name", "file", "line"). |
|
1345 | sort_stats("name", "file", "line"). | |
1346 |
|
1346 | |||
1347 | -T <filename>: save profile results as shown on screen to a text |
|
1347 | -T <filename>: save profile results as shown on screen to a text | |
1348 | file. The profile is still shown on screen. |
|
1348 | file. The profile is still shown on screen. | |
1349 |
|
1349 | |||
1350 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1350 | -D <filename>: save (via dump_stats) profile statistics to given | |
1351 | filename. This data is in a format understod by the pstats module, and |
|
1351 | filename. This data is in a format understod by the pstats module, and | |
1352 | is generated by a call to the dump_stats() method of profile |
|
1352 | is generated by a call to the dump_stats() method of profile | |
1353 | objects. The profile is still shown on screen. |
|
1353 | objects. The profile is still shown on screen. | |
1354 |
|
1354 | |||
1355 | If you want to run complete programs under the profiler's control, use |
|
1355 | If you want to run complete programs under the profiler's control, use | |
1356 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1356 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1357 | contains profiler specific options as described here. |
|
1357 | contains profiler specific options as described here. | |
1358 |
|
1358 | |||
1359 | You can read the complete documentation for the profile module with:: |
|
1359 | You can read the complete documentation for the profile module with:: | |
1360 |
|
1360 | |||
1361 | In [1]: import profile; profile.help() |
|
1361 | In [1]: import profile; profile.help() | |
1362 | """ |
|
1362 | """ | |
1363 |
|
1363 | |||
1364 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1364 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1365 | # protect user quote marks |
|
1365 | # protect user quote marks | |
1366 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1366 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") | |
1367 |
|
1367 | |||
1368 | if user_mode: # regular user call |
|
1368 | if user_mode: # regular user call | |
1369 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1369 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', | |
1370 | list_all=1) |
|
1370 | list_all=1) | |
1371 | namespace = self.shell.user_ns |
|
1371 | namespace = self.shell.user_ns | |
1372 | else: # called to run a program by %run -p |
|
1372 | else: # called to run a program by %run -p | |
1373 | try: |
|
1373 | try: | |
1374 | filename = get_py_filename(arg_lst[0]) |
|
1374 | filename = get_py_filename(arg_lst[0]) | |
1375 | except IOError,msg: |
|
1375 | except IOError,msg: | |
1376 | error(msg) |
|
1376 | error(msg) | |
1377 | return |
|
1377 | return | |
1378 |
|
1378 | |||
1379 | arg_str = 'execfile(filename,prog_ns)' |
|
1379 | arg_str = 'execfile(filename,prog_ns)' | |
1380 | namespace = locals() |
|
1380 | namespace = locals() | |
1381 |
|
1381 | |||
1382 | opts.merge(opts_def) |
|
1382 | opts.merge(opts_def) | |
1383 |
|
1383 | |||
1384 | prof = profile.Profile() |
|
1384 | prof = profile.Profile() | |
1385 | try: |
|
1385 | try: | |
1386 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1386 | prof = prof.runctx(arg_str,namespace,namespace) | |
1387 | sys_exit = '' |
|
1387 | sys_exit = '' | |
1388 | except SystemExit: |
|
1388 | except SystemExit: | |
1389 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1389 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1390 |
|
1390 | |||
1391 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1391 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1392 |
|
1392 | |||
1393 | lims = opts.l |
|
1393 | lims = opts.l | |
1394 | if lims: |
|
1394 | if lims: | |
1395 | lims = [] # rebuild lims with ints/floats/strings |
|
1395 | lims = [] # rebuild lims with ints/floats/strings | |
1396 | for lim in opts.l: |
|
1396 | for lim in opts.l: | |
1397 | try: |
|
1397 | try: | |
1398 | lims.append(int(lim)) |
|
1398 | lims.append(int(lim)) | |
1399 | except ValueError: |
|
1399 | except ValueError: | |
1400 | try: |
|
1400 | try: | |
1401 | lims.append(float(lim)) |
|
1401 | lims.append(float(lim)) | |
1402 | except ValueError: |
|
1402 | except ValueError: | |
1403 | lims.append(lim) |
|
1403 | lims.append(lim) | |
1404 |
|
1404 | |||
1405 | # Trap output. |
|
1405 | # Trap output. | |
1406 | stdout_trap = StringIO() |
|
1406 | stdout_trap = StringIO() | |
1407 |
|
1407 | |||
1408 | if hasattr(stats,'stream'): |
|
1408 | if hasattr(stats,'stream'): | |
1409 | # In newer versions of python, the stats object has a 'stream' |
|
1409 | # In newer versions of python, the stats object has a 'stream' | |
1410 | # attribute to write into. |
|
1410 | # attribute to write into. | |
1411 | stats.stream = stdout_trap |
|
1411 | stats.stream = stdout_trap | |
1412 | stats.print_stats(*lims) |
|
1412 | stats.print_stats(*lims) | |
1413 | else: |
|
1413 | else: | |
1414 | # For older versions, we manually redirect stdout during printing |
|
1414 | # For older versions, we manually redirect stdout during printing | |
1415 | sys_stdout = sys.stdout |
|
1415 | sys_stdout = sys.stdout | |
1416 | try: |
|
1416 | try: | |
1417 | sys.stdout = stdout_trap |
|
1417 | sys.stdout = stdout_trap | |
1418 | stats.print_stats(*lims) |
|
1418 | stats.print_stats(*lims) | |
1419 | finally: |
|
1419 | finally: | |
1420 | sys.stdout = sys_stdout |
|
1420 | sys.stdout = sys_stdout | |
1421 |
|
1421 | |||
1422 | output = stdout_trap.getvalue() |
|
1422 | output = stdout_trap.getvalue() | |
1423 | output = output.rstrip() |
|
1423 | output = output.rstrip() | |
1424 |
|
1424 | |||
1425 | page.page(output) |
|
1425 | page.page(output) | |
1426 | print sys_exit, |
|
1426 | print sys_exit, | |
1427 |
|
1427 | |||
1428 | dump_file = opts.D[0] |
|
1428 | dump_file = opts.D[0] | |
1429 | text_file = opts.T[0] |
|
1429 | text_file = opts.T[0] | |
1430 | if dump_file: |
|
1430 | if dump_file: | |
1431 | prof.dump_stats(dump_file) |
|
1431 | prof.dump_stats(dump_file) | |
1432 | print '\n*** Profile stats marshalled to file',\ |
|
1432 | print '\n*** Profile stats marshalled to file',\ | |
1433 | `dump_file`+'.',sys_exit |
|
1433 | `dump_file`+'.',sys_exit | |
1434 | if text_file: |
|
1434 | if text_file: | |
1435 | pfile = file(text_file,'w') |
|
1435 | pfile = file(text_file,'w') | |
1436 | pfile.write(output) |
|
1436 | pfile.write(output) | |
1437 | pfile.close() |
|
1437 | pfile.close() | |
1438 | print '\n*** Profile printout saved to text file',\ |
|
1438 | print '\n*** Profile printout saved to text file',\ | |
1439 | `text_file`+'.',sys_exit |
|
1439 | `text_file`+'.',sys_exit | |
1440 |
|
1440 | |||
1441 | if opts.has_key('r'): |
|
1441 | if opts.has_key('r'): | |
1442 | return stats |
|
1442 | return stats | |
1443 | else: |
|
1443 | else: | |
1444 | return None |
|
1444 | return None | |
1445 |
|
1445 | |||
1446 | @testdec.skip_doctest |
|
1446 | @testdec.skip_doctest | |
1447 | def magic_run(self, parameter_s ='',runner=None, |
|
1447 | def magic_run(self, parameter_s ='',runner=None, | |
1448 | file_finder=get_py_filename): |
|
1448 | file_finder=get_py_filename): | |
1449 | """Run the named file inside IPython as a program. |
|
1449 | """Run the named file inside IPython as a program. | |
1450 |
|
1450 | |||
1451 | Usage:\\ |
|
1451 | Usage:\\ | |
1452 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1452 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
1453 |
|
1453 | |||
1454 | Parameters after the filename are passed as command-line arguments to |
|
1454 | Parameters after the filename are passed as command-line arguments to | |
1455 | the program (put in sys.argv). Then, control returns to IPython's |
|
1455 | the program (put in sys.argv). Then, control returns to IPython's | |
1456 | prompt. |
|
1456 | prompt. | |
1457 |
|
1457 | |||
1458 | This is similar to running at a system prompt:\\ |
|
1458 | This is similar to running at a system prompt:\\ | |
1459 | $ python file args\\ |
|
1459 | $ python file args\\ | |
1460 | but with the advantage of giving you IPython's tracebacks, and of |
|
1460 | but with the advantage of giving you IPython's tracebacks, and of | |
1461 | loading all variables into your interactive namespace for further use |
|
1461 | loading all variables into your interactive namespace for further use | |
1462 | (unless -p is used, see below). |
|
1462 | (unless -p is used, see below). | |
1463 |
|
1463 | |||
1464 | The file is executed in a namespace initially consisting only of |
|
1464 | The file is executed in a namespace initially consisting only of | |
1465 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1465 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
1466 | sees its environment as if it were being run as a stand-alone program |
|
1466 | sees its environment as if it were being run as a stand-alone program | |
1467 | (except for sharing global objects such as previously imported |
|
1467 | (except for sharing global objects such as previously imported | |
1468 | modules). But after execution, the IPython interactive namespace gets |
|
1468 | modules). But after execution, the IPython interactive namespace gets | |
1469 | updated with all variables defined in the program (except for __name__ |
|
1469 | updated with all variables defined in the program (except for __name__ | |
1470 | and sys.argv). This allows for very convenient loading of code for |
|
1470 | and sys.argv). This allows for very convenient loading of code for | |
1471 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1471 | interactive work, while giving each program a 'clean sheet' to run in. | |
1472 |
|
1472 | |||
1473 | Options: |
|
1473 | Options: | |
1474 |
|
1474 | |||
1475 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1475 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
1476 | without extension (as python does under import). This allows running |
|
1476 | without extension (as python does under import). This allows running | |
1477 | scripts and reloading the definitions in them without calling code |
|
1477 | scripts and reloading the definitions in them without calling code | |
1478 | protected by an ' if __name__ == "__main__" ' clause. |
|
1478 | protected by an ' if __name__ == "__main__" ' clause. | |
1479 |
|
1479 | |||
1480 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1480 | -i: run the file in IPython's namespace instead of an empty one. This | |
1481 | is useful if you are experimenting with code written in a text editor |
|
1481 | is useful if you are experimenting with code written in a text editor | |
1482 | which depends on variables defined interactively. |
|
1482 | which depends on variables defined interactively. | |
1483 |
|
1483 | |||
1484 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1484 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
1485 | being run. This is particularly useful if IPython is being used to |
|
1485 | being run. This is particularly useful if IPython is being used to | |
1486 | run unittests, which always exit with a sys.exit() call. In such |
|
1486 | run unittests, which always exit with a sys.exit() call. In such | |
1487 | cases you are interested in the output of the test results, not in |
|
1487 | cases you are interested in the output of the test results, not in | |
1488 | seeing a traceback of the unittest module. |
|
1488 | seeing a traceback of the unittest module. | |
1489 |
|
1489 | |||
1490 | -t: print timing information at the end of the run. IPython will give |
|
1490 | -t: print timing information at the end of the run. IPython will give | |
1491 | you an estimated CPU time consumption for your script, which under |
|
1491 | you an estimated CPU time consumption for your script, which under | |
1492 | Unix uses the resource module to avoid the wraparound problems of |
|
1492 | Unix uses the resource module to avoid the wraparound problems of | |
1493 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1493 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
1494 | is also given (for Windows platforms this is reported as 0.0). |
|
1494 | is also given (for Windows platforms this is reported as 0.0). | |
1495 |
|
1495 | |||
1496 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1496 | If -t is given, an additional -N<N> option can be given, where <N> | |
1497 | must be an integer indicating how many times you want the script to |
|
1497 | must be an integer indicating how many times you want the script to | |
1498 | run. The final timing report will include total and per run results. |
|
1498 | run. The final timing report will include total and per run results. | |
1499 |
|
1499 | |||
1500 | For example (testing the script uniq_stable.py): |
|
1500 | For example (testing the script uniq_stable.py): | |
1501 |
|
1501 | |||
1502 | In [1]: run -t uniq_stable |
|
1502 | In [1]: run -t uniq_stable | |
1503 |
|
1503 | |||
1504 | IPython CPU timings (estimated):\\ |
|
1504 | IPython CPU timings (estimated):\\ | |
1505 | User : 0.19597 s.\\ |
|
1505 | User : 0.19597 s.\\ | |
1506 | System: 0.0 s.\\ |
|
1506 | System: 0.0 s.\\ | |
1507 |
|
1507 | |||
1508 | In [2]: run -t -N5 uniq_stable |
|
1508 | In [2]: run -t -N5 uniq_stable | |
1509 |
|
1509 | |||
1510 | IPython CPU timings (estimated):\\ |
|
1510 | IPython CPU timings (estimated):\\ | |
1511 | Total runs performed: 5\\ |
|
1511 | Total runs performed: 5\\ | |
1512 | Times : Total Per run\\ |
|
1512 | Times : Total Per run\\ | |
1513 | User : 0.910862 s, 0.1821724 s.\\ |
|
1513 | User : 0.910862 s, 0.1821724 s.\\ | |
1514 | System: 0.0 s, 0.0 s. |
|
1514 | System: 0.0 s, 0.0 s. | |
1515 |
|
1515 | |||
1516 | -d: run your program under the control of pdb, the Python debugger. |
|
1516 | -d: run your program under the control of pdb, the Python debugger. | |
1517 | This allows you to execute your program step by step, watch variables, |
|
1517 | This allows you to execute your program step by step, watch variables, | |
1518 | etc. Internally, what IPython does is similar to calling: |
|
1518 | etc. Internally, what IPython does is similar to calling: | |
1519 |
|
1519 | |||
1520 | pdb.run('execfile("YOURFILENAME")') |
|
1520 | pdb.run('execfile("YOURFILENAME")') | |
1521 |
|
1521 | |||
1522 | with a breakpoint set on line 1 of your file. You can change the line |
|
1522 | with a breakpoint set on line 1 of your file. You can change the line | |
1523 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1523 | number for this automatic breakpoint to be <N> by using the -bN option | |
1524 | (where N must be an integer). For example: |
|
1524 | (where N must be an integer). For example: | |
1525 |
|
1525 | |||
1526 | %run -d -b40 myscript |
|
1526 | %run -d -b40 myscript | |
1527 |
|
1527 | |||
1528 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1528 | will set the first breakpoint at line 40 in myscript.py. Note that | |
1529 | the first breakpoint must be set on a line which actually does |
|
1529 | the first breakpoint must be set on a line which actually does | |
1530 | something (not a comment or docstring) for it to stop execution. |
|
1530 | something (not a comment or docstring) for it to stop execution. | |
1531 |
|
1531 | |||
1532 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1532 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
1533 | first enter 'c' (without qoutes) to start execution up to the first |
|
1533 | first enter 'c' (without qoutes) to start execution up to the first | |
1534 | breakpoint. |
|
1534 | breakpoint. | |
1535 |
|
1535 | |||
1536 | Entering 'help' gives information about the use of the debugger. You |
|
1536 | Entering 'help' gives information about the use of the debugger. You | |
1537 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1537 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
1538 | at a prompt. |
|
1538 | at a prompt. | |
1539 |
|
1539 | |||
1540 | -p: run program under the control of the Python profiler module (which |
|
1540 | -p: run program under the control of the Python profiler module (which | |
1541 | prints a detailed report of execution times, function calls, etc). |
|
1541 | prints a detailed report of execution times, function calls, etc). | |
1542 |
|
1542 | |||
1543 | You can pass other options after -p which affect the behavior of the |
|
1543 | You can pass other options after -p which affect the behavior of the | |
1544 | profiler itself. See the docs for %prun for details. |
|
1544 | profiler itself. See the docs for %prun for details. | |
1545 |
|
1545 | |||
1546 | In this mode, the program's variables do NOT propagate back to the |
|
1546 | In this mode, the program's variables do NOT propagate back to the | |
1547 | IPython interactive namespace (because they remain in the namespace |
|
1547 | IPython interactive namespace (because they remain in the namespace | |
1548 | where the profiler executes them). |
|
1548 | where the profiler executes them). | |
1549 |
|
1549 | |||
1550 | Internally this triggers a call to %prun, see its documentation for |
|
1550 | Internally this triggers a call to %prun, see its documentation for | |
1551 | details on the options available specifically for profiling. |
|
1551 | details on the options available specifically for profiling. | |
1552 |
|
1552 | |||
1553 | There is one special usage for which the text above doesn't apply: |
|
1553 | There is one special usage for which the text above doesn't apply: | |
1554 | if the filename ends with .ipy, the file is run as ipython script, |
|
1554 | if the filename ends with .ipy, the file is run as ipython script, | |
1555 | just as if the commands were written on IPython prompt. |
|
1555 | just as if the commands were written on IPython prompt. | |
1556 | """ |
|
1556 | """ | |
1557 |
|
1557 | |||
1558 | # get arguments and set sys.argv for program to be run. |
|
1558 | # get arguments and set sys.argv for program to be run. | |
1559 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1559 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', | |
1560 | mode='list',list_all=1) |
|
1560 | mode='list',list_all=1) | |
1561 |
|
1561 | |||
1562 | try: |
|
1562 | try: | |
1563 | filename = file_finder(arg_lst[0]) |
|
1563 | filename = file_finder(arg_lst[0]) | |
1564 | except IndexError: |
|
1564 | except IndexError: | |
1565 | warn('you must provide at least a filename.') |
|
1565 | warn('you must provide at least a filename.') | |
1566 | print '\n%run:\n',oinspect.getdoc(self.magic_run) |
|
1566 | print '\n%run:\n',oinspect.getdoc(self.magic_run) | |
1567 | return |
|
1567 | return | |
1568 | except IOError,msg: |
|
1568 | except IOError,msg: | |
1569 | error(msg) |
|
1569 | error(msg) | |
1570 | return |
|
1570 | return | |
1571 |
|
1571 | |||
1572 | if filename.lower().endswith('.ipy'): |
|
1572 | if filename.lower().endswith('.ipy'): | |
1573 | self.shell.safe_execfile_ipy(filename) |
|
1573 | self.shell.safe_execfile_ipy(filename) | |
1574 | return |
|
1574 | return | |
1575 |
|
1575 | |||
1576 | # Control the response to exit() calls made by the script being run |
|
1576 | # Control the response to exit() calls made by the script being run | |
1577 | exit_ignore = opts.has_key('e') |
|
1577 | exit_ignore = opts.has_key('e') | |
1578 |
|
1578 | |||
1579 | # Make sure that the running script gets a proper sys.argv as if it |
|
1579 | # Make sure that the running script gets a proper sys.argv as if it | |
1580 | # were run from a system shell. |
|
1580 | # were run from a system shell. | |
1581 | save_argv = sys.argv # save it for later restoring |
|
1581 | save_argv = sys.argv # save it for later restoring | |
1582 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1582 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename | |
1583 |
|
1583 | |||
1584 | if opts.has_key('i'): |
|
1584 | if opts.has_key('i'): | |
1585 | # Run in user's interactive namespace |
|
1585 | # Run in user's interactive namespace | |
1586 | prog_ns = self.shell.user_ns |
|
1586 | prog_ns = self.shell.user_ns | |
1587 | __name__save = self.shell.user_ns['__name__'] |
|
1587 | __name__save = self.shell.user_ns['__name__'] | |
1588 | prog_ns['__name__'] = '__main__' |
|
1588 | prog_ns['__name__'] = '__main__' | |
1589 | main_mod = self.shell.new_main_mod(prog_ns) |
|
1589 | main_mod = self.shell.new_main_mod(prog_ns) | |
1590 | else: |
|
1590 | else: | |
1591 | # Run in a fresh, empty namespace |
|
1591 | # Run in a fresh, empty namespace | |
1592 | if opts.has_key('n'): |
|
1592 | if opts.has_key('n'): | |
1593 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1593 | name = os.path.splitext(os.path.basename(filename))[0] | |
1594 | else: |
|
1594 | else: | |
1595 | name = '__main__' |
|
1595 | name = '__main__' | |
1596 |
|
1596 | |||
1597 | main_mod = self.shell.new_main_mod() |
|
1597 | main_mod = self.shell.new_main_mod() | |
1598 | prog_ns = main_mod.__dict__ |
|
1598 | prog_ns = main_mod.__dict__ | |
1599 | prog_ns['__name__'] = name |
|
1599 | prog_ns['__name__'] = name | |
1600 |
|
1600 | |||
1601 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1601 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must | |
1602 | # set the __file__ global in the script's namespace |
|
1602 | # set the __file__ global in the script's namespace | |
1603 | prog_ns['__file__'] = filename |
|
1603 | prog_ns['__file__'] = filename | |
1604 |
|
1604 | |||
1605 | # pickle fix. See interactiveshell for an explanation. But we need to make sure |
|
1605 | # pickle fix. See interactiveshell for an explanation. But we need to make sure | |
1606 | # that, if we overwrite __main__, we replace it at the end |
|
1606 | # that, if we overwrite __main__, we replace it at the end | |
1607 | main_mod_name = prog_ns['__name__'] |
|
1607 | main_mod_name = prog_ns['__name__'] | |
1608 |
|
1608 | |||
1609 | if main_mod_name == '__main__': |
|
1609 | if main_mod_name == '__main__': | |
1610 | restore_main = sys.modules['__main__'] |
|
1610 | restore_main = sys.modules['__main__'] | |
1611 | else: |
|
1611 | else: | |
1612 | restore_main = False |
|
1612 | restore_main = False | |
1613 |
|
1613 | |||
1614 | # This needs to be undone at the end to prevent holding references to |
|
1614 | # This needs to be undone at the end to prevent holding references to | |
1615 | # every single object ever created. |
|
1615 | # every single object ever created. | |
1616 | sys.modules[main_mod_name] = main_mod |
|
1616 | sys.modules[main_mod_name] = main_mod | |
1617 |
|
1617 | |||
1618 | stats = None |
|
1618 | stats = None | |
1619 | try: |
|
1619 | try: | |
1620 | self.shell.save_history() |
|
1620 | self.shell.save_history() | |
1621 |
|
1621 | |||
1622 | if opts.has_key('p'): |
|
1622 | if opts.has_key('p'): | |
1623 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1623 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) | |
1624 | else: |
|
1624 | else: | |
1625 | if opts.has_key('d'): |
|
1625 | if opts.has_key('d'): | |
1626 | deb = debugger.Pdb(self.shell.colors) |
|
1626 | deb = debugger.Pdb(self.shell.colors) | |
1627 | # reset Breakpoint state, which is moronically kept |
|
1627 | # reset Breakpoint state, which is moronically kept | |
1628 | # in a class |
|
1628 | # in a class | |
1629 | bdb.Breakpoint.next = 1 |
|
1629 | bdb.Breakpoint.next = 1 | |
1630 | bdb.Breakpoint.bplist = {} |
|
1630 | bdb.Breakpoint.bplist = {} | |
1631 | bdb.Breakpoint.bpbynumber = [None] |
|
1631 | bdb.Breakpoint.bpbynumber = [None] | |
1632 | # Set an initial breakpoint to stop execution |
|
1632 | # Set an initial breakpoint to stop execution | |
1633 | maxtries = 10 |
|
1633 | maxtries = 10 | |
1634 | bp = int(opts.get('b',[1])[0]) |
|
1634 | bp = int(opts.get('b',[1])[0]) | |
1635 | checkline = deb.checkline(filename,bp) |
|
1635 | checkline = deb.checkline(filename,bp) | |
1636 | if not checkline: |
|
1636 | if not checkline: | |
1637 | for bp in range(bp+1,bp+maxtries+1): |
|
1637 | for bp in range(bp+1,bp+maxtries+1): | |
1638 | if deb.checkline(filename,bp): |
|
1638 | if deb.checkline(filename,bp): | |
1639 | break |
|
1639 | break | |
1640 | else: |
|
1640 | else: | |
1641 | msg = ("\nI failed to find a valid line to set " |
|
1641 | msg = ("\nI failed to find a valid line to set " | |
1642 | "a breakpoint\n" |
|
1642 | "a breakpoint\n" | |
1643 | "after trying up to line: %s.\n" |
|
1643 | "after trying up to line: %s.\n" | |
1644 | "Please set a valid breakpoint manually " |
|
1644 | "Please set a valid breakpoint manually " | |
1645 | "with the -b option." % bp) |
|
1645 | "with the -b option." % bp) | |
1646 | error(msg) |
|
1646 | error(msg) | |
1647 | return |
|
1647 | return | |
1648 | # if we find a good linenumber, set the breakpoint |
|
1648 | # if we find a good linenumber, set the breakpoint | |
1649 | deb.do_break('%s:%s' % (filename,bp)) |
|
1649 | deb.do_break('%s:%s' % (filename,bp)) | |
1650 | # Start file run |
|
1650 | # Start file run | |
1651 | print "NOTE: Enter 'c' at the", |
|
1651 | print "NOTE: Enter 'c' at the", | |
1652 | print "%s prompt to start your script." % deb.prompt |
|
1652 | print "%s prompt to start your script." % deb.prompt | |
1653 | try: |
|
1653 | try: | |
1654 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1654 | deb.run('execfile("%s")' % filename,prog_ns) | |
1655 |
|
1655 | |||
1656 | except: |
|
1656 | except: | |
1657 | etype, value, tb = sys.exc_info() |
|
1657 | etype, value, tb = sys.exc_info() | |
1658 | # Skip three frames in the traceback: the %run one, |
|
1658 | # Skip three frames in the traceback: the %run one, | |
1659 | # one inside bdb.py, and the command-line typed by the |
|
1659 | # one inside bdb.py, and the command-line typed by the | |
1660 | # user (run by exec in pdb itself). |
|
1660 | # user (run by exec in pdb itself). | |
1661 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1661 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) | |
1662 | else: |
|
1662 | else: | |
1663 | if runner is None: |
|
1663 | if runner is None: | |
1664 | runner = self.shell.safe_execfile |
|
1664 | runner = self.shell.safe_execfile | |
1665 | if opts.has_key('t'): |
|
1665 | if opts.has_key('t'): | |
1666 | # timed execution |
|
1666 | # timed execution | |
1667 | try: |
|
1667 | try: | |
1668 | nruns = int(opts['N'][0]) |
|
1668 | nruns = int(opts['N'][0]) | |
1669 | if nruns < 1: |
|
1669 | if nruns < 1: | |
1670 | error('Number of runs must be >=1') |
|
1670 | error('Number of runs must be >=1') | |
1671 | return |
|
1671 | return | |
1672 | except (KeyError): |
|
1672 | except (KeyError): | |
1673 | nruns = 1 |
|
1673 | nruns = 1 | |
1674 | if nruns == 1: |
|
1674 | if nruns == 1: | |
1675 | t0 = clock2() |
|
1675 | t0 = clock2() | |
1676 | runner(filename,prog_ns,prog_ns, |
|
1676 | runner(filename,prog_ns,prog_ns, | |
1677 | exit_ignore=exit_ignore) |
|
1677 | exit_ignore=exit_ignore) | |
1678 | t1 = clock2() |
|
1678 | t1 = clock2() | |
1679 | t_usr = t1[0]-t0[0] |
|
1679 | t_usr = t1[0]-t0[0] | |
1680 | t_sys = t1[1]-t0[1] |
|
1680 | t_sys = t1[1]-t0[1] | |
1681 | print "\nIPython CPU timings (estimated):" |
|
1681 | print "\nIPython CPU timings (estimated):" | |
1682 | print " User : %10s s." % t_usr |
|
1682 | print " User : %10s s." % t_usr | |
1683 | print " System: %10s s." % t_sys |
|
1683 | print " System: %10s s." % t_sys | |
1684 | else: |
|
1684 | else: | |
1685 | runs = range(nruns) |
|
1685 | runs = range(nruns) | |
1686 | t0 = clock2() |
|
1686 | t0 = clock2() | |
1687 | for nr in runs: |
|
1687 | for nr in runs: | |
1688 | runner(filename,prog_ns,prog_ns, |
|
1688 | runner(filename,prog_ns,prog_ns, | |
1689 | exit_ignore=exit_ignore) |
|
1689 | exit_ignore=exit_ignore) | |
1690 | t1 = clock2() |
|
1690 | t1 = clock2() | |
1691 | t_usr = t1[0]-t0[0] |
|
1691 | t_usr = t1[0]-t0[0] | |
1692 | t_sys = t1[1]-t0[1] |
|
1692 | t_sys = t1[1]-t0[1] | |
1693 | print "\nIPython CPU timings (estimated):" |
|
1693 | print "\nIPython CPU timings (estimated):" | |
1694 | print "Total runs performed:",nruns |
|
1694 | print "Total runs performed:",nruns | |
1695 | print " Times : %10s %10s" % ('Total','Per run') |
|
1695 | print " Times : %10s %10s" % ('Total','Per run') | |
1696 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1696 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) | |
1697 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1697 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) | |
1698 |
|
1698 | |||
1699 | else: |
|
1699 | else: | |
1700 | # regular execution |
|
1700 | # regular execution | |
1701 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1701 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1702 |
|
1702 | |||
1703 | if opts.has_key('i'): |
|
1703 | if opts.has_key('i'): | |
1704 | self.shell.user_ns['__name__'] = __name__save |
|
1704 | self.shell.user_ns['__name__'] = __name__save | |
1705 | else: |
|
1705 | else: | |
1706 | # The shell MUST hold a reference to prog_ns so after %run |
|
1706 | # The shell MUST hold a reference to prog_ns so after %run | |
1707 | # exits, the python deletion mechanism doesn't zero it out |
|
1707 | # exits, the python deletion mechanism doesn't zero it out | |
1708 | # (leaving dangling references). |
|
1708 | # (leaving dangling references). | |
1709 | self.shell.cache_main_mod(prog_ns,filename) |
|
1709 | self.shell.cache_main_mod(prog_ns,filename) | |
1710 | # update IPython interactive namespace |
|
1710 | # update IPython interactive namespace | |
1711 |
|
1711 | |||
1712 | # Some forms of read errors on the file may mean the |
|
1712 | # Some forms of read errors on the file may mean the | |
1713 | # __name__ key was never set; using pop we don't have to |
|
1713 | # __name__ key was never set; using pop we don't have to | |
1714 | # worry about a possible KeyError. |
|
1714 | # worry about a possible KeyError. | |
1715 | prog_ns.pop('__name__', None) |
|
1715 | prog_ns.pop('__name__', None) | |
1716 |
|
1716 | |||
1717 | self.shell.user_ns.update(prog_ns) |
|
1717 | self.shell.user_ns.update(prog_ns) | |
1718 | finally: |
|
1718 | finally: | |
1719 | # It's a bit of a mystery why, but __builtins__ can change from |
|
1719 | # It's a bit of a mystery why, but __builtins__ can change from | |
1720 | # being a module to becoming a dict missing some key data after |
|
1720 | # being a module to becoming a dict missing some key data after | |
1721 | # %run. As best I can see, this is NOT something IPython is doing |
|
1721 | # %run. As best I can see, this is NOT something IPython is doing | |
1722 | # at all, and similar problems have been reported before: |
|
1722 | # at all, and similar problems have been reported before: | |
1723 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
1723 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html | |
1724 | # Since this seems to be done by the interpreter itself, the best |
|
1724 | # Since this seems to be done by the interpreter itself, the best | |
1725 | # we can do is to at least restore __builtins__ for the user on |
|
1725 | # we can do is to at least restore __builtins__ for the user on | |
1726 | # exit. |
|
1726 | # exit. | |
1727 | self.shell.user_ns['__builtins__'] = __builtin__ |
|
1727 | self.shell.user_ns['__builtins__'] = __builtin__ | |
1728 |
|
1728 | |||
1729 | # Ensure key global structures are restored |
|
1729 | # Ensure key global structures are restored | |
1730 | sys.argv = save_argv |
|
1730 | sys.argv = save_argv | |
1731 | if restore_main: |
|
1731 | if restore_main: | |
1732 | sys.modules['__main__'] = restore_main |
|
1732 | sys.modules['__main__'] = restore_main | |
1733 | else: |
|
1733 | else: | |
1734 | # Remove from sys.modules the reference to main_mod we'd |
|
1734 | # Remove from sys.modules the reference to main_mod we'd | |
1735 | # added. Otherwise it will trap references to objects |
|
1735 | # added. Otherwise it will trap references to objects | |
1736 | # contained therein. |
|
1736 | # contained therein. | |
1737 | del sys.modules[main_mod_name] |
|
1737 | del sys.modules[main_mod_name] | |
1738 |
|
1738 | |||
1739 | self.shell.reload_history() |
|
1739 | self.shell.reload_history() | |
1740 |
|
1740 | |||
1741 | return stats |
|
1741 | return stats | |
1742 |
|
1742 | |||
1743 | @testdec.skip_doctest |
|
1743 | @testdec.skip_doctest | |
1744 | def magic_timeit(self, parameter_s =''): |
|
1744 | def magic_timeit(self, parameter_s =''): | |
1745 | """Time execution of a Python statement or expression |
|
1745 | """Time execution of a Python statement or expression | |
1746 |
|
1746 | |||
1747 | Usage:\\ |
|
1747 | Usage:\\ | |
1748 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1748 | %timeit [-n<N> -r<R> [-t|-c]] statement | |
1749 |
|
1749 | |||
1750 | Time execution of a Python statement or expression using the timeit |
|
1750 | Time execution of a Python statement or expression using the timeit | |
1751 | module. |
|
1751 | module. | |
1752 |
|
1752 | |||
1753 | Options: |
|
1753 | Options: | |
1754 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1754 | -n<N>: execute the given statement <N> times in a loop. If this value | |
1755 | is not given, a fitting value is chosen. |
|
1755 | is not given, a fitting value is chosen. | |
1756 |
|
1756 | |||
1757 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1757 | -r<R>: repeat the loop iteration <R> times and take the best result. | |
1758 | Default: 3 |
|
1758 | Default: 3 | |
1759 |
|
1759 | |||
1760 | -t: use time.time to measure the time, which is the default on Unix. |
|
1760 | -t: use time.time to measure the time, which is the default on Unix. | |
1761 | This function measures wall time. |
|
1761 | This function measures wall time. | |
1762 |
|
1762 | |||
1763 | -c: use time.clock to measure the time, which is the default on |
|
1763 | -c: use time.clock to measure the time, which is the default on | |
1764 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1764 | Windows and measures wall time. On Unix, resource.getrusage is used | |
1765 | instead and returns the CPU user time. |
|
1765 | instead and returns the CPU user time. | |
1766 |
|
1766 | |||
1767 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1767 | -p<P>: use a precision of <P> digits to display the timing result. | |
1768 | Default: 3 |
|
1768 | Default: 3 | |
1769 |
|
1769 | |||
1770 |
|
1770 | |||
1771 | Examples: |
|
1771 | Examples: | |
1772 |
|
1772 | |||
1773 | In [1]: %timeit pass |
|
1773 | In [1]: %timeit pass | |
1774 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1774 | 10000000 loops, best of 3: 53.3 ns per loop | |
1775 |
|
1775 | |||
1776 | In [2]: u = None |
|
1776 | In [2]: u = None | |
1777 |
|
1777 | |||
1778 | In [3]: %timeit u is None |
|
1778 | In [3]: %timeit u is None | |
1779 | 10000000 loops, best of 3: 184 ns per loop |
|
1779 | 10000000 loops, best of 3: 184 ns per loop | |
1780 |
|
1780 | |||
1781 | In [4]: %timeit -r 4 u == None |
|
1781 | In [4]: %timeit -r 4 u == None | |
1782 | 1000000 loops, best of 4: 242 ns per loop |
|
1782 | 1000000 loops, best of 4: 242 ns per loop | |
1783 |
|
1783 | |||
1784 | In [5]: import time |
|
1784 | In [5]: import time | |
1785 |
|
1785 | |||
1786 | In [6]: %timeit -n1 time.sleep(2) |
|
1786 | In [6]: %timeit -n1 time.sleep(2) | |
1787 | 1 loops, best of 3: 2 s per loop |
|
1787 | 1 loops, best of 3: 2 s per loop | |
1788 |
|
1788 | |||
1789 |
|
1789 | |||
1790 | The times reported by %timeit will be slightly higher than those |
|
1790 | The times reported by %timeit will be slightly higher than those | |
1791 | reported by the timeit.py script when variables are accessed. This is |
|
1791 | reported by the timeit.py script when variables are accessed. This is | |
1792 | due to the fact that %timeit executes the statement in the namespace |
|
1792 | due to the fact that %timeit executes the statement in the namespace | |
1793 | of the shell, compared with timeit.py, which uses a single setup |
|
1793 | of the shell, compared with timeit.py, which uses a single setup | |
1794 | statement to import function or create variables. Generally, the bias |
|
1794 | statement to import function or create variables. Generally, the bias | |
1795 | does not matter as long as results from timeit.py are not mixed with |
|
1795 | does not matter as long as results from timeit.py are not mixed with | |
1796 | those from %timeit.""" |
|
1796 | those from %timeit.""" | |
1797 |
|
1797 | |||
1798 | import timeit |
|
1798 | import timeit | |
1799 | import math |
|
1799 | import math | |
1800 |
|
1800 | |||
1801 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in |
|
1801 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in | |
1802 | # certain terminals. Until we figure out a robust way of |
|
1802 | # certain terminals. Until we figure out a robust way of | |
1803 | # auto-detecting if the terminal can deal with it, use plain 'us' for |
|
1803 | # auto-detecting if the terminal can deal with it, use plain 'us' for | |
1804 | # microseconds. I am really NOT happy about disabling the proper |
|
1804 | # microseconds. I am really NOT happy about disabling the proper | |
1805 | # 'micro' prefix, but crashing is worse... If anyone knows what the |
|
1805 | # 'micro' prefix, but crashing is worse... If anyone knows what the | |
1806 | # right solution for this is, I'm all ears... |
|
1806 | # right solution for this is, I'm all ears... | |
1807 | # |
|
1807 | # | |
1808 | # Note: using |
|
1808 | # Note: using | |
1809 | # |
|
1809 | # | |
1810 | # s = u'\xb5' |
|
1810 | # s = u'\xb5' | |
1811 | # s.encode(sys.getdefaultencoding()) |
|
1811 | # s.encode(sys.getdefaultencoding()) | |
1812 | # |
|
1812 | # | |
1813 | # is not sufficient, as I've seen terminals where that fails but |
|
1813 | # is not sufficient, as I've seen terminals where that fails but | |
1814 | # print s |
|
1814 | # print s | |
1815 | # |
|
1815 | # | |
1816 | # succeeds |
|
1816 | # succeeds | |
1817 | # |
|
1817 | # | |
1818 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1818 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 | |
1819 |
|
1819 | |||
1820 | #units = [u"s", u"ms",u'\xb5',"ns"] |
|
1820 | #units = [u"s", u"ms",u'\xb5',"ns"] | |
1821 | units = [u"s", u"ms",u'us',"ns"] |
|
1821 | units = [u"s", u"ms",u'us',"ns"] | |
1822 |
|
1822 | |||
1823 | scaling = [1, 1e3, 1e6, 1e9] |
|
1823 | scaling = [1, 1e3, 1e6, 1e9] | |
1824 |
|
1824 | |||
1825 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1825 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', | |
1826 | posix=False) |
|
1826 | posix=False) | |
1827 | if stmt == "": |
|
1827 | if stmt == "": | |
1828 | return |
|
1828 | return | |
1829 | timefunc = timeit.default_timer |
|
1829 | timefunc = timeit.default_timer | |
1830 | number = int(getattr(opts, "n", 0)) |
|
1830 | number = int(getattr(opts, "n", 0)) | |
1831 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1831 | repeat = int(getattr(opts, "r", timeit.default_repeat)) | |
1832 | precision = int(getattr(opts, "p", 3)) |
|
1832 | precision = int(getattr(opts, "p", 3)) | |
1833 | if hasattr(opts, "t"): |
|
1833 | if hasattr(opts, "t"): | |
1834 | timefunc = time.time |
|
1834 | timefunc = time.time | |
1835 | if hasattr(opts, "c"): |
|
1835 | if hasattr(opts, "c"): | |
1836 | timefunc = clock |
|
1836 | timefunc = clock | |
1837 |
|
1837 | |||
1838 | timer = timeit.Timer(timer=timefunc) |
|
1838 | timer = timeit.Timer(timer=timefunc) | |
1839 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1839 | # this code has tight coupling to the inner workings of timeit.Timer, | |
1840 | # but is there a better way to achieve that the code stmt has access |
|
1840 | # but is there a better way to achieve that the code stmt has access | |
1841 | # to the shell namespace? |
|
1841 | # to the shell namespace? | |
1842 |
|
1842 | |||
1843 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1843 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), | |
1844 | 'setup': "pass"} |
|
1844 | 'setup': "pass"} | |
1845 | # Track compilation time so it can be reported if too long |
|
1845 | # Track compilation time so it can be reported if too long | |
1846 | # Minimum time above which compilation time will be reported |
|
1846 | # Minimum time above which compilation time will be reported | |
1847 | tc_min = 0.1 |
|
1847 | tc_min = 0.1 | |
1848 |
|
1848 | |||
1849 | t0 = clock() |
|
1849 | t0 = clock() | |
1850 | code = compile(src, "<magic-timeit>", "exec") |
|
1850 | code = compile(src, "<magic-timeit>", "exec") | |
1851 | tc = clock()-t0 |
|
1851 | tc = clock()-t0 | |
1852 |
|
1852 | |||
1853 | ns = {} |
|
1853 | ns = {} | |
1854 | exec code in self.shell.user_ns, ns |
|
1854 | exec code in self.shell.user_ns, ns | |
1855 | timer.inner = ns["inner"] |
|
1855 | timer.inner = ns["inner"] | |
1856 |
|
1856 | |||
1857 | if number == 0: |
|
1857 | if number == 0: | |
1858 | # determine number so that 0.2 <= total time < 2.0 |
|
1858 | # determine number so that 0.2 <= total time < 2.0 | |
1859 | number = 1 |
|
1859 | number = 1 | |
1860 | for i in range(1, 10): |
|
1860 | for i in range(1, 10): | |
1861 | if timer.timeit(number) >= 0.2: |
|
1861 | if timer.timeit(number) >= 0.2: | |
1862 | break |
|
1862 | break | |
1863 | number *= 10 |
|
1863 | number *= 10 | |
1864 |
|
1864 | |||
1865 | best = min(timer.repeat(repeat, number)) / number |
|
1865 | best = min(timer.repeat(repeat, number)) / number | |
1866 |
|
1866 | |||
1867 | if best > 0.0 and best < 1000.0: |
|
1867 | if best > 0.0 and best < 1000.0: | |
1868 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1868 | order = min(-int(math.floor(math.log10(best)) // 3), 3) | |
1869 | elif best >= 1000.0: |
|
1869 | elif best >= 1000.0: | |
1870 | order = 0 |
|
1870 | order = 0 | |
1871 | else: |
|
1871 | else: | |
1872 | order = 3 |
|
1872 | order = 3 | |
1873 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1873 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, | |
1874 | precision, |
|
1874 | precision, | |
1875 | best * scaling[order], |
|
1875 | best * scaling[order], | |
1876 | units[order]) |
|
1876 | units[order]) | |
1877 | if tc > tc_min: |
|
1877 | if tc > tc_min: | |
1878 | print "Compiler time: %.2f s" % tc |
|
1878 | print "Compiler time: %.2f s" % tc | |
1879 |
|
1879 | |||
1880 | @testdec.skip_doctest |
|
1880 | @testdec.skip_doctest | |
1881 | def magic_time(self,parameter_s = ''): |
|
1881 | def magic_time(self,parameter_s = ''): | |
1882 | """Time execution of a Python statement or expression. |
|
1882 | """Time execution of a Python statement or expression. | |
1883 |
|
1883 | |||
1884 | The CPU and wall clock times are printed, and the value of the |
|
1884 | The CPU and wall clock times are printed, and the value of the | |
1885 | expression (if any) is returned. Note that under Win32, system time |
|
1885 | expression (if any) is returned. Note that under Win32, system time | |
1886 | is always reported as 0, since it can not be measured. |
|
1886 | is always reported as 0, since it can not be measured. | |
1887 |
|
1887 | |||
1888 | This function provides very basic timing functionality. In Python |
|
1888 | This function provides very basic timing functionality. In Python | |
1889 | 2.3, the timeit module offers more control and sophistication, so this |
|
1889 | 2.3, the timeit module offers more control and sophistication, so this | |
1890 | could be rewritten to use it (patches welcome). |
|
1890 | could be rewritten to use it (patches welcome). | |
1891 |
|
1891 | |||
1892 | Some examples: |
|
1892 | Some examples: | |
1893 |
|
1893 | |||
1894 | In [1]: time 2**128 |
|
1894 | In [1]: time 2**128 | |
1895 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1895 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1896 | Wall time: 0.00 |
|
1896 | Wall time: 0.00 | |
1897 | Out[1]: 340282366920938463463374607431768211456L |
|
1897 | Out[1]: 340282366920938463463374607431768211456L | |
1898 |
|
1898 | |||
1899 | In [2]: n = 1000000 |
|
1899 | In [2]: n = 1000000 | |
1900 |
|
1900 | |||
1901 | In [3]: time sum(range(n)) |
|
1901 | In [3]: time sum(range(n)) | |
1902 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1902 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
1903 | Wall time: 1.37 |
|
1903 | Wall time: 1.37 | |
1904 | Out[3]: 499999500000L |
|
1904 | Out[3]: 499999500000L | |
1905 |
|
1905 | |||
1906 | In [4]: time print 'hello world' |
|
1906 | In [4]: time print 'hello world' | |
1907 | hello world |
|
1907 | hello world | |
1908 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1908 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1909 | Wall time: 0.00 |
|
1909 | Wall time: 0.00 | |
1910 |
|
1910 | |||
1911 | Note that the time needed by Python to compile the given expression |
|
1911 | Note that the time needed by Python to compile the given expression | |
1912 | will be reported if it is more than 0.1s. In this example, the |
|
1912 | will be reported if it is more than 0.1s. In this example, the | |
1913 | actual exponentiation is done by Python at compilation time, so while |
|
1913 | actual exponentiation is done by Python at compilation time, so while | |
1914 | the expression can take a noticeable amount of time to compute, that |
|
1914 | the expression can take a noticeable amount of time to compute, that | |
1915 | time is purely due to the compilation: |
|
1915 | time is purely due to the compilation: | |
1916 |
|
1916 | |||
1917 | In [5]: time 3**9999; |
|
1917 | In [5]: time 3**9999; | |
1918 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1918 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1919 | Wall time: 0.00 s |
|
1919 | Wall time: 0.00 s | |
1920 |
|
1920 | |||
1921 | In [6]: time 3**999999; |
|
1921 | In [6]: time 3**999999; | |
1922 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1922 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1923 | Wall time: 0.00 s |
|
1923 | Wall time: 0.00 s | |
1924 | Compiler : 0.78 s |
|
1924 | Compiler : 0.78 s | |
1925 | """ |
|
1925 | """ | |
1926 |
|
1926 | |||
1927 | # fail immediately if the given expression can't be compiled |
|
1927 | # fail immediately if the given expression can't be compiled | |
1928 |
|
1928 | |||
1929 | expr = self.shell.prefilter(parameter_s,False) |
|
1929 | expr = self.shell.prefilter(parameter_s,False) | |
1930 |
|
1930 | |||
1931 | # Minimum time above which compilation time will be reported |
|
1931 | # Minimum time above which compilation time will be reported | |
1932 | tc_min = 0.1 |
|
1932 | tc_min = 0.1 | |
1933 |
|
1933 | |||
1934 | try: |
|
1934 | try: | |
1935 | mode = 'eval' |
|
1935 | mode = 'eval' | |
1936 | t0 = clock() |
|
1936 | t0 = clock() | |
1937 | code = compile(expr,'<timed eval>',mode) |
|
1937 | code = compile(expr,'<timed eval>',mode) | |
1938 | tc = clock()-t0 |
|
1938 | tc = clock()-t0 | |
1939 | except SyntaxError: |
|
1939 | except SyntaxError: | |
1940 | mode = 'exec' |
|
1940 | mode = 'exec' | |
1941 | t0 = clock() |
|
1941 | t0 = clock() | |
1942 | code = compile(expr,'<timed exec>',mode) |
|
1942 | code = compile(expr,'<timed exec>',mode) | |
1943 | tc = clock()-t0 |
|
1943 | tc = clock()-t0 | |
1944 | # skew measurement as little as possible |
|
1944 | # skew measurement as little as possible | |
1945 | glob = self.shell.user_ns |
|
1945 | glob = self.shell.user_ns | |
1946 | clk = clock2 |
|
1946 | clk = clock2 | |
1947 | wtime = time.time |
|
1947 | wtime = time.time | |
1948 | # time execution |
|
1948 | # time execution | |
1949 | wall_st = wtime() |
|
1949 | wall_st = wtime() | |
1950 | if mode=='eval': |
|
1950 | if mode=='eval': | |
1951 | st = clk() |
|
1951 | st = clk() | |
1952 | out = eval(code,glob) |
|
1952 | out = eval(code,glob) | |
1953 | end = clk() |
|
1953 | end = clk() | |
1954 | else: |
|
1954 | else: | |
1955 | st = clk() |
|
1955 | st = clk() | |
1956 | exec code in glob |
|
1956 | exec code in glob | |
1957 | end = clk() |
|
1957 | end = clk() | |
1958 | out = None |
|
1958 | out = None | |
1959 | wall_end = wtime() |
|
1959 | wall_end = wtime() | |
1960 | # Compute actual times and report |
|
1960 | # Compute actual times and report | |
1961 | wall_time = wall_end-wall_st |
|
1961 | wall_time = wall_end-wall_st | |
1962 | cpu_user = end[0]-st[0] |
|
1962 | cpu_user = end[0]-st[0] | |
1963 | cpu_sys = end[1]-st[1] |
|
1963 | cpu_sys = end[1]-st[1] | |
1964 | cpu_tot = cpu_user+cpu_sys |
|
1964 | cpu_tot = cpu_user+cpu_sys | |
1965 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1965 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
1966 | (cpu_user,cpu_sys,cpu_tot) |
|
1966 | (cpu_user,cpu_sys,cpu_tot) | |
1967 | print "Wall time: %.2f s" % wall_time |
|
1967 | print "Wall time: %.2f s" % wall_time | |
1968 | if tc > tc_min: |
|
1968 | if tc > tc_min: | |
1969 | print "Compiler : %.2f s" % tc |
|
1969 | print "Compiler : %.2f s" % tc | |
1970 | return out |
|
1970 | return out | |
1971 |
|
1971 | |||
1972 | @testdec.skip_doctest |
|
1972 | @testdec.skip_doctest | |
1973 | def magic_macro(self,parameter_s = ''): |
|
1973 | def magic_macro(self,parameter_s = ''): | |
1974 | """Define a set of input lines as a macro for future re-execution. |
|
1974 | """Define a set of input lines as a macro for future re-execution. | |
1975 |
|
1975 | |||
1976 | Usage:\\ |
|
1976 | Usage:\\ | |
1977 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1977 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... | |
1978 |
|
1978 | |||
1979 | Options: |
|
1979 | Options: | |
1980 |
|
1980 | |||
1981 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1981 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1982 | so that magics are loaded in their transformed version to valid |
|
1982 | so that magics are loaded in their transformed version to valid | |
1983 | Python. If this option is given, the raw input as typed as the |
|
1983 | Python. If this option is given, the raw input as typed as the | |
1984 | command line is used instead. |
|
1984 | command line is used instead. | |
1985 |
|
1985 | |||
1986 | This will define a global variable called `name` which is a string |
|
1986 | This will define a global variable called `name` which is a string | |
1987 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1987 | made of joining the slices and lines you specify (n1,n2,... numbers | |
1988 | above) from your input history into a single string. This variable |
|
1988 | above) from your input history into a single string. This variable | |
1989 | acts like an automatic function which re-executes those lines as if |
|
1989 | acts like an automatic function which re-executes those lines as if | |
1990 | you had typed them. You just type 'name' at the prompt and the code |
|
1990 | you had typed them. You just type 'name' at the prompt and the code | |
1991 | executes. |
|
1991 | executes. | |
1992 |
|
1992 | |||
1993 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
1993 | The notation for indicating number ranges is: n1-n2 means 'use line | |
1994 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
1994 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means | |
1995 | using the lines numbered 5,6 and 7. |
|
1995 | using the lines numbered 5,6 and 7. | |
1996 |
|
1996 | |||
1997 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1997 | Note: as a 'hidden' feature, you can also use traditional python slice | |
1998 | notation, where N:M means numbers N through M-1. |
|
1998 | notation, where N:M means numbers N through M-1. | |
1999 |
|
1999 | |||
2000 | For example, if your history contains (%hist prints it): |
|
2000 | For example, if your history contains (%hist prints it): | |
2001 |
|
2001 | |||
2002 | 44: x=1 |
|
2002 | 44: x=1 | |
2003 | 45: y=3 |
|
2003 | 45: y=3 | |
2004 | 46: z=x+y |
|
2004 | 46: z=x+y | |
2005 | 47: print x |
|
2005 | 47: print x | |
2006 | 48: a=5 |
|
2006 | 48: a=5 | |
2007 | 49: print 'x',x,'y',y |
|
2007 | 49: print 'x',x,'y',y | |
2008 |
|
2008 | |||
2009 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
2009 | you can create a macro with lines 44 through 47 (included) and line 49 | |
2010 | called my_macro with: |
|
2010 | called my_macro with: | |
2011 |
|
2011 | |||
2012 | In [55]: %macro my_macro 44-47 49 |
|
2012 | In [55]: %macro my_macro 44-47 49 | |
2013 |
|
2013 | |||
2014 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
2014 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
2015 | in one pass. |
|
2015 | in one pass. | |
2016 |
|
2016 | |||
2017 | You don't need to give the line-numbers in order, and any given line |
|
2017 | You don't need to give the line-numbers in order, and any given line | |
2018 | number can appear multiple times. You can assemble macros with any |
|
2018 | number can appear multiple times. You can assemble macros with any | |
2019 | lines from your input history in any order. |
|
2019 | lines from your input history in any order. | |
2020 |
|
2020 | |||
2021 | The macro is a simple object which holds its value in an attribute, |
|
2021 | The macro is a simple object which holds its value in an attribute, | |
2022 | but IPython's display system checks for macros and executes them as |
|
2022 | but IPython's display system checks for macros and executes them as | |
2023 | code instead of printing them when you type their name. |
|
2023 | code instead of printing them when you type their name. | |
2024 |
|
2024 | |||
2025 | You can view a macro's contents by explicitly printing it with: |
|
2025 | You can view a macro's contents by explicitly printing it with: | |
2026 |
|
2026 | |||
2027 | 'print macro_name'. |
|
2027 | 'print macro_name'. | |
2028 |
|
2028 | |||
2029 | For one-off cases which DON'T contain magic function calls in them you |
|
2029 | For one-off cases which DON'T contain magic function calls in them you | |
2030 | can obtain similar results by explicitly executing slices from your |
|
2030 | can obtain similar results by explicitly executing slices from your | |
2031 | input history with: |
|
2031 | input history with: | |
2032 |
|
2032 | |||
2033 | In [60]: exec In[44:48]+In[49]""" |
|
2033 | In [60]: exec In[44:48]+In[49]""" | |
2034 |
|
2034 | |||
2035 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2035 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2036 | if not args: |
|
2036 | if not args: | |
2037 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] |
|
2037 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] | |
2038 | macs.sort() |
|
2038 | macs.sort() | |
2039 | return macs |
|
2039 | return macs | |
2040 | if len(args) == 1: |
|
2040 | if len(args) == 1: | |
2041 | raise UsageError( |
|
2041 | raise UsageError( | |
2042 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
2042 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") | |
2043 | name,ranges = args[0], args[1:] |
|
2043 | name,ranges = args[0], args[1:] | |
2044 |
|
2044 | |||
2045 | #print 'rng',ranges # dbg |
|
2045 | #print 'rng',ranges # dbg | |
2046 | lines = self.extract_input_slices(ranges,opts.has_key('r')) |
|
2046 | lines = self.extract_input_slices(ranges,opts.has_key('r')) | |
2047 | macro = Macro(lines) |
|
2047 | macro = Macro(lines) | |
2048 | self.shell.define_macro(name, macro) |
|
2048 | self.shell.define_macro(name, macro) | |
2049 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
2049 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
2050 | print 'Macro contents:' |
|
2050 | print 'Macro contents:' | |
2051 | print macro, |
|
2051 | print macro, | |
2052 |
|
2052 | |||
2053 | def magic_save(self,parameter_s = ''): |
|
2053 | def magic_save(self,parameter_s = ''): | |
2054 | """Save a set of lines to a given filename. |
|
2054 | """Save a set of lines to a given filename. | |
2055 |
|
2055 | |||
2056 | Usage:\\ |
|
2056 | Usage:\\ | |
2057 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
2057 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
2058 |
|
2058 | |||
2059 | Options: |
|
2059 | Options: | |
2060 |
|
2060 | |||
2061 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2061 | -r: use 'raw' input. By default, the 'processed' history is used, | |
2062 | so that magics are loaded in their transformed version to valid |
|
2062 | so that magics are loaded in their transformed version to valid | |
2063 | Python. If this option is given, the raw input as typed as the |
|
2063 | Python. If this option is given, the raw input as typed as the | |
2064 | command line is used instead. |
|
2064 | command line is used instead. | |
2065 |
|
2065 | |||
2066 | This function uses the same syntax as %macro for line extraction, but |
|
2066 | This function uses the same syntax as %macro for line extraction, but | |
2067 | instead of creating a macro it saves the resulting string to the |
|
2067 | instead of creating a macro it saves the resulting string to the | |
2068 | filename you specify. |
|
2068 | filename you specify. | |
2069 |
|
2069 | |||
2070 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2070 | It adds a '.py' extension to the file if you don't do so yourself, and | |
2071 | it asks for confirmation before overwriting existing files.""" |
|
2071 | it asks for confirmation before overwriting existing files.""" | |
2072 |
|
2072 | |||
2073 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2073 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2074 | fname,ranges = args[0], args[1:] |
|
2074 | fname,ranges = args[0], args[1:] | |
2075 | if not fname.endswith('.py'): |
|
2075 | if not fname.endswith('.py'): | |
2076 | fname += '.py' |
|
2076 | fname += '.py' | |
2077 | if os.path.isfile(fname): |
|
2077 | if os.path.isfile(fname): | |
2078 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2078 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
2079 | if ans.lower() not in ['y','yes']: |
|
2079 | if ans.lower() not in ['y','yes']: | |
2080 | print 'Operation cancelled.' |
|
2080 | print 'Operation cancelled.' | |
2081 | return |
|
2081 | return | |
2082 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) |
|
2082 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) | |
2083 | f = file(fname,'w') |
|
2083 | f = file(fname,'w') | |
2084 | f.write(cmds) |
|
2084 | f.write(cmds) | |
2085 | f.close() |
|
2085 | f.close() | |
2086 | print 'The following commands were written to file `%s`:' % fname |
|
2086 | print 'The following commands were written to file `%s`:' % fname | |
2087 | print cmds |
|
2087 | print cmds | |
2088 |
|
2088 | |||
2089 | def _edit_macro(self,mname,macro): |
|
2089 | def _edit_macro(self,mname,macro): | |
2090 | """open an editor with the macro data in a file""" |
|
2090 | """open an editor with the macro data in a file""" | |
2091 | filename = self.shell.mktempfile(macro.value) |
|
2091 | filename = self.shell.mktempfile(macro.value) | |
2092 | self.shell.hooks.editor(filename) |
|
2092 | self.shell.hooks.editor(filename) | |
2093 |
|
2093 | |||
2094 | # and make a new macro object, to replace the old one |
|
2094 | # and make a new macro object, to replace the old one | |
2095 | mfile = open(filename) |
|
2095 | mfile = open(filename) | |
2096 | mvalue = mfile.read() |
|
2096 | mvalue = mfile.read() | |
2097 | mfile.close() |
|
2097 | mfile.close() | |
2098 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2098 | self.shell.user_ns[mname] = Macro(mvalue) | |
2099 |
|
2099 | |||
2100 | def magic_ed(self,parameter_s=''): |
|
2100 | def magic_ed(self,parameter_s=''): | |
2101 | """Alias to %edit.""" |
|
2101 | """Alias to %edit.""" | |
2102 | return self.magic_edit(parameter_s) |
|
2102 | return self.magic_edit(parameter_s) | |
2103 |
|
2103 | |||
2104 | @testdec.skip_doctest |
|
2104 | @testdec.skip_doctest | |
2105 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2105 | def magic_edit(self,parameter_s='',last_call=['','']): | |
2106 | """Bring up an editor and execute the resulting code. |
|
2106 | """Bring up an editor and execute the resulting code. | |
2107 |
|
2107 | |||
2108 | Usage: |
|
2108 | Usage: | |
2109 | %edit [options] [args] |
|
2109 | %edit [options] [args] | |
2110 |
|
2110 | |||
2111 | %edit runs IPython's editor hook. The default version of this hook is |
|
2111 | %edit runs IPython's editor hook. The default version of this hook is | |
2112 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
2112 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
2113 | environment variable $EDITOR. If this isn't found, it will default to |
|
2113 | environment variable $EDITOR. If this isn't found, it will default to | |
2114 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
2114 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
2115 | docstring for how to change the editor hook. |
|
2115 | docstring for how to change the editor hook. | |
2116 |
|
2116 | |||
2117 | You can also set the value of this editor via the command line option |
|
2117 | You can also set the value of this editor via the command line option | |
2118 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
2118 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
2119 | specifically for IPython an editor different from your typical default |
|
2119 | specifically for IPython an editor different from your typical default | |
2120 | (and for Windows users who typically don't set environment variables). |
|
2120 | (and for Windows users who typically don't set environment variables). | |
2121 |
|
2121 | |||
2122 | This command allows you to conveniently edit multi-line code right in |
|
2122 | This command allows you to conveniently edit multi-line code right in | |
2123 | your IPython session. |
|
2123 | your IPython session. | |
2124 |
|
2124 | |||
2125 | If called without arguments, %edit opens up an empty editor with a |
|
2125 | If called without arguments, %edit opens up an empty editor with a | |
2126 | temporary file and will execute the contents of this file when you |
|
2126 | temporary file and will execute the contents of this file when you | |
2127 | close it (don't forget to save it!). |
|
2127 | close it (don't forget to save it!). | |
2128 |
|
2128 | |||
2129 |
|
2129 | |||
2130 | Options: |
|
2130 | Options: | |
2131 |
|
2131 | |||
2132 | -n <number>: open the editor at a specified line number. By default, |
|
2132 | -n <number>: open the editor at a specified line number. By default, | |
2133 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2133 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
2134 | you can configure this by providing your own modified hook if your |
|
2134 | you can configure this by providing your own modified hook if your | |
2135 | favorite editor supports line-number specifications with a different |
|
2135 | favorite editor supports line-number specifications with a different | |
2136 | syntax. |
|
2136 | syntax. | |
2137 |
|
2137 | |||
2138 | -p: this will call the editor with the same data as the previous time |
|
2138 | -p: this will call the editor with the same data as the previous time | |
2139 | it was used, regardless of how long ago (in your current session) it |
|
2139 | it was used, regardless of how long ago (in your current session) it | |
2140 | was. |
|
2140 | was. | |
2141 |
|
2141 | |||
2142 | -r: use 'raw' input. This option only applies to input taken from the |
|
2142 | -r: use 'raw' input. This option only applies to input taken from the | |
2143 | user's history. By default, the 'processed' history is used, so that |
|
2143 | user's history. By default, the 'processed' history is used, so that | |
2144 | magics are loaded in their transformed version to valid Python. If |
|
2144 | magics are loaded in their transformed version to valid Python. If | |
2145 | this option is given, the raw input as typed as the command line is |
|
2145 | this option is given, the raw input as typed as the command line is | |
2146 | used instead. When you exit the editor, it will be executed by |
|
2146 | used instead. When you exit the editor, it will be executed by | |
2147 | IPython's own processor. |
|
2147 | IPython's own processor. | |
2148 |
|
2148 | |||
2149 | -x: do not execute the edited code immediately upon exit. This is |
|
2149 | -x: do not execute the edited code immediately upon exit. This is | |
2150 | mainly useful if you are editing programs which need to be called with |
|
2150 | mainly useful if you are editing programs which need to be called with | |
2151 | command line arguments, which you can then do using %run. |
|
2151 | command line arguments, which you can then do using %run. | |
2152 |
|
2152 | |||
2153 |
|
2153 | |||
2154 | Arguments: |
|
2154 | Arguments: | |
2155 |
|
2155 | |||
2156 | If arguments are given, the following possibilites exist: |
|
2156 | If arguments are given, the following possibilites exist: | |
2157 |
|
2157 | |||
2158 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
2158 | - The arguments are numbers or pairs of colon-separated numbers (like | |
2159 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
2159 | 1 4:8 9). These are interpreted as lines of previous input to be | |
2160 | loaded into the editor. The syntax is the same of the %macro command. |
|
2160 | loaded into the editor. The syntax is the same of the %macro command. | |
2161 |
|
2161 | |||
2162 | - If the argument doesn't start with a number, it is evaluated as a |
|
2162 | - If the argument doesn't start with a number, it is evaluated as a | |
2163 | variable and its contents loaded into the editor. You can thus edit |
|
2163 | variable and its contents loaded into the editor. You can thus edit | |
2164 | any string which contains python code (including the result of |
|
2164 | any string which contains python code (including the result of | |
2165 | previous edits). |
|
2165 | previous edits). | |
2166 |
|
2166 | |||
2167 | - If the argument is the name of an object (other than a string), |
|
2167 | - If the argument is the name of an object (other than a string), | |
2168 | IPython will try to locate the file where it was defined and open the |
|
2168 | IPython will try to locate the file where it was defined and open the | |
2169 | editor at the point where it is defined. You can use `%edit function` |
|
2169 | editor at the point where it is defined. You can use `%edit function` | |
2170 | to load an editor exactly at the point where 'function' is defined, |
|
2170 | to load an editor exactly at the point where 'function' is defined, | |
2171 | edit it and have the file be executed automatically. |
|
2171 | edit it and have the file be executed automatically. | |
2172 |
|
2172 | |||
2173 | If the object is a macro (see %macro for details), this opens up your |
|
2173 | If the object is a macro (see %macro for details), this opens up your | |
2174 | specified editor with a temporary file containing the macro's data. |
|
2174 | specified editor with a temporary file containing the macro's data. | |
2175 | Upon exit, the macro is reloaded with the contents of the file. |
|
2175 | Upon exit, the macro is reloaded with the contents of the file. | |
2176 |
|
2176 | |||
2177 | Note: opening at an exact line is only supported under Unix, and some |
|
2177 | Note: opening at an exact line is only supported under Unix, and some | |
2178 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2178 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
2179 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2179 | '+NUMBER' parameter necessary for this feature. Good editors like | |
2180 | (X)Emacs, vi, jed, pico and joe all do. |
|
2180 | (X)Emacs, vi, jed, pico and joe all do. | |
2181 |
|
2181 | |||
2182 | - If the argument is not found as a variable, IPython will look for a |
|
2182 | - If the argument is not found as a variable, IPython will look for a | |
2183 | file with that name (adding .py if necessary) and load it into the |
|
2183 | file with that name (adding .py if necessary) and load it into the | |
2184 | editor. It will execute its contents with execfile() when you exit, |
|
2184 | editor. It will execute its contents with execfile() when you exit, | |
2185 | loading any code in the file into your interactive namespace. |
|
2185 | loading any code in the file into your interactive namespace. | |
2186 |
|
2186 | |||
2187 | After executing your code, %edit will return as output the code you |
|
2187 | After executing your code, %edit will return as output the code you | |
2188 | typed in the editor (except when it was an existing file). This way |
|
2188 | typed in the editor (except when it was an existing file). This way | |
2189 | you can reload the code in further invocations of %edit as a variable, |
|
2189 | you can reload the code in further invocations of %edit as a variable, | |
2190 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2190 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
2191 | the output. |
|
2191 | the output. | |
2192 |
|
2192 | |||
2193 | Note that %edit is also available through the alias %ed. |
|
2193 | Note that %edit is also available through the alias %ed. | |
2194 |
|
2194 | |||
2195 | This is an example of creating a simple function inside the editor and |
|
2195 | This is an example of creating a simple function inside the editor and | |
2196 | then modifying it. First, start up the editor: |
|
2196 | then modifying it. First, start up the editor: | |
2197 |
|
2197 | |||
2198 | In [1]: ed |
|
2198 | In [1]: ed | |
2199 | Editing... done. Executing edited code... |
|
2199 | Editing... done. Executing edited code... | |
2200 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
2200 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' | |
2201 |
|
2201 | |||
2202 | We can then call the function foo(): |
|
2202 | We can then call the function foo(): | |
2203 |
|
2203 | |||
2204 | In [2]: foo() |
|
2204 | In [2]: foo() | |
2205 | foo() was defined in an editing session |
|
2205 | foo() was defined in an editing session | |
2206 |
|
2206 | |||
2207 | Now we edit foo. IPython automatically loads the editor with the |
|
2207 | Now we edit foo. IPython automatically loads the editor with the | |
2208 | (temporary) file where foo() was previously defined: |
|
2208 | (temporary) file where foo() was previously defined: | |
2209 |
|
2209 | |||
2210 | In [3]: ed foo |
|
2210 | In [3]: ed foo | |
2211 | Editing... done. Executing edited code... |
|
2211 | Editing... done. Executing edited code... | |
2212 |
|
2212 | |||
2213 | And if we call foo() again we get the modified version: |
|
2213 | And if we call foo() again we get the modified version: | |
2214 |
|
2214 | |||
2215 | In [4]: foo() |
|
2215 | In [4]: foo() | |
2216 | foo() has now been changed! |
|
2216 | foo() has now been changed! | |
2217 |
|
2217 | |||
2218 | Here is an example of how to edit a code snippet successive |
|
2218 | Here is an example of how to edit a code snippet successive | |
2219 | times. First we call the editor: |
|
2219 | times. First we call the editor: | |
2220 |
|
2220 | |||
2221 | In [5]: ed |
|
2221 | In [5]: ed | |
2222 | Editing... done. Executing edited code... |
|
2222 | Editing... done. Executing edited code... | |
2223 | hello |
|
2223 | hello | |
2224 | Out[5]: "print 'hello'n" |
|
2224 | Out[5]: "print 'hello'n" | |
2225 |
|
2225 | |||
2226 | Now we call it again with the previous output (stored in _): |
|
2226 | Now we call it again with the previous output (stored in _): | |
2227 |
|
2227 | |||
2228 | In [6]: ed _ |
|
2228 | In [6]: ed _ | |
2229 | Editing... done. Executing edited code... |
|
2229 | Editing... done. Executing edited code... | |
2230 | hello world |
|
2230 | hello world | |
2231 | Out[6]: "print 'hello world'n" |
|
2231 | Out[6]: "print 'hello world'n" | |
2232 |
|
2232 | |||
2233 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2233 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
2234 |
|
2234 | |||
2235 | In [7]: ed _8 |
|
2235 | In [7]: ed _8 | |
2236 | Editing... done. Executing edited code... |
|
2236 | Editing... done. Executing edited code... | |
2237 | hello again |
|
2237 | hello again | |
2238 | Out[7]: "print 'hello again'n" |
|
2238 | Out[7]: "print 'hello again'n" | |
2239 |
|
2239 | |||
2240 |
|
2240 | |||
2241 | Changing the default editor hook: |
|
2241 | Changing the default editor hook: | |
2242 |
|
2242 | |||
2243 | If you wish to write your own editor hook, you can put it in a |
|
2243 | If you wish to write your own editor hook, you can put it in a | |
2244 | configuration file which you load at startup time. The default hook |
|
2244 | configuration file which you load at startup time. The default hook | |
2245 | is defined in the IPython.core.hooks module, and you can use that as a |
|
2245 | is defined in the IPython.core.hooks module, and you can use that as a | |
2246 | starting example for further modifications. That file also has |
|
2246 | starting example for further modifications. That file also has | |
2247 | general instructions on how to set a new hook for use once you've |
|
2247 | general instructions on how to set a new hook for use once you've | |
2248 | defined it.""" |
|
2248 | defined it.""" | |
2249 |
|
2249 | |||
2250 | # FIXME: This function has become a convoluted mess. It needs a |
|
2250 | # FIXME: This function has become a convoluted mess. It needs a | |
2251 | # ground-up rewrite with clean, simple logic. |
|
2251 | # ground-up rewrite with clean, simple logic. | |
2252 |
|
2252 | |||
2253 | def make_filename(arg): |
|
2253 | def make_filename(arg): | |
2254 | "Make a filename from the given args" |
|
2254 | "Make a filename from the given args" | |
2255 | try: |
|
2255 | try: | |
2256 | filename = get_py_filename(arg) |
|
2256 | filename = get_py_filename(arg) | |
2257 | except IOError: |
|
2257 | except IOError: | |
2258 | if args.endswith('.py'): |
|
2258 | if args.endswith('.py'): | |
2259 | filename = arg |
|
2259 | filename = arg | |
2260 | else: |
|
2260 | else: | |
2261 | filename = None |
|
2261 | filename = None | |
2262 | return filename |
|
2262 | return filename | |
2263 |
|
2263 | |||
2264 | # custom exceptions |
|
2264 | # custom exceptions | |
2265 | class DataIsObject(Exception): pass |
|
2265 | class DataIsObject(Exception): pass | |
2266 |
|
2266 | |||
2267 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2267 | opts,args = self.parse_options(parameter_s,'prxn:') | |
2268 | # Set a few locals from the options for convenience: |
|
2268 | # Set a few locals from the options for convenience: | |
2269 | opts_p = opts.has_key('p') |
|
2269 | opts_p = opts.has_key('p') | |
2270 | opts_r = opts.has_key('r') |
|
2270 | opts_r = opts.has_key('r') | |
2271 |
|
2271 | |||
2272 | # Default line number value |
|
2272 | # Default line number value | |
2273 | lineno = opts.get('n',None) |
|
2273 | lineno = opts.get('n',None) | |
2274 |
|
2274 | |||
2275 | if opts_p: |
|
2275 | if opts_p: | |
2276 | args = '_%s' % last_call[0] |
|
2276 | args = '_%s' % last_call[0] | |
2277 | if not self.shell.user_ns.has_key(args): |
|
2277 | if not self.shell.user_ns.has_key(args): | |
2278 | args = last_call[1] |
|
2278 | args = last_call[1] | |
2279 |
|
2279 | |||
2280 | # use last_call to remember the state of the previous call, but don't |
|
2280 | # use last_call to remember the state of the previous call, but don't | |
2281 | # let it be clobbered by successive '-p' calls. |
|
2281 | # let it be clobbered by successive '-p' calls. | |
2282 | try: |
|
2282 | try: | |
2283 | last_call[0] = self.shell.displayhook.prompt_count |
|
2283 | last_call[0] = self.shell.displayhook.prompt_count | |
2284 | if not opts_p: |
|
2284 | if not opts_p: | |
2285 | last_call[1] = parameter_s |
|
2285 | last_call[1] = parameter_s | |
2286 | except: |
|
2286 | except: | |
2287 | pass |
|
2287 | pass | |
2288 |
|
2288 | |||
2289 | # by default this is done with temp files, except when the given |
|
2289 | # by default this is done with temp files, except when the given | |
2290 | # arg is a filename |
|
2290 | # arg is a filename | |
2291 | use_temp = 1 |
|
2291 | use_temp = 1 | |
2292 |
|
2292 | |||
2293 | if re.match(r'\d',args): |
|
2293 | if re.match(r'\d',args): | |
2294 | # Mode where user specifies ranges of lines, like in %macro. |
|
2294 | # Mode where user specifies ranges of lines, like in %macro. | |
2295 | # This means that you can't edit files whose names begin with |
|
2295 | # This means that you can't edit files whose names begin with | |
2296 | # numbers this way. Tough. |
|
2296 | # numbers this way. Tough. | |
2297 | ranges = args.split() |
|
2297 | ranges = args.split() | |
2298 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
2298 | data = ''.join(self.extract_input_slices(ranges,opts_r)) | |
2299 | elif args.endswith('.py'): |
|
2299 | elif args.endswith('.py'): | |
2300 | filename = make_filename(args) |
|
2300 | filename = make_filename(args) | |
2301 | data = '' |
|
2301 | data = '' | |
2302 | use_temp = 0 |
|
2302 | use_temp = 0 | |
2303 | elif args: |
|
2303 | elif args: | |
2304 | try: |
|
2304 | try: | |
2305 | # Load the parameter given as a variable. If not a string, |
|
2305 | # Load the parameter given as a variable. If not a string, | |
2306 | # process it as an object instead (below) |
|
2306 | # process it as an object instead (below) | |
2307 |
|
2307 | |||
2308 | #print '*** args',args,'type',type(args) # dbg |
|
2308 | #print '*** args',args,'type',type(args) # dbg | |
2309 | data = eval(args,self.shell.user_ns) |
|
2309 | data = eval(args,self.shell.user_ns) | |
2310 | if not type(data) in StringTypes: |
|
2310 | if not type(data) in StringTypes: | |
2311 | raise DataIsObject |
|
2311 | raise DataIsObject | |
2312 |
|
2312 | |||
2313 | except (NameError,SyntaxError): |
|
2313 | except (NameError,SyntaxError): | |
2314 | # given argument is not a variable, try as a filename |
|
2314 | # given argument is not a variable, try as a filename | |
2315 | filename = make_filename(args) |
|
2315 | filename = make_filename(args) | |
2316 | if filename is None: |
|
2316 | if filename is None: | |
2317 | warn("Argument given (%s) can't be found as a variable " |
|
2317 | warn("Argument given (%s) can't be found as a variable " | |
2318 | "or as a filename." % args) |
|
2318 | "or as a filename." % args) | |
2319 | return |
|
2319 | return | |
2320 |
|
2320 | |||
2321 | data = '' |
|
2321 | data = '' | |
2322 | use_temp = 0 |
|
2322 | use_temp = 0 | |
2323 | except DataIsObject: |
|
2323 | except DataIsObject: | |
2324 |
|
2324 | |||
2325 | # macros have a special edit function |
|
2325 | # macros have a special edit function | |
2326 | if isinstance(data,Macro): |
|
2326 | if isinstance(data,Macro): | |
2327 | self._edit_macro(args,data) |
|
2327 | self._edit_macro(args,data) | |
2328 | return |
|
2328 | return | |
2329 |
|
2329 | |||
2330 | # For objects, try to edit the file where they are defined |
|
2330 | # For objects, try to edit the file where they are defined | |
2331 | try: |
|
2331 | try: | |
2332 | filename = inspect.getabsfile(data) |
|
2332 | filename = inspect.getabsfile(data) | |
2333 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2333 | if 'fakemodule' in filename.lower() and inspect.isclass(data): | |
2334 | # class created by %edit? Try to find source |
|
2334 | # class created by %edit? Try to find source | |
2335 | # by looking for method definitions instead, the |
|
2335 | # by looking for method definitions instead, the | |
2336 | # __module__ in those classes is FakeModule. |
|
2336 | # __module__ in those classes is FakeModule. | |
2337 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2337 | attrs = [getattr(data, aname) for aname in dir(data)] | |
2338 | for attr in attrs: |
|
2338 | for attr in attrs: | |
2339 | if not inspect.ismethod(attr): |
|
2339 | if not inspect.ismethod(attr): | |
2340 | continue |
|
2340 | continue | |
2341 | filename = inspect.getabsfile(attr) |
|
2341 | filename = inspect.getabsfile(attr) | |
2342 | if filename and 'fakemodule' not in filename.lower(): |
|
2342 | if filename and 'fakemodule' not in filename.lower(): | |
2343 | # change the attribute to be the edit target instead |
|
2343 | # change the attribute to be the edit target instead | |
2344 | data = attr |
|
2344 | data = attr | |
2345 | break |
|
2345 | break | |
2346 |
|
2346 | |||
2347 | datafile = 1 |
|
2347 | datafile = 1 | |
2348 | except TypeError: |
|
2348 | except TypeError: | |
2349 | filename = make_filename(args) |
|
2349 | filename = make_filename(args) | |
2350 | datafile = 1 |
|
2350 | datafile = 1 | |
2351 | warn('Could not find file where `%s` is defined.\n' |
|
2351 | warn('Could not find file where `%s` is defined.\n' | |
2352 | 'Opening a file named `%s`' % (args,filename)) |
|
2352 | 'Opening a file named `%s`' % (args,filename)) | |
2353 | # Now, make sure we can actually read the source (if it was in |
|
2353 | # Now, make sure we can actually read the source (if it was in | |
2354 | # a temp file it's gone by now). |
|
2354 | # a temp file it's gone by now). | |
2355 | if datafile: |
|
2355 | if datafile: | |
2356 | try: |
|
2356 | try: | |
2357 | if lineno is None: |
|
2357 | if lineno is None: | |
2358 | lineno = inspect.getsourcelines(data)[1] |
|
2358 | lineno = inspect.getsourcelines(data)[1] | |
2359 | except IOError: |
|
2359 | except IOError: | |
2360 | filename = make_filename(args) |
|
2360 | filename = make_filename(args) | |
2361 | if filename is None: |
|
2361 | if filename is None: | |
2362 | warn('The file `%s` where `%s` was defined cannot ' |
|
2362 | warn('The file `%s` where `%s` was defined cannot ' | |
2363 | 'be read.' % (filename,data)) |
|
2363 | 'be read.' % (filename,data)) | |
2364 | return |
|
2364 | return | |
2365 | use_temp = 0 |
|
2365 | use_temp = 0 | |
2366 | else: |
|
2366 | else: | |
2367 | data = '' |
|
2367 | data = '' | |
2368 |
|
2368 | |||
2369 | if use_temp: |
|
2369 | if use_temp: | |
2370 | filename = self.shell.mktempfile(data) |
|
2370 | filename = self.shell.mktempfile(data) | |
2371 | print 'IPython will make a temporary file named:',filename |
|
2371 | print 'IPython will make a temporary file named:',filename | |
2372 |
|
2372 | |||
2373 | # do actual editing here |
|
2373 | # do actual editing here | |
2374 | print 'Editing...', |
|
2374 | print 'Editing...', | |
2375 | sys.stdout.flush() |
|
2375 | sys.stdout.flush() | |
2376 | try: |
|
2376 | try: | |
2377 | # Quote filenames that may have spaces in them |
|
2377 | # Quote filenames that may have spaces in them | |
2378 | if ' ' in filename: |
|
2378 | if ' ' in filename: | |
2379 | filename = "%s" % filename |
|
2379 | filename = "%s" % filename | |
2380 | self.shell.hooks.editor(filename,lineno) |
|
2380 | self.shell.hooks.editor(filename,lineno) | |
2381 | except TryNext: |
|
2381 | except TryNext: | |
2382 | warn('Could not open editor') |
|
2382 | warn('Could not open editor') | |
2383 | return |
|
2383 | return | |
2384 |
|
2384 | |||
2385 | # XXX TODO: should this be generalized for all string vars? |
|
2385 | # XXX TODO: should this be generalized for all string vars? | |
2386 | # For now, this is special-cased to blocks created by cpaste |
|
2386 | # For now, this is special-cased to blocks created by cpaste | |
2387 | if args.strip() == 'pasted_block': |
|
2387 | if args.strip() == 'pasted_block': | |
2388 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
2388 | self.shell.user_ns['pasted_block'] = file_read(filename) | |
2389 |
|
2389 | |||
2390 | if opts.has_key('x'): # -x prevents actual execution |
|
2390 | if opts.has_key('x'): # -x prevents actual execution | |
2391 |
|
2391 | |||
2392 | else: |
|
2392 | else: | |
2393 | print 'done. Executing edited code...' |
|
2393 | print 'done. Executing edited code...' | |
2394 | if opts_r: |
|
2394 | if opts_r: | |
2395 | self.shell.run_cell(file_read(filename)) |
|
2395 | self.shell.run_cell(file_read(filename)) | |
2396 | else: |
|
2396 | else: | |
2397 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2397 | self.shell.safe_execfile(filename,self.shell.user_ns, | |
2398 | self.shell.user_ns) |
|
2398 | self.shell.user_ns) | |
2399 |
|
2399 | |||
2400 |
|
2400 | |||
2401 | if use_temp: |
|
2401 | if use_temp: | |
2402 | try: |
|
2402 | try: | |
2403 | return open(filename).read() |
|
2403 | return open(filename).read() | |
2404 | except IOError,msg: |
|
2404 | except IOError,msg: | |
2405 | if msg.filename == filename: |
|
2405 | if msg.filename == filename: | |
2406 | warn('File not found. Did you forget to save?') |
|
2406 | warn('File not found. Did you forget to save?') | |
2407 | return |
|
2407 | return | |
2408 | else: |
|
2408 | else: | |
2409 | self.shell.showtraceback() |
|
2409 | self.shell.showtraceback() | |
2410 |
|
2410 | |||
2411 | def magic_xmode(self,parameter_s = ''): |
|
2411 | def magic_xmode(self,parameter_s = ''): | |
2412 | """Switch modes for the exception handlers. |
|
2412 | """Switch modes for the exception handlers. | |
2413 |
|
2413 | |||
2414 | Valid modes: Plain, Context and Verbose. |
|
2414 | Valid modes: Plain, Context and Verbose. | |
2415 |
|
2415 | |||
2416 | If called without arguments, acts as a toggle.""" |
|
2416 | If called without arguments, acts as a toggle.""" | |
2417 |
|
2417 | |||
2418 | def xmode_switch_err(name): |
|
2418 | def xmode_switch_err(name): | |
2419 | warn('Error changing %s exception modes.\n%s' % |
|
2419 | warn('Error changing %s exception modes.\n%s' % | |
2420 | (name,sys.exc_info()[1])) |
|
2420 | (name,sys.exc_info()[1])) | |
2421 |
|
2421 | |||
2422 | shell = self.shell |
|
2422 | shell = self.shell | |
2423 | new_mode = parameter_s.strip().capitalize() |
|
2423 | new_mode = parameter_s.strip().capitalize() | |
2424 | try: |
|
2424 | try: | |
2425 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2425 | shell.InteractiveTB.set_mode(mode=new_mode) | |
2426 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2426 | print 'Exception reporting mode:',shell.InteractiveTB.mode | |
2427 | except: |
|
2427 | except: | |
2428 | xmode_switch_err('user') |
|
2428 | xmode_switch_err('user') | |
2429 |
|
2429 | |||
2430 | def magic_colors(self,parameter_s = ''): |
|
2430 | def magic_colors(self,parameter_s = ''): | |
2431 | """Switch color scheme for prompts, info system and exception handlers. |
|
2431 | """Switch color scheme for prompts, info system and exception handlers. | |
2432 |
|
2432 | |||
2433 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2433 | Currently implemented schemes: NoColor, Linux, LightBG. | |
2434 |
|
2434 | |||
2435 | Color scheme names are not case-sensitive. |
|
2435 | Color scheme names are not case-sensitive. | |
2436 |
|
2436 | |||
2437 | Examples |
|
2437 | Examples | |
2438 | -------- |
|
2438 | -------- | |
2439 | To get a plain black and white terminal:: |
|
2439 | To get a plain black and white terminal:: | |
2440 |
|
2440 | |||
2441 | %colors nocolor |
|
2441 | %colors nocolor | |
2442 | """ |
|
2442 | """ | |
2443 |
|
2443 | |||
2444 | def color_switch_err(name): |
|
2444 | def color_switch_err(name): | |
2445 | warn('Error changing %s color schemes.\n%s' % |
|
2445 | warn('Error changing %s color schemes.\n%s' % | |
2446 | (name,sys.exc_info()[1])) |
|
2446 | (name,sys.exc_info()[1])) | |
2447 |
|
2447 | |||
2448 |
|
2448 | |||
2449 | new_scheme = parameter_s.strip() |
|
2449 | new_scheme = parameter_s.strip() | |
2450 | if not new_scheme: |
|
2450 | if not new_scheme: | |
2451 | raise UsageError( |
|
2451 | raise UsageError( | |
2452 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2452 | "%colors: you must specify a color scheme. See '%colors?'") | |
2453 | return |
|
2453 | return | |
2454 | # local shortcut |
|
2454 | # local shortcut | |
2455 | shell = self.shell |
|
2455 | shell = self.shell | |
2456 |
|
2456 | |||
2457 | import IPython.utils.rlineimpl as readline |
|
2457 | import IPython.utils.rlineimpl as readline | |
2458 |
|
2458 | |||
2459 | if not readline.have_readline and sys.platform == "win32": |
|
2459 | if not readline.have_readline and sys.platform == "win32": | |
2460 | msg = """\ |
|
2460 | msg = """\ | |
2461 | Proper color support under MS Windows requires the pyreadline library. |
|
2461 | Proper color support under MS Windows requires the pyreadline library. | |
2462 | You can find it at: |
|
2462 | You can find it at: | |
2463 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2463 | http://ipython.scipy.org/moin/PyReadline/Intro | |
2464 | Gary's readline needs the ctypes module, from: |
|
2464 | Gary's readline needs the ctypes module, from: | |
2465 | http://starship.python.net/crew/theller/ctypes |
|
2465 | http://starship.python.net/crew/theller/ctypes | |
2466 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2466 | (Note that ctypes is already part of Python versions 2.5 and newer). | |
2467 |
|
2467 | |||
2468 | Defaulting color scheme to 'NoColor'""" |
|
2468 | Defaulting color scheme to 'NoColor'""" | |
2469 | new_scheme = 'NoColor' |
|
2469 | new_scheme = 'NoColor' | |
2470 | warn(msg) |
|
2470 | warn(msg) | |
2471 |
|
2471 | |||
2472 | # readline option is 0 |
|
2472 | # readline option is 0 | |
2473 | if not shell.has_readline: |
|
2473 | if not shell.has_readline: | |
2474 | new_scheme = 'NoColor' |
|
2474 | new_scheme = 'NoColor' | |
2475 |
|
2475 | |||
2476 | # Set prompt colors |
|
2476 | # Set prompt colors | |
2477 | try: |
|
2477 | try: | |
2478 | shell.displayhook.set_colors(new_scheme) |
|
2478 | shell.displayhook.set_colors(new_scheme) | |
2479 | except: |
|
2479 | except: | |
2480 | color_switch_err('prompt') |
|
2480 | color_switch_err('prompt') | |
2481 | else: |
|
2481 | else: | |
2482 | shell.colors = \ |
|
2482 | shell.colors = \ | |
2483 | shell.displayhook.color_table.active_scheme_name |
|
2483 | shell.displayhook.color_table.active_scheme_name | |
2484 | # Set exception colors |
|
2484 | # Set exception colors | |
2485 | try: |
|
2485 | try: | |
2486 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2486 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
2487 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2487 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
2488 | except: |
|
2488 | except: | |
2489 | color_switch_err('exception') |
|
2489 | color_switch_err('exception') | |
2490 |
|
2490 | |||
2491 | # Set info (for 'object?') colors |
|
2491 | # Set info (for 'object?') colors | |
2492 | if shell.color_info: |
|
2492 | if shell.color_info: | |
2493 | try: |
|
2493 | try: | |
2494 | shell.inspector.set_active_scheme(new_scheme) |
|
2494 | shell.inspector.set_active_scheme(new_scheme) | |
2495 | except: |
|
2495 | except: | |
2496 | color_switch_err('object inspector') |
|
2496 | color_switch_err('object inspector') | |
2497 | else: |
|
2497 | else: | |
2498 | shell.inspector.set_active_scheme('NoColor') |
|
2498 | shell.inspector.set_active_scheme('NoColor') | |
2499 |
|
2499 | |||
2500 | def magic_pprint(self, parameter_s=''): |
|
2500 | def magic_pprint(self, parameter_s=''): | |
2501 | """Toggle pretty printing on/off.""" |
|
2501 | """Toggle pretty printing on/off.""" | |
2502 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
2502 | ptformatter = self.shell.display_formatter.formatters['text/plain'] | |
2503 | ptformatter.pprint = bool(1 - ptformatter.pprint) |
|
2503 | ptformatter.pprint = bool(1 - ptformatter.pprint) | |
2504 | print 'Pretty printing has been turned', \ |
|
2504 | print 'Pretty printing has been turned', \ | |
2505 | ['OFF','ON'][ptformatter.pprint] |
|
2505 | ['OFF','ON'][ptformatter.pprint] | |
2506 |
|
2506 | |||
2507 | def magic_Exit(self, parameter_s=''): |
|
2507 | def magic_Exit(self, parameter_s=''): | |
2508 | """Exit IPython.""" |
|
2508 | """Exit IPython.""" | |
2509 |
|
2509 | |||
2510 | self.shell.ask_exit() |
|
2510 | self.shell.ask_exit() | |
2511 |
|
2511 | |||
2512 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. |
|
2512 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. | |
2513 | magic_exit = magic_quit = magic_Quit = magic_Exit |
|
2513 | magic_exit = magic_quit = magic_Quit = magic_Exit | |
2514 |
|
2514 | |||
2515 | #...................................................................... |
|
2515 | #...................................................................... | |
2516 | # Functions to implement unix shell-type things |
|
2516 | # Functions to implement unix shell-type things | |
2517 |
|
2517 | |||
2518 | @testdec.skip_doctest |
|
2518 | @testdec.skip_doctest | |
2519 | def magic_alias(self, parameter_s = ''): |
|
2519 | def magic_alias(self, parameter_s = ''): | |
2520 | """Define an alias for a system command. |
|
2520 | """Define an alias for a system command. | |
2521 |
|
2521 | |||
2522 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2522 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
2523 |
|
2523 | |||
2524 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2524 | Then, typing 'alias_name params' will execute the system command 'cmd | |
2525 | params' (from your underlying operating system). |
|
2525 | params' (from your underlying operating system). | |
2526 |
|
2526 | |||
2527 | Aliases have lower precedence than magic functions and Python normal |
|
2527 | Aliases have lower precedence than magic functions and Python normal | |
2528 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2528 | variables, so if 'foo' is both a Python variable and an alias, the | |
2529 | alias can not be executed until 'del foo' removes the Python variable. |
|
2529 | alias can not be executed until 'del foo' removes the Python variable. | |
2530 |
|
2530 | |||
2531 | You can use the %l specifier in an alias definition to represent the |
|
2531 | You can use the %l specifier in an alias definition to represent the | |
2532 | whole line when the alias is called. For example: |
|
2532 | whole line when the alias is called. For example: | |
2533 |
|
2533 | |||
2534 | In [2]: alias bracket echo "Input in brackets: <%l>" |
|
2534 | In [2]: alias bracket echo "Input in brackets: <%l>" | |
2535 | In [3]: bracket hello world |
|
2535 | In [3]: bracket hello world | |
2536 | Input in brackets: <hello world> |
|
2536 | Input in brackets: <hello world> | |
2537 |
|
2537 | |||
2538 | You can also define aliases with parameters using %s specifiers (one |
|
2538 | You can also define aliases with parameters using %s specifiers (one | |
2539 | per parameter): |
|
2539 | per parameter): | |
2540 |
|
2540 | |||
2541 | In [1]: alias parts echo first %s second %s |
|
2541 | In [1]: alias parts echo first %s second %s | |
2542 | In [2]: %parts A B |
|
2542 | In [2]: %parts A B | |
2543 | first A second B |
|
2543 | first A second B | |
2544 | In [3]: %parts A |
|
2544 | In [3]: %parts A | |
2545 | Incorrect number of arguments: 2 expected. |
|
2545 | Incorrect number of arguments: 2 expected. | |
2546 | parts is an alias to: 'echo first %s second %s' |
|
2546 | parts is an alias to: 'echo first %s second %s' | |
2547 |
|
2547 | |||
2548 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2548 | Note that %l and %s are mutually exclusive. You can only use one or | |
2549 | the other in your aliases. |
|
2549 | the other in your aliases. | |
2550 |
|
2550 | |||
2551 | Aliases expand Python variables just like system calls using ! or !! |
|
2551 | Aliases expand Python variables just like system calls using ! or !! | |
2552 | do: all expressions prefixed with '$' get expanded. For details of |
|
2552 | do: all expressions prefixed with '$' get expanded. For details of | |
2553 | the semantic rules, see PEP-215: |
|
2553 | the semantic rules, see PEP-215: | |
2554 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2554 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
2555 | IPython for variable expansion. If you want to access a true shell |
|
2555 | IPython for variable expansion. If you want to access a true shell | |
2556 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2556 | variable, an extra $ is necessary to prevent its expansion by IPython: | |
2557 |
|
2557 | |||
2558 | In [6]: alias show echo |
|
2558 | In [6]: alias show echo | |
2559 | In [7]: PATH='A Python string' |
|
2559 | In [7]: PATH='A Python string' | |
2560 | In [8]: show $PATH |
|
2560 | In [8]: show $PATH | |
2561 | A Python string |
|
2561 | A Python string | |
2562 | In [9]: show $$PATH |
|
2562 | In [9]: show $$PATH | |
2563 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2563 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
2564 |
|
2564 | |||
2565 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2565 | You can use the alias facility to acess all of $PATH. See the %rehash | |
2566 | and %rehashx functions, which automatically create aliases for the |
|
2566 | and %rehashx functions, which automatically create aliases for the | |
2567 | contents of your $PATH. |
|
2567 | contents of your $PATH. | |
2568 |
|
2568 | |||
2569 | If called with no parameters, %alias prints the current alias table.""" |
|
2569 | If called with no parameters, %alias prints the current alias table.""" | |
2570 |
|
2570 | |||
2571 | par = parameter_s.strip() |
|
2571 | par = parameter_s.strip() | |
2572 | if not par: |
|
2572 | if not par: | |
2573 | stored = self.db.get('stored_aliases', {} ) |
|
2573 | stored = self.db.get('stored_aliases', {} ) | |
2574 | aliases = sorted(self.shell.alias_manager.aliases) |
|
2574 | aliases = sorted(self.shell.alias_manager.aliases) | |
2575 | # for k, v in stored: |
|
2575 | # for k, v in stored: | |
2576 | # atab.append(k, v[0]) |
|
2576 | # atab.append(k, v[0]) | |
2577 |
|
2577 | |||
2578 | print "Total number of aliases:", len(aliases) |
|
2578 | print "Total number of aliases:", len(aliases) | |
2579 | sys.stdout.flush() |
|
2579 | sys.stdout.flush() | |
2580 | return aliases |
|
2580 | return aliases | |
2581 |
|
2581 | |||
2582 | # Now try to define a new one |
|
2582 | # Now try to define a new one | |
2583 | try: |
|
2583 | try: | |
2584 | alias,cmd = par.split(None, 1) |
|
2584 | alias,cmd = par.split(None, 1) | |
2585 | except: |
|
2585 | except: | |
2586 | print oinspect.getdoc(self.magic_alias) |
|
2586 | print oinspect.getdoc(self.magic_alias) | |
2587 | else: |
|
2587 | else: | |
2588 | self.shell.alias_manager.soft_define_alias(alias, cmd) |
|
2588 | self.shell.alias_manager.soft_define_alias(alias, cmd) | |
2589 | # end magic_alias |
|
2589 | # end magic_alias | |
2590 |
|
2590 | |||
2591 | def magic_unalias(self, parameter_s = ''): |
|
2591 | def magic_unalias(self, parameter_s = ''): | |
2592 | """Remove an alias""" |
|
2592 | """Remove an alias""" | |
2593 |
|
2593 | |||
2594 | aname = parameter_s.strip() |
|
2594 | aname = parameter_s.strip() | |
2595 | self.shell.alias_manager.undefine_alias(aname) |
|
2595 | self.shell.alias_manager.undefine_alias(aname) | |
2596 | stored = self.db.get('stored_aliases', {} ) |
|
2596 | stored = self.db.get('stored_aliases', {} ) | |
2597 | if aname in stored: |
|
2597 | if aname in stored: | |
2598 | print "Removing %stored alias",aname |
|
2598 | print "Removing %stored alias",aname | |
2599 | del stored[aname] |
|
2599 | del stored[aname] | |
2600 | self.db['stored_aliases'] = stored |
|
2600 | self.db['stored_aliases'] = stored | |
2601 |
|
2601 | |||
2602 | def magic_rehashx(self, parameter_s = ''): |
|
2602 | def magic_rehashx(self, parameter_s = ''): | |
2603 | """Update the alias table with all executable files in $PATH. |
|
2603 | """Update the alias table with all executable files in $PATH. | |
2604 |
|
2604 | |||
2605 | This version explicitly checks that every entry in $PATH is a file |
|
2605 | This version explicitly checks that every entry in $PATH is a file | |
2606 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2606 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2607 |
|
2607 | |||
2608 | Under Windows, it checks executability as a match agains a |
|
2608 | Under Windows, it checks executability as a match agains a | |
2609 | '|'-separated string of extensions, stored in the IPython config |
|
2609 | '|'-separated string of extensions, stored in the IPython config | |
2610 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2610 | variable win_exec_ext. This defaults to 'exe|com|bat'. | |
2611 |
|
2611 | |||
2612 | This function also resets the root module cache of module completer, |
|
2612 | This function also resets the root module cache of module completer, | |
2613 | used on slow filesystems. |
|
2613 | used on slow filesystems. | |
2614 | """ |
|
2614 | """ | |
2615 | from IPython.core.alias import InvalidAliasError |
|
2615 | from IPython.core.alias import InvalidAliasError | |
2616 |
|
2616 | |||
2617 | # for the benefit of module completer in ipy_completers.py |
|
2617 | # for the benefit of module completer in ipy_completers.py | |
2618 | del self.db['rootmodules'] |
|
2618 | del self.db['rootmodules'] | |
2619 |
|
2619 | |||
2620 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2620 | path = [os.path.abspath(os.path.expanduser(p)) for p in | |
2621 | os.environ.get('PATH','').split(os.pathsep)] |
|
2621 | os.environ.get('PATH','').split(os.pathsep)] | |
2622 | path = filter(os.path.isdir,path) |
|
2622 | path = filter(os.path.isdir,path) | |
2623 |
|
2623 | |||
2624 | syscmdlist = [] |
|
2624 | syscmdlist = [] | |
2625 | # Now define isexec in a cross platform manner. |
|
2625 | # Now define isexec in a cross platform manner. | |
2626 | if os.name == 'posix': |
|
2626 | if os.name == 'posix': | |
2627 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2627 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2628 | os.access(fname,os.X_OK) |
|
2628 | os.access(fname,os.X_OK) | |
2629 | else: |
|
2629 | else: | |
2630 | try: |
|
2630 | try: | |
2631 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2631 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2632 | except KeyError: |
|
2632 | except KeyError: | |
2633 | winext = 'exe|com|bat|py' |
|
2633 | winext = 'exe|com|bat|py' | |
2634 | if 'py' not in winext: |
|
2634 | if 'py' not in winext: | |
2635 | winext += '|py' |
|
2635 | winext += '|py' | |
2636 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2636 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2637 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2637 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2638 | savedir = os.getcwd() |
|
2638 | savedir = os.getcwd() | |
2639 |
|
2639 | |||
2640 | # Now walk the paths looking for executables to alias. |
|
2640 | # Now walk the paths looking for executables to alias. | |
2641 | try: |
|
2641 | try: | |
2642 | # write the whole loop for posix/Windows so we don't have an if in |
|
2642 | # write the whole loop for posix/Windows so we don't have an if in | |
2643 | # the innermost part |
|
2643 | # the innermost part | |
2644 | if os.name == 'posix': |
|
2644 | if os.name == 'posix': | |
2645 | for pdir in path: |
|
2645 | for pdir in path: | |
2646 | os.chdir(pdir) |
|
2646 | os.chdir(pdir) | |
2647 | for ff in os.listdir(pdir): |
|
2647 | for ff in os.listdir(pdir): | |
2648 | if isexec(ff): |
|
2648 | if isexec(ff): | |
2649 | try: |
|
2649 | try: | |
2650 | # Removes dots from the name since ipython |
|
2650 | # Removes dots from the name since ipython | |
2651 | # will assume names with dots to be python. |
|
2651 | # will assume names with dots to be python. | |
2652 | self.shell.alias_manager.define_alias( |
|
2652 | self.shell.alias_manager.define_alias( | |
2653 | ff.replace('.',''), ff) |
|
2653 | ff.replace('.',''), ff) | |
2654 | except InvalidAliasError: |
|
2654 | except InvalidAliasError: | |
2655 | pass |
|
2655 | pass | |
2656 | else: |
|
2656 | else: | |
2657 | syscmdlist.append(ff) |
|
2657 | syscmdlist.append(ff) | |
2658 | else: |
|
2658 | else: | |
2659 | no_alias = self.shell.alias_manager.no_alias |
|
2659 | no_alias = self.shell.alias_manager.no_alias | |
2660 | for pdir in path: |
|
2660 | for pdir in path: | |
2661 | os.chdir(pdir) |
|
2661 | os.chdir(pdir) | |
2662 | for ff in os.listdir(pdir): |
|
2662 | for ff in os.listdir(pdir): | |
2663 | base, ext = os.path.splitext(ff) |
|
2663 | base, ext = os.path.splitext(ff) | |
2664 | if isexec(ff) and base.lower() not in no_alias: |
|
2664 | if isexec(ff) and base.lower() not in no_alias: | |
2665 | if ext.lower() == '.exe': |
|
2665 | if ext.lower() == '.exe': | |
2666 | ff = base |
|
2666 | ff = base | |
2667 | try: |
|
2667 | try: | |
2668 | # Removes dots from the name since ipython |
|
2668 | # Removes dots from the name since ipython | |
2669 | # will assume names with dots to be python. |
|
2669 | # will assume names with dots to be python. | |
2670 | self.shell.alias_manager.define_alias( |
|
2670 | self.shell.alias_manager.define_alias( | |
2671 | base.lower().replace('.',''), ff) |
|
2671 | base.lower().replace('.',''), ff) | |
2672 | except InvalidAliasError: |
|
2672 | except InvalidAliasError: | |
2673 | pass |
|
2673 | pass | |
2674 | syscmdlist.append(ff) |
|
2674 | syscmdlist.append(ff) | |
2675 | db = self.db |
|
2675 | db = self.db | |
2676 | db['syscmdlist'] = syscmdlist |
|
2676 | db['syscmdlist'] = syscmdlist | |
2677 | finally: |
|
2677 | finally: | |
2678 | os.chdir(savedir) |
|
2678 | os.chdir(savedir) | |
2679 |
|
2679 | |||
2680 | @testdec.skip_doctest |
|
2680 | @testdec.skip_doctest | |
2681 | def magic_pwd(self, parameter_s = ''): |
|
2681 | def magic_pwd(self, parameter_s = ''): | |
2682 | """Return the current working directory path. |
|
2682 | """Return the current working directory path. | |
2683 |
|
2683 | |||
2684 | Examples |
|
2684 | Examples | |
2685 | -------- |
|
2685 | -------- | |
2686 | :: |
|
2686 | :: | |
2687 |
|
2687 | |||
2688 | In [9]: pwd |
|
2688 | In [9]: pwd | |
2689 | Out[9]: '/home/tsuser/sprint/ipython' |
|
2689 | Out[9]: '/home/tsuser/sprint/ipython' | |
2690 | """ |
|
2690 | """ | |
2691 | return os.getcwd() |
|
2691 | return os.getcwd() | |
2692 |
|
2692 | |||
2693 | @testdec.skip_doctest |
|
2693 | @testdec.skip_doctest | |
2694 | def magic_cd(self, parameter_s=''): |
|
2694 | def magic_cd(self, parameter_s=''): | |
2695 | """Change the current working directory. |
|
2695 | """Change the current working directory. | |
2696 |
|
2696 | |||
2697 | This command automatically maintains an internal list of directories |
|
2697 | This command automatically maintains an internal list of directories | |
2698 | you visit during your IPython session, in the variable _dh. The |
|
2698 | you visit during your IPython session, in the variable _dh. The | |
2699 | command %dhist shows this history nicely formatted. You can also |
|
2699 | command %dhist shows this history nicely formatted. You can also | |
2700 | do 'cd -<tab>' to see directory history conveniently. |
|
2700 | do 'cd -<tab>' to see directory history conveniently. | |
2701 |
|
2701 | |||
2702 | Usage: |
|
2702 | Usage: | |
2703 |
|
2703 | |||
2704 | cd 'dir': changes to directory 'dir'. |
|
2704 | cd 'dir': changes to directory 'dir'. | |
2705 |
|
2705 | |||
2706 | cd -: changes to the last visited directory. |
|
2706 | cd -: changes to the last visited directory. | |
2707 |
|
2707 | |||
2708 | cd -<n>: changes to the n-th directory in the directory history. |
|
2708 | cd -<n>: changes to the n-th directory in the directory history. | |
2709 |
|
2709 | |||
2710 | cd --foo: change to directory that matches 'foo' in history |
|
2710 | cd --foo: change to directory that matches 'foo' in history | |
2711 |
|
2711 | |||
2712 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2712 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
2713 | (note: cd <bookmark_name> is enough if there is no |
|
2713 | (note: cd <bookmark_name> is enough if there is no | |
2714 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2714 | directory <bookmark_name>, but a bookmark with the name exists.) | |
2715 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2715 | 'cd -b <tab>' allows you to tab-complete bookmark names. | |
2716 |
|
2716 | |||
2717 | Options: |
|
2717 | Options: | |
2718 |
|
2718 | |||
2719 | -q: quiet. Do not print the working directory after the cd command is |
|
2719 | -q: quiet. Do not print the working directory after the cd command is | |
2720 | executed. By default IPython's cd command does print this directory, |
|
2720 | executed. By default IPython's cd command does print this directory, | |
2721 | since the default prompts do not display path information. |
|
2721 | since the default prompts do not display path information. | |
2722 |
|
2722 | |||
2723 | Note that !cd doesn't work for this purpose because the shell where |
|
2723 | Note that !cd doesn't work for this purpose because the shell where | |
2724 | !command runs is immediately discarded after executing 'command'. |
|
2724 | !command runs is immediately discarded after executing 'command'. | |
2725 |
|
2725 | |||
2726 | Examples |
|
2726 | Examples | |
2727 | -------- |
|
2727 | -------- | |
2728 | :: |
|
2728 | :: | |
2729 |
|
2729 | |||
2730 | In [10]: cd parent/child |
|
2730 | In [10]: cd parent/child | |
2731 | /home/tsuser/parent/child |
|
2731 | /home/tsuser/parent/child | |
2732 | """ |
|
2732 | """ | |
2733 |
|
2733 | |||
2734 | parameter_s = parameter_s.strip() |
|
2734 | parameter_s = parameter_s.strip() | |
2735 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2735 | #bkms = self.shell.persist.get("bookmarks",{}) | |
2736 |
|
2736 | |||
2737 | oldcwd = os.getcwd() |
|
2737 | oldcwd = os.getcwd() | |
2738 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2738 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
2739 | # jump in directory history by number |
|
2739 | # jump in directory history by number | |
2740 | if numcd: |
|
2740 | if numcd: | |
2741 | nn = int(numcd.group(2)) |
|
2741 | nn = int(numcd.group(2)) | |
2742 | try: |
|
2742 | try: | |
2743 | ps = self.shell.user_ns['_dh'][nn] |
|
2743 | ps = self.shell.user_ns['_dh'][nn] | |
2744 | except IndexError: |
|
2744 | except IndexError: | |
2745 | print 'The requested directory does not exist in history.' |
|
2745 | print 'The requested directory does not exist in history.' | |
2746 | return |
|
2746 | return | |
2747 | else: |
|
2747 | else: | |
2748 | opts = {} |
|
2748 | opts = {} | |
2749 | elif parameter_s.startswith('--'): |
|
2749 | elif parameter_s.startswith('--'): | |
2750 | ps = None |
|
2750 | ps = None | |
2751 | fallback = None |
|
2751 | fallback = None | |
2752 | pat = parameter_s[2:] |
|
2752 | pat = parameter_s[2:] | |
2753 | dh = self.shell.user_ns['_dh'] |
|
2753 | dh = self.shell.user_ns['_dh'] | |
2754 | # first search only by basename (last component) |
|
2754 | # first search only by basename (last component) | |
2755 | for ent in reversed(dh): |
|
2755 | for ent in reversed(dh): | |
2756 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
2756 | if pat in os.path.basename(ent) and os.path.isdir(ent): | |
2757 | ps = ent |
|
2757 | ps = ent | |
2758 | break |
|
2758 | break | |
2759 |
|
2759 | |||
2760 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
2760 | if fallback is None and pat in ent and os.path.isdir(ent): | |
2761 | fallback = ent |
|
2761 | fallback = ent | |
2762 |
|
2762 | |||
2763 | # if we have no last part match, pick the first full path match |
|
2763 | # if we have no last part match, pick the first full path match | |
2764 | if ps is None: |
|
2764 | if ps is None: | |
2765 | ps = fallback |
|
2765 | ps = fallback | |
2766 |
|
2766 | |||
2767 | if ps is None: |
|
2767 | if ps is None: | |
2768 | print "No matching entry in directory history" |
|
2768 | print "No matching entry in directory history" | |
2769 | return |
|
2769 | return | |
2770 | else: |
|
2770 | else: | |
2771 | opts = {} |
|
2771 | opts = {} | |
2772 |
|
2772 | |||
2773 |
|
2773 | |||
2774 | else: |
|
2774 | else: | |
2775 | #turn all non-space-escaping backslashes to slashes, |
|
2775 | #turn all non-space-escaping backslashes to slashes, | |
2776 | # for c:\windows\directory\names\ |
|
2776 | # for c:\windows\directory\names\ | |
2777 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2777 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) | |
2778 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2778 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
2779 | # jump to previous |
|
2779 | # jump to previous | |
2780 | if ps == '-': |
|
2780 | if ps == '-': | |
2781 | try: |
|
2781 | try: | |
2782 | ps = self.shell.user_ns['_dh'][-2] |
|
2782 | ps = self.shell.user_ns['_dh'][-2] | |
2783 | except IndexError: |
|
2783 | except IndexError: | |
2784 | raise UsageError('%cd -: No previous directory to change to.') |
|
2784 | raise UsageError('%cd -: No previous directory to change to.') | |
2785 | # jump to bookmark if needed |
|
2785 | # jump to bookmark if needed | |
2786 | else: |
|
2786 | else: | |
2787 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2787 | if not os.path.isdir(ps) or opts.has_key('b'): | |
2788 | bkms = self.db.get('bookmarks', {}) |
|
2788 | bkms = self.db.get('bookmarks', {}) | |
2789 |
|
2789 | |||
2790 | if bkms.has_key(ps): |
|
2790 | if bkms.has_key(ps): | |
2791 | target = bkms[ps] |
|
2791 | target = bkms[ps] | |
2792 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2792 | print '(bookmark:%s) -> %s' % (ps,target) | |
2793 | ps = target |
|
2793 | ps = target | |
2794 | else: |
|
2794 | else: | |
2795 | if opts.has_key('b'): |
|
2795 | if opts.has_key('b'): | |
2796 | raise UsageError("Bookmark '%s' not found. " |
|
2796 | raise UsageError("Bookmark '%s' not found. " | |
2797 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2797 | "Use '%%bookmark -l' to see your bookmarks." % ps) | |
2798 |
|
2798 | |||
2799 | # at this point ps should point to the target dir |
|
2799 | # at this point ps should point to the target dir | |
2800 | if ps: |
|
2800 | if ps: | |
2801 | try: |
|
2801 | try: | |
2802 | os.chdir(os.path.expanduser(ps)) |
|
2802 | os.chdir(os.path.expanduser(ps)) | |
2803 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2803 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
2804 | set_term_title('IPython: ' + abbrev_cwd()) |
|
2804 | set_term_title('IPython: ' + abbrev_cwd()) | |
2805 | except OSError: |
|
2805 | except OSError: | |
2806 | print sys.exc_info()[1] |
|
2806 | print sys.exc_info()[1] | |
2807 | else: |
|
2807 | else: | |
2808 | cwd = os.getcwd() |
|
2808 | cwd = os.getcwd() | |
2809 | dhist = self.shell.user_ns['_dh'] |
|
2809 | dhist = self.shell.user_ns['_dh'] | |
2810 | if oldcwd != cwd: |
|
2810 | if oldcwd != cwd: | |
2811 | dhist.append(cwd) |
|
2811 | dhist.append(cwd) | |
2812 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2812 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2813 |
|
2813 | |||
2814 | else: |
|
2814 | else: | |
2815 | os.chdir(self.shell.home_dir) |
|
2815 | os.chdir(self.shell.home_dir) | |
2816 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2816 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
2817 | set_term_title('IPython: ' + '~') |
|
2817 | set_term_title('IPython: ' + '~') | |
2818 | cwd = os.getcwd() |
|
2818 | cwd = os.getcwd() | |
2819 | dhist = self.shell.user_ns['_dh'] |
|
2819 | dhist = self.shell.user_ns['_dh'] | |
2820 |
|
2820 | |||
2821 | if oldcwd != cwd: |
|
2821 | if oldcwd != cwd: | |
2822 | dhist.append(cwd) |
|
2822 | dhist.append(cwd) | |
2823 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2823 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2824 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2824 | if not 'q' in opts and self.shell.user_ns['_dh']: | |
2825 | print self.shell.user_ns['_dh'][-1] |
|
2825 | print self.shell.user_ns['_dh'][-1] | |
2826 |
|
2826 | |||
2827 |
|
2827 | |||
2828 | def magic_env(self, parameter_s=''): |
|
2828 | def magic_env(self, parameter_s=''): | |
2829 | """List environment variables.""" |
|
2829 | """List environment variables.""" | |
2830 |
|
2830 | |||
2831 | return os.environ.data |
|
2831 | return os.environ.data | |
2832 |
|
2832 | |||
2833 | def magic_pushd(self, parameter_s=''): |
|
2833 | def magic_pushd(self, parameter_s=''): | |
2834 | """Place the current dir on stack and change directory. |
|
2834 | """Place the current dir on stack and change directory. | |
2835 |
|
2835 | |||
2836 | Usage:\\ |
|
2836 | Usage:\\ | |
2837 | %pushd ['dirname'] |
|
2837 | %pushd ['dirname'] | |
2838 | """ |
|
2838 | """ | |
2839 |
|
2839 | |||
2840 | dir_s = self.shell.dir_stack |
|
2840 | dir_s = self.shell.dir_stack | |
2841 | tgt = os.path.expanduser(parameter_s) |
|
2841 | tgt = os.path.expanduser(parameter_s) | |
2842 | cwd = os.getcwd().replace(self.home_dir,'~') |
|
2842 | cwd = os.getcwd().replace(self.home_dir,'~') | |
2843 | if tgt: |
|
2843 | if tgt: | |
2844 | self.magic_cd(parameter_s) |
|
2844 | self.magic_cd(parameter_s) | |
2845 | dir_s.insert(0,cwd) |
|
2845 | dir_s.insert(0,cwd) | |
2846 | return self.magic_dirs() |
|
2846 | return self.magic_dirs() | |
2847 |
|
2847 | |||
2848 | def magic_popd(self, parameter_s=''): |
|
2848 | def magic_popd(self, parameter_s=''): | |
2849 | """Change to directory popped off the top of the stack. |
|
2849 | """Change to directory popped off the top of the stack. | |
2850 | """ |
|
2850 | """ | |
2851 | if not self.shell.dir_stack: |
|
2851 | if not self.shell.dir_stack: | |
2852 | raise UsageError("%popd on empty stack") |
|
2852 | raise UsageError("%popd on empty stack") | |
2853 | top = self.shell.dir_stack.pop(0) |
|
2853 | top = self.shell.dir_stack.pop(0) | |
2854 | self.magic_cd(top) |
|
2854 | self.magic_cd(top) | |
2855 | print "popd ->",top |
|
2855 | print "popd ->",top | |
2856 |
|
2856 | |||
2857 | def magic_dirs(self, parameter_s=''): |
|
2857 | def magic_dirs(self, parameter_s=''): | |
2858 | """Return the current directory stack.""" |
|
2858 | """Return the current directory stack.""" | |
2859 |
|
2859 | |||
2860 | return self.shell.dir_stack |
|
2860 | return self.shell.dir_stack | |
2861 |
|
2861 | |||
2862 | def magic_dhist(self, parameter_s=''): |
|
2862 | def magic_dhist(self, parameter_s=''): | |
2863 | """Print your history of visited directories. |
|
2863 | """Print your history of visited directories. | |
2864 |
|
2864 | |||
2865 | %dhist -> print full history\\ |
|
2865 | %dhist -> print full history\\ | |
2866 | %dhist n -> print last n entries only\\ |
|
2866 | %dhist n -> print last n entries only\\ | |
2867 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2867 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
2868 |
|
2868 | |||
2869 | This history is automatically maintained by the %cd command, and |
|
2869 | This history is automatically maintained by the %cd command, and | |
2870 | always available as the global list variable _dh. You can use %cd -<n> |
|
2870 | always available as the global list variable _dh. You can use %cd -<n> | |
2871 | to go to directory number <n>. |
|
2871 | to go to directory number <n>. | |
2872 |
|
2872 | |||
2873 | Note that most of time, you should view directory history by entering |
|
2873 | Note that most of time, you should view directory history by entering | |
2874 | cd -<TAB>. |
|
2874 | cd -<TAB>. | |
2875 |
|
2875 | |||
2876 | """ |
|
2876 | """ | |
2877 |
|
2877 | |||
2878 | dh = self.shell.user_ns['_dh'] |
|
2878 | dh = self.shell.user_ns['_dh'] | |
2879 | if parameter_s: |
|
2879 | if parameter_s: | |
2880 | try: |
|
2880 | try: | |
2881 | args = map(int,parameter_s.split()) |
|
2881 | args = map(int,parameter_s.split()) | |
2882 | except: |
|
2882 | except: | |
2883 | self.arg_err(Magic.magic_dhist) |
|
2883 | self.arg_err(Magic.magic_dhist) | |
2884 | return |
|
2884 | return | |
2885 | if len(args) == 1: |
|
2885 | if len(args) == 1: | |
2886 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2886 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
2887 | elif len(args) == 2: |
|
2887 | elif len(args) == 2: | |
2888 | ini,fin = args |
|
2888 | ini,fin = args | |
2889 | else: |
|
2889 | else: | |
2890 | self.arg_err(Magic.magic_dhist) |
|
2890 | self.arg_err(Magic.magic_dhist) | |
2891 | return |
|
2891 | return | |
2892 | else: |
|
2892 | else: | |
2893 | ini,fin = 0,len(dh) |
|
2893 | ini,fin = 0,len(dh) | |
2894 | nlprint(dh, |
|
2894 | nlprint(dh, | |
2895 | header = 'Directory history (kept in _dh)', |
|
2895 | header = 'Directory history (kept in _dh)', | |
2896 | start=ini,stop=fin) |
|
2896 | start=ini,stop=fin) | |
2897 |
|
2897 | |||
2898 | @testdec.skip_doctest |
|
2898 | @testdec.skip_doctest | |
2899 | def magic_sc(self, parameter_s=''): |
|
2899 | def magic_sc(self, parameter_s=''): | |
2900 | """Shell capture - execute a shell command and capture its output. |
|
2900 | """Shell capture - execute a shell command and capture its output. | |
2901 |
|
2901 | |||
2902 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2902 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
2903 |
|
2903 | |||
2904 | You should use the form 'var = !command' instead. Example: |
|
2904 | You should use the form 'var = !command' instead. Example: | |
2905 |
|
2905 | |||
2906 | "%sc -l myfiles = ls ~" should now be written as |
|
2906 | "%sc -l myfiles = ls ~" should now be written as | |
2907 |
|
2907 | |||
2908 | "myfiles = !ls ~" |
|
2908 | "myfiles = !ls ~" | |
2909 |
|
2909 | |||
2910 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2910 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
2911 | below. |
|
2911 | below. | |
2912 |
|
2912 | |||
2913 | -- |
|
2913 | -- | |
2914 | %sc [options] varname=command |
|
2914 | %sc [options] varname=command | |
2915 |
|
2915 | |||
2916 | IPython will run the given command using commands.getoutput(), and |
|
2916 | IPython will run the given command using commands.getoutput(), and | |
2917 | will then update the user's interactive namespace with a variable |
|
2917 | will then update the user's interactive namespace with a variable | |
2918 | called varname, containing the value of the call. Your command can |
|
2918 | called varname, containing the value of the call. Your command can | |
2919 | contain shell wildcards, pipes, etc. |
|
2919 | contain shell wildcards, pipes, etc. | |
2920 |
|
2920 | |||
2921 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2921 | The '=' sign in the syntax is mandatory, and the variable name you | |
2922 | supply must follow Python's standard conventions for valid names. |
|
2922 | supply must follow Python's standard conventions for valid names. | |
2923 |
|
2923 | |||
2924 | (A special format without variable name exists for internal use) |
|
2924 | (A special format without variable name exists for internal use) | |
2925 |
|
2925 | |||
2926 | Options: |
|
2926 | Options: | |
2927 |
|
2927 | |||
2928 | -l: list output. Split the output on newlines into a list before |
|
2928 | -l: list output. Split the output on newlines into a list before | |
2929 | assigning it to the given variable. By default the output is stored |
|
2929 | assigning it to the given variable. By default the output is stored | |
2930 | as a single string. |
|
2930 | as a single string. | |
2931 |
|
2931 | |||
2932 | -v: verbose. Print the contents of the variable. |
|
2932 | -v: verbose. Print the contents of the variable. | |
2933 |
|
2933 | |||
2934 | In most cases you should not need to split as a list, because the |
|
2934 | In most cases you should not need to split as a list, because the | |
2935 | returned value is a special type of string which can automatically |
|
2935 | returned value is a special type of string which can automatically | |
2936 | provide its contents either as a list (split on newlines) or as a |
|
2936 | provide its contents either as a list (split on newlines) or as a | |
2937 | space-separated string. These are convenient, respectively, either |
|
2937 | space-separated string. These are convenient, respectively, either | |
2938 | for sequential processing or to be passed to a shell command. |
|
2938 | for sequential processing or to be passed to a shell command. | |
2939 |
|
2939 | |||
2940 | For example: |
|
2940 | For example: | |
2941 |
|
2941 | |||
2942 | # all-random |
|
2942 | # all-random | |
2943 |
|
2943 | |||
2944 | # Capture into variable a |
|
2944 | # Capture into variable a | |
2945 | In [1]: sc a=ls *py |
|
2945 | In [1]: sc a=ls *py | |
2946 |
|
2946 | |||
2947 | # a is a string with embedded newlines |
|
2947 | # a is a string with embedded newlines | |
2948 | In [2]: a |
|
2948 | In [2]: a | |
2949 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
2949 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' | |
2950 |
|
2950 | |||
2951 | # which can be seen as a list: |
|
2951 | # which can be seen as a list: | |
2952 | In [3]: a.l |
|
2952 | In [3]: a.l | |
2953 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
2953 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] | |
2954 |
|
2954 | |||
2955 | # or as a whitespace-separated string: |
|
2955 | # or as a whitespace-separated string: | |
2956 | In [4]: a.s |
|
2956 | In [4]: a.s | |
2957 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
2957 | Out[4]: 'setup.py win32_manual_post_install.py' | |
2958 |
|
2958 | |||
2959 | # a.s is useful to pass as a single command line: |
|
2959 | # a.s is useful to pass as a single command line: | |
2960 | In [5]: !wc -l $a.s |
|
2960 | In [5]: !wc -l $a.s | |
2961 | 146 setup.py |
|
2961 | 146 setup.py | |
2962 | 130 win32_manual_post_install.py |
|
2962 | 130 win32_manual_post_install.py | |
2963 | 276 total |
|
2963 | 276 total | |
2964 |
|
2964 | |||
2965 | # while the list form is useful to loop over: |
|
2965 | # while the list form is useful to loop over: | |
2966 | In [6]: for f in a.l: |
|
2966 | In [6]: for f in a.l: | |
2967 | ...: !wc -l $f |
|
2967 | ...: !wc -l $f | |
2968 | ...: |
|
2968 | ...: | |
2969 | 146 setup.py |
|
2969 | 146 setup.py | |
2970 | 130 win32_manual_post_install.py |
|
2970 | 130 win32_manual_post_install.py | |
2971 |
|
2971 | |||
2972 | Similiarly, the lists returned by the -l option are also special, in |
|
2972 | Similiarly, the lists returned by the -l option are also special, in | |
2973 | the sense that you can equally invoke the .s attribute on them to |
|
2973 | the sense that you can equally invoke the .s attribute on them to | |
2974 | automatically get a whitespace-separated string from their contents: |
|
2974 | automatically get a whitespace-separated string from their contents: | |
2975 |
|
2975 | |||
2976 | In [7]: sc -l b=ls *py |
|
2976 | In [7]: sc -l b=ls *py | |
2977 |
|
2977 | |||
2978 | In [8]: b |
|
2978 | In [8]: b | |
2979 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
2979 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] | |
2980 |
|
2980 | |||
2981 | In [9]: b.s |
|
2981 | In [9]: b.s | |
2982 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
2982 | Out[9]: 'setup.py win32_manual_post_install.py' | |
2983 |
|
2983 | |||
2984 | In summary, both the lists and strings used for ouptut capture have |
|
2984 | In summary, both the lists and strings used for ouptut capture have | |
2985 | the following special attributes: |
|
2985 | the following special attributes: | |
2986 |
|
2986 | |||
2987 | .l (or .list) : value as list. |
|
2987 | .l (or .list) : value as list. | |
2988 | .n (or .nlstr): value as newline-separated string. |
|
2988 | .n (or .nlstr): value as newline-separated string. | |
2989 | .s (or .spstr): value as space-separated string. |
|
2989 | .s (or .spstr): value as space-separated string. | |
2990 | """ |
|
2990 | """ | |
2991 |
|
2991 | |||
2992 | opts,args = self.parse_options(parameter_s,'lv') |
|
2992 | opts,args = self.parse_options(parameter_s,'lv') | |
2993 | # Try to get a variable name and command to run |
|
2993 | # Try to get a variable name and command to run | |
2994 | try: |
|
2994 | try: | |
2995 | # the variable name must be obtained from the parse_options |
|
2995 | # the variable name must be obtained from the parse_options | |
2996 | # output, which uses shlex.split to strip options out. |
|
2996 | # output, which uses shlex.split to strip options out. | |
2997 | var,_ = args.split('=',1) |
|
2997 | var,_ = args.split('=',1) | |
2998 | var = var.strip() |
|
2998 | var = var.strip() | |
2999 | # But the the command has to be extracted from the original input |
|
2999 | # But the the command has to be extracted from the original input | |
3000 | # parameter_s, not on what parse_options returns, to avoid the |
|
3000 | # parameter_s, not on what parse_options returns, to avoid the | |
3001 | # quote stripping which shlex.split performs on it. |
|
3001 | # quote stripping which shlex.split performs on it. | |
3002 | _,cmd = parameter_s.split('=',1) |
|
3002 | _,cmd = parameter_s.split('=',1) | |
3003 | except ValueError: |
|
3003 | except ValueError: | |
3004 | var,cmd = '','' |
|
3004 | var,cmd = '','' | |
3005 | # If all looks ok, proceed |
|
3005 | # If all looks ok, proceed | |
3006 | split = 'l' in opts |
|
3006 | split = 'l' in opts | |
3007 | out = self.shell.getoutput(cmd, split=split) |
|
3007 | out = self.shell.getoutput(cmd, split=split) | |
3008 | if opts.has_key('v'): |
|
3008 | if opts.has_key('v'): | |
3009 | print '%s ==\n%s' % (var,pformat(out)) |
|
3009 | print '%s ==\n%s' % (var,pformat(out)) | |
3010 | if var: |
|
3010 | if var: | |
3011 | self.shell.user_ns.update({var:out}) |
|
3011 | self.shell.user_ns.update({var:out}) | |
3012 | else: |
|
3012 | else: | |
3013 | return out |
|
3013 | return out | |
3014 |
|
3014 | |||
3015 | def magic_sx(self, parameter_s=''): |
|
3015 | def magic_sx(self, parameter_s=''): | |
3016 | """Shell execute - run a shell command and capture its output. |
|
3016 | """Shell execute - run a shell command and capture its output. | |
3017 |
|
3017 | |||
3018 | %sx command |
|
3018 | %sx command | |
3019 |
|
3019 | |||
3020 | IPython will run the given command using commands.getoutput(), and |
|
3020 | IPython will run the given command using commands.getoutput(), and | |
3021 | return the result formatted as a list (split on '\\n'). Since the |
|
3021 | return the result formatted as a list (split on '\\n'). Since the | |
3022 | output is _returned_, it will be stored in ipython's regular output |
|
3022 | output is _returned_, it will be stored in ipython's regular output | |
3023 | cache Out[N] and in the '_N' automatic variables. |
|
3023 | cache Out[N] and in the '_N' automatic variables. | |
3024 |
|
3024 | |||
3025 | Notes: |
|
3025 | Notes: | |
3026 |
|
3026 | |||
3027 | 1) If an input line begins with '!!', then %sx is automatically |
|
3027 | 1) If an input line begins with '!!', then %sx is automatically | |
3028 | invoked. That is, while: |
|
3028 | invoked. That is, while: | |
3029 | !ls |
|
3029 | !ls | |
3030 | causes ipython to simply issue system('ls'), typing |
|
3030 | causes ipython to simply issue system('ls'), typing | |
3031 | !!ls |
|
3031 | !!ls | |
3032 | is a shorthand equivalent to: |
|
3032 | is a shorthand equivalent to: | |
3033 | %sx ls |
|
3033 | %sx ls | |
3034 |
|
3034 | |||
3035 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
3035 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
3036 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
3036 | like '%sc -l'. The reason for this is to make it as easy as possible | |
3037 | to process line-oriented shell output via further python commands. |
|
3037 | to process line-oriented shell output via further python commands. | |
3038 | %sc is meant to provide much finer control, but requires more |
|
3038 | %sc is meant to provide much finer control, but requires more | |
3039 | typing. |
|
3039 | typing. | |
3040 |
|
3040 | |||
3041 | 3) Just like %sc -l, this is a list with special attributes: |
|
3041 | 3) Just like %sc -l, this is a list with special attributes: | |
3042 |
|
3042 | |||
3043 | .l (or .list) : value as list. |
|
3043 | .l (or .list) : value as list. | |
3044 | .n (or .nlstr): value as newline-separated string. |
|
3044 | .n (or .nlstr): value as newline-separated string. | |
3045 | .s (or .spstr): value as whitespace-separated string. |
|
3045 | .s (or .spstr): value as whitespace-separated string. | |
3046 |
|
3046 | |||
3047 | This is very useful when trying to use such lists as arguments to |
|
3047 | This is very useful when trying to use such lists as arguments to | |
3048 | system commands.""" |
|
3048 | system commands.""" | |
3049 |
|
3049 | |||
3050 | if parameter_s: |
|
3050 | if parameter_s: | |
3051 | return self.shell.getoutput(parameter_s) |
|
3051 | return self.shell.getoutput(parameter_s) | |
3052 |
|
3052 | |||
3053 | def magic_r(self, parameter_s=''): |
|
3053 | def magic_r(self, parameter_s=''): | |
3054 | """Repeat previous input. |
|
3054 | """Repeat previous input. | |
3055 |
|
3055 | |||
3056 | Note: Consider using the more powerfull %rep instead! |
|
3056 | Note: Consider using the more powerfull %rep instead! | |
3057 |
|
3057 | |||
3058 | If given an argument, repeats the previous command which starts with |
|
3058 | If given an argument, repeats the previous command which starts with | |
3059 | the same string, otherwise it just repeats the previous input. |
|
3059 | the same string, otherwise it just repeats the previous input. | |
3060 |
|
3060 | |||
3061 | Shell escaped commands (with ! as first character) are not recognized |
|
3061 | Shell escaped commands (with ! as first character) are not recognized | |
3062 | by this system, only pure python code and magic commands. |
|
3062 | by this system, only pure python code and magic commands. | |
3063 | """ |
|
3063 | """ | |
3064 |
|
3064 | |||
3065 | start = parameter_s.strip() |
|
3065 | start = parameter_s.strip() | |
3066 | esc_magic = ESC_MAGIC |
|
3066 | esc_magic = ESC_MAGIC | |
3067 | # Identify magic commands even if automagic is on (which means |
|
3067 | # Identify magic commands even if automagic is on (which means | |
3068 | # the in-memory version is different from that typed by the user). |
|
3068 | # the in-memory version is different from that typed by the user). | |
3069 | if self.shell.automagic: |
|
3069 | if self.shell.automagic: | |
3070 | start_magic = esc_magic+start |
|
3070 | start_magic = esc_magic+start | |
3071 | else: |
|
3071 | else: | |
3072 | start_magic = start |
|
3072 | start_magic = start | |
3073 | # Look through the input history in reverse |
|
3073 | # Look through the input history in reverse | |
3074 | for n in range(len(self.shell.history_manager.input_hist_parsed)-2,0,-1): |
|
3074 | for n in range(len(self.shell.history_manager.input_hist_parsed)-2,0,-1): | |
3075 | input = self.shell.history_manager.input_hist_parsed[n] |
|
3075 | input = self.shell.history_manager.input_hist_parsed[n] | |
3076 | # skip plain 'r' lines so we don't recurse to infinity |
|
3076 | # skip plain 'r' lines so we don't recurse to infinity | |
3077 | if input != '_ip.magic("r")\n' and \ |
|
3077 | if input != '_ip.magic("r")\n' and \ | |
3078 | (input.startswith(start) or input.startswith(start_magic)): |
|
3078 | (input.startswith(start) or input.startswith(start_magic)): | |
3079 | #print 'match',`input` # dbg |
|
3079 | #print 'match',`input` # dbg | |
3080 | print 'Executing:',input, |
|
3080 | print 'Executing:',input, | |
3081 | self.shell.run_cell(input) |
|
3081 | self.shell.run_cell(input) | |
3082 | return |
|
3082 | return | |
3083 | print 'No previous input matching `%s` found.' % start |
|
3083 | print 'No previous input matching `%s` found.' % start | |
3084 |
|
3084 | |||
3085 |
|
3085 | |||
3086 | def magic_bookmark(self, parameter_s=''): |
|
3086 | def magic_bookmark(self, parameter_s=''): | |
3087 | """Manage IPython's bookmark system. |
|
3087 | """Manage IPython's bookmark system. | |
3088 |
|
3088 | |||
3089 | %bookmark <name> - set bookmark to current dir |
|
3089 | %bookmark <name> - set bookmark to current dir | |
3090 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3090 | %bookmark <name> <dir> - set bookmark to <dir> | |
3091 | %bookmark -l - list all bookmarks |
|
3091 | %bookmark -l - list all bookmarks | |
3092 | %bookmark -d <name> - remove bookmark |
|
3092 | %bookmark -d <name> - remove bookmark | |
3093 | %bookmark -r - remove all bookmarks |
|
3093 | %bookmark -r - remove all bookmarks | |
3094 |
|
3094 | |||
3095 | You can later on access a bookmarked folder with: |
|
3095 | You can later on access a bookmarked folder with: | |
3096 | %cd -b <name> |
|
3096 | %cd -b <name> | |
3097 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3097 | or simply '%cd <name>' if there is no directory called <name> AND | |
3098 | there is such a bookmark defined. |
|
3098 | there is such a bookmark defined. | |
3099 |
|
3099 | |||
3100 | Your bookmarks persist through IPython sessions, but they are |
|
3100 | Your bookmarks persist through IPython sessions, but they are | |
3101 | associated with each profile.""" |
|
3101 | associated with each profile.""" | |
3102 |
|
3102 | |||
3103 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3103 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
3104 | if len(args) > 2: |
|
3104 | if len(args) > 2: | |
3105 | raise UsageError("%bookmark: too many arguments") |
|
3105 | raise UsageError("%bookmark: too many arguments") | |
3106 |
|
3106 | |||
3107 | bkms = self.db.get('bookmarks',{}) |
|
3107 | bkms = self.db.get('bookmarks',{}) | |
3108 |
|
3108 | |||
3109 | if opts.has_key('d'): |
|
3109 | if opts.has_key('d'): | |
3110 | try: |
|
3110 | try: | |
3111 | todel = args[0] |
|
3111 | todel = args[0] | |
3112 | except IndexError: |
|
3112 | except IndexError: | |
3113 | raise UsageError( |
|
3113 | raise UsageError( | |
3114 | "%bookmark -d: must provide a bookmark to delete") |
|
3114 | "%bookmark -d: must provide a bookmark to delete") | |
3115 | else: |
|
3115 | else: | |
3116 | try: |
|
3116 | try: | |
3117 | del bkms[todel] |
|
3117 | del bkms[todel] | |
3118 | except KeyError: |
|
3118 | except KeyError: | |
3119 | raise UsageError( |
|
3119 | raise UsageError( | |
3120 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3120 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) | |
3121 |
|
3121 | |||
3122 | elif opts.has_key('r'): |
|
3122 | elif opts.has_key('r'): | |
3123 | bkms = {} |
|
3123 | bkms = {} | |
3124 | elif opts.has_key('l'): |
|
3124 | elif opts.has_key('l'): | |
3125 | bks = bkms.keys() |
|
3125 | bks = bkms.keys() | |
3126 | bks.sort() |
|
3126 | bks.sort() | |
3127 | if bks: |
|
3127 | if bks: | |
3128 | size = max(map(len,bks)) |
|
3128 | size = max(map(len,bks)) | |
3129 | else: |
|
3129 | else: | |
3130 | size = 0 |
|
3130 | size = 0 | |
3131 | fmt = '%-'+str(size)+'s -> %s' |
|
3131 | fmt = '%-'+str(size)+'s -> %s' | |
3132 | print 'Current bookmarks:' |
|
3132 | print 'Current bookmarks:' | |
3133 | for bk in bks: |
|
3133 | for bk in bks: | |
3134 | print fmt % (bk,bkms[bk]) |
|
3134 | print fmt % (bk,bkms[bk]) | |
3135 | else: |
|
3135 | else: | |
3136 | if not args: |
|
3136 | if not args: | |
3137 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3137 | raise UsageError("%bookmark: You must specify the bookmark name") | |
3138 | elif len(args)==1: |
|
3138 | elif len(args)==1: | |
3139 | bkms[args[0]] = os.getcwd() |
|
3139 | bkms[args[0]] = os.getcwd() | |
3140 | elif len(args)==2: |
|
3140 | elif len(args)==2: | |
3141 | bkms[args[0]] = args[1] |
|
3141 | bkms[args[0]] = args[1] | |
3142 | self.db['bookmarks'] = bkms |
|
3142 | self.db['bookmarks'] = bkms | |
3143 |
|
3143 | |||
3144 | def magic_pycat(self, parameter_s=''): |
|
3144 | def magic_pycat(self, parameter_s=''): | |
3145 | """Show a syntax-highlighted file through a pager. |
|
3145 | """Show a syntax-highlighted file through a pager. | |
3146 |
|
3146 | |||
3147 | This magic is similar to the cat utility, but it will assume the file |
|
3147 | This magic is similar to the cat utility, but it will assume the file | |
3148 | to be Python source and will show it with syntax highlighting. """ |
|
3148 | to be Python source and will show it with syntax highlighting. """ | |
3149 |
|
3149 | |||
3150 | try: |
|
3150 | try: | |
3151 | filename = get_py_filename(parameter_s) |
|
3151 | filename = get_py_filename(parameter_s) | |
3152 | cont = file_read(filename) |
|
3152 | cont = file_read(filename) | |
3153 | except IOError: |
|
3153 | except IOError: | |
3154 | try: |
|
3154 | try: | |
3155 | cont = eval(parameter_s,self.user_ns) |
|
3155 | cont = eval(parameter_s,self.user_ns) | |
3156 | except NameError: |
|
3156 | except NameError: | |
3157 | cont = None |
|
3157 | cont = None | |
3158 | if cont is None: |
|
3158 | if cont is None: | |
3159 | print "Error: no such file or variable" |
|
3159 | print "Error: no such file or variable" | |
3160 | return |
|
3160 | return | |
3161 |
|
3161 | |||
3162 | page.page(self.shell.pycolorize(cont)) |
|
3162 | page.page(self.shell.pycolorize(cont)) | |
3163 |
|
3163 | |||
3164 | def _rerun_pasted(self): |
|
3164 | def _rerun_pasted(self): | |
3165 | """ Rerun a previously pasted command. |
|
3165 | """ Rerun a previously pasted command. | |
3166 | """ |
|
3166 | """ | |
3167 | b = self.user_ns.get('pasted_block', None) |
|
3167 | b = self.user_ns.get('pasted_block', None) | |
3168 | if b is None: |
|
3168 | if b is None: | |
3169 | raise UsageError('No previous pasted block available') |
|
3169 | raise UsageError('No previous pasted block available') | |
3170 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) |
|
3170 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) | |
3171 | exec b in self.user_ns |
|
3171 | exec b in self.user_ns | |
3172 |
|
3172 | |||
3173 | def _get_pasted_lines(self, sentinel): |
|
3173 | def _get_pasted_lines(self, sentinel): | |
3174 | """ Yield pasted lines until the user enters the given sentinel value. |
|
3174 | """ Yield pasted lines until the user enters the given sentinel value. | |
3175 | """ |
|
3175 | """ | |
3176 | from IPython.core import interactiveshell |
|
3176 | from IPython.core import interactiveshell | |
3177 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3177 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel | |
3178 | while True: |
|
3178 | while True: | |
3179 | l = interactiveshell.raw_input_original(':') |
|
3179 | l = interactiveshell.raw_input_original(':') | |
3180 | if l == sentinel: |
|
3180 | if l == sentinel: | |
3181 | return |
|
3181 | return | |
3182 | else: |
|
3182 | else: | |
3183 | yield l |
|
3183 | yield l | |
3184 |
|
3184 | |||
3185 | def _strip_pasted_lines_for_code(self, raw_lines): |
|
3185 | def _strip_pasted_lines_for_code(self, raw_lines): | |
3186 | """ Strip non-code parts of a sequence of lines to return a block of |
|
3186 | """ Strip non-code parts of a sequence of lines to return a block of | |
3187 | code. |
|
3187 | code. | |
3188 | """ |
|
3188 | """ | |
3189 | # Regular expressions that declare text we strip from the input: |
|
3189 | # Regular expressions that declare text we strip from the input: | |
3190 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt |
|
3190 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt | |
3191 | r'^\s*(\s?>)+', # Python input prompt |
|
3191 | r'^\s*(\s?>)+', # Python input prompt | |
3192 | r'^\s*\.{3,}', # Continuation prompts |
|
3192 | r'^\s*\.{3,}', # Continuation prompts | |
3193 | r'^\++', |
|
3193 | r'^\++', | |
3194 | ] |
|
3194 | ] | |
3195 |
|
3195 | |||
3196 | strip_from_start = map(re.compile,strip_re) |
|
3196 | strip_from_start = map(re.compile,strip_re) | |
3197 |
|
3197 | |||
3198 | lines = [] |
|
3198 | lines = [] | |
3199 | for l in raw_lines: |
|
3199 | for l in raw_lines: | |
3200 | for pat in strip_from_start: |
|
3200 | for pat in strip_from_start: | |
3201 | l = pat.sub('',l) |
|
3201 | l = pat.sub('',l) | |
3202 | lines.append(l) |
|
3202 | lines.append(l) | |
3203 |
|
3203 | |||
3204 | block = "\n".join(lines) + '\n' |
|
3204 | block = "\n".join(lines) + '\n' | |
3205 | #print "block:\n",block |
|
3205 | #print "block:\n",block | |
3206 | return block |
|
3206 | return block | |
3207 |
|
3207 | |||
3208 | def _execute_block(self, block, par): |
|
3208 | def _execute_block(self, block, par): | |
3209 | """ Execute a block, or store it in a variable, per the user's request. |
|
3209 | """ Execute a block, or store it in a variable, per the user's request. | |
3210 | """ |
|
3210 | """ | |
3211 | if not par: |
|
3211 | if not par: | |
3212 | b = textwrap.dedent(block) |
|
3212 | b = textwrap.dedent(block) | |
3213 | self.user_ns['pasted_block'] = b |
|
3213 | self.user_ns['pasted_block'] = b | |
3214 | exec b in self.user_ns |
|
3214 | exec b in self.user_ns | |
3215 | else: |
|
3215 | else: | |
3216 | self.user_ns[par] = SList(block.splitlines()) |
|
3216 | self.user_ns[par] = SList(block.splitlines()) | |
3217 | print "Block assigned to '%s'" % par |
|
3217 | print "Block assigned to '%s'" % par | |
3218 |
|
3218 | |||
3219 | def magic_quickref(self,arg): |
|
3219 | def magic_quickref(self,arg): | |
3220 | """ Show a quick reference sheet """ |
|
3220 | """ Show a quick reference sheet """ | |
3221 | import IPython.core.usage |
|
3221 | import IPython.core.usage | |
3222 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') |
|
3222 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') | |
3223 |
|
3223 | |||
3224 | page.page(qr) |
|
3224 | page.page(qr) | |
3225 |
|
3225 | |||
3226 | def magic_doctest_mode(self,parameter_s=''): |
|
3226 | def magic_doctest_mode(self,parameter_s=''): | |
3227 | """Toggle doctest mode on and off. |
|
3227 | """Toggle doctest mode on and off. | |
3228 |
|
3228 | |||
3229 | This mode is intended to make IPython behave as much as possible like a |
|
3229 | This mode is intended to make IPython behave as much as possible like a | |
3230 | plain Python shell, from the perspective of how its prompts, exceptions |
|
3230 | plain Python shell, from the perspective of how its prompts, exceptions | |
3231 | and output look. This makes it easy to copy and paste parts of a |
|
3231 | and output look. This makes it easy to copy and paste parts of a | |
3232 | session into doctests. It does so by: |
|
3232 | session into doctests. It does so by: | |
3233 |
|
3233 | |||
3234 | - Changing the prompts to the classic ``>>>`` ones. |
|
3234 | - Changing the prompts to the classic ``>>>`` ones. | |
3235 | - Changing the exception reporting mode to 'Plain'. |
|
3235 | - Changing the exception reporting mode to 'Plain'. | |
3236 | - Disabling pretty-printing of output. |
|
3236 | - Disabling pretty-printing of output. | |
3237 |
|
3237 | |||
3238 | Note that IPython also supports the pasting of code snippets that have |
|
3238 | Note that IPython also supports the pasting of code snippets that have | |
3239 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
3239 | leading '>>>' and '...' prompts in them. This means that you can paste | |
3240 | doctests from files or docstrings (even if they have leading |
|
3240 | doctests from files or docstrings (even if they have leading | |
3241 | whitespace), and the code will execute correctly. You can then use |
|
3241 | whitespace), and the code will execute correctly. You can then use | |
3242 | '%history -t' to see the translated history; this will give you the |
|
3242 | '%history -t' to see the translated history; this will give you the | |
3243 | input after removal of all the leading prompts and whitespace, which |
|
3243 | input after removal of all the leading prompts and whitespace, which | |
3244 | can be pasted back into an editor. |
|
3244 | can be pasted back into an editor. | |
3245 |
|
3245 | |||
3246 | With these features, you can switch into this mode easily whenever you |
|
3246 | With these features, you can switch into this mode easily whenever you | |
3247 | need to do testing and changes to doctests, without having to leave |
|
3247 | need to do testing and changes to doctests, without having to leave | |
3248 | your existing IPython session. |
|
3248 | your existing IPython session. | |
3249 | """ |
|
3249 | """ | |
3250 |
|
3250 | |||
3251 | from IPython.utils.ipstruct import Struct |
|
3251 | from IPython.utils.ipstruct import Struct | |
3252 |
|
3252 | |||
3253 | # Shorthands |
|
3253 | # Shorthands | |
3254 | shell = self.shell |
|
3254 | shell = self.shell | |
3255 | oc = shell.displayhook |
|
3255 | oc = shell.displayhook | |
3256 | meta = shell.meta |
|
3256 | meta = shell.meta | |
3257 | disp_formatter = self.shell.display_formatter |
|
3257 | disp_formatter = self.shell.display_formatter | |
3258 | ptformatter = disp_formatter.formatters['text/plain'] |
|
3258 | ptformatter = disp_formatter.formatters['text/plain'] | |
3259 | # dstore is a data store kept in the instance metadata bag to track any |
|
3259 | # dstore is a data store kept in the instance metadata bag to track any | |
3260 | # changes we make, so we can undo them later. |
|
3260 | # changes we make, so we can undo them later. | |
3261 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3261 | dstore = meta.setdefault('doctest_mode',Struct()) | |
3262 | save_dstore = dstore.setdefault |
|
3262 | save_dstore = dstore.setdefault | |
3263 |
|
3263 | |||
3264 | # save a few values we'll need to recover later |
|
3264 | # save a few values we'll need to recover later | |
3265 | mode = save_dstore('mode',False) |
|
3265 | mode = save_dstore('mode',False) | |
3266 | save_dstore('rc_pprint',ptformatter.pprint) |
|
3266 | save_dstore('rc_pprint',ptformatter.pprint) | |
3267 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3267 | save_dstore('xmode',shell.InteractiveTB.mode) | |
3268 | save_dstore('rc_separate_out',shell.separate_out) |
|
3268 | save_dstore('rc_separate_out',shell.separate_out) | |
3269 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
3269 | save_dstore('rc_separate_out2',shell.separate_out2) | |
3270 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) |
|
3270 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) | |
3271 | save_dstore('rc_separate_in',shell.separate_in) |
|
3271 | save_dstore('rc_separate_in',shell.separate_in) | |
3272 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) |
|
3272 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) | |
3273 |
|
3273 | |||
3274 | if mode == False: |
|
3274 | if mode == False: | |
3275 | # turn on |
|
3275 | # turn on | |
3276 | oc.prompt1.p_template = '>>> ' |
|
3276 | oc.prompt1.p_template = '>>> ' | |
3277 | oc.prompt2.p_template = '... ' |
|
3277 | oc.prompt2.p_template = '... ' | |
3278 | oc.prompt_out.p_template = '' |
|
3278 | oc.prompt_out.p_template = '' | |
3279 |
|
3279 | |||
3280 | # Prompt separators like plain python |
|
3280 | # Prompt separators like plain python | |
3281 | oc.input_sep = oc.prompt1.sep = '' |
|
3281 | oc.input_sep = oc.prompt1.sep = '' | |
3282 | oc.output_sep = '' |
|
3282 | oc.output_sep = '' | |
3283 | oc.output_sep2 = '' |
|
3283 | oc.output_sep2 = '' | |
3284 |
|
3284 | |||
3285 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3285 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3286 | oc.prompt_out.pad_left = False |
|
3286 | oc.prompt_out.pad_left = False | |
3287 |
|
3287 | |||
3288 | ptformatter.pprint = False |
|
3288 | ptformatter.pprint = False | |
3289 | disp_formatter.plain_text_only = True |
|
3289 | disp_formatter.plain_text_only = True | |
3290 |
|
3290 | |||
3291 | shell.magic_xmode('Plain') |
|
3291 | shell.magic_xmode('Plain') | |
3292 | else: |
|
3292 | else: | |
3293 | # turn off |
|
3293 | # turn off | |
3294 | oc.prompt1.p_template = shell.prompt_in1 |
|
3294 | oc.prompt1.p_template = shell.prompt_in1 | |
3295 | oc.prompt2.p_template = shell.prompt_in2 |
|
3295 | oc.prompt2.p_template = shell.prompt_in2 | |
3296 | oc.prompt_out.p_template = shell.prompt_out |
|
3296 | oc.prompt_out.p_template = shell.prompt_out | |
3297 |
|
3297 | |||
3298 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in |
|
3298 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in | |
3299 |
|
3299 | |||
3300 | oc.output_sep = dstore.rc_separate_out |
|
3300 | oc.output_sep = dstore.rc_separate_out | |
3301 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3301 | oc.output_sep2 = dstore.rc_separate_out2 | |
3302 |
|
3302 | |||
3303 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3303 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3304 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3304 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left | |
3305 |
|
3305 | |||
3306 | ptformatter.pprint = dstore.rc_pprint |
|
3306 | ptformatter.pprint = dstore.rc_pprint | |
3307 | disp_formatter.plain_text_only = dstore.rc_plain_text_only |
|
3307 | disp_formatter.plain_text_only = dstore.rc_plain_text_only | |
3308 |
|
3308 | |||
3309 | shell.magic_xmode(dstore.xmode) |
|
3309 | shell.magic_xmode(dstore.xmode) | |
3310 |
|
3310 | |||
3311 | # Store new mode and inform |
|
3311 | # Store new mode and inform | |
3312 | dstore.mode = bool(1-int(mode)) |
|
3312 | dstore.mode = bool(1-int(mode)) | |
3313 | mode_label = ['OFF','ON'][dstore.mode] |
|
3313 | mode_label = ['OFF','ON'][dstore.mode] | |
3314 | print 'Doctest mode is:', mode_label |
|
3314 | print 'Doctest mode is:', mode_label | |
3315 |
|
3315 | |||
3316 | def magic_gui(self, parameter_s=''): |
|
3316 | def magic_gui(self, parameter_s=''): | |
3317 | """Enable or disable IPython GUI event loop integration. |
|
3317 | """Enable or disable IPython GUI event loop integration. | |
3318 |
|
3318 | |||
3319 | %gui [GUINAME] |
|
3319 | %gui [GUINAME] | |
3320 |
|
3320 | |||
3321 | This magic replaces IPython's threaded shells that were activated |
|
3321 | This magic replaces IPython's threaded shells that were activated | |
3322 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
3322 | using the (pylab/wthread/etc.) command line flags. GUI toolkits | |
3323 | can now be enabled, disabled and swtiched at runtime and keyboard |
|
3323 | can now be enabled, disabled and swtiched at runtime and keyboard | |
3324 | interrupts should work without any problems. The following toolkits |
|
3324 | interrupts should work without any problems. The following toolkits | |
3325 | are supported: wxPython, PyQt4, PyGTK, and Tk:: |
|
3325 | are supported: wxPython, PyQt4, PyGTK, and Tk:: | |
3326 |
|
3326 | |||
3327 | %gui wx # enable wxPython event loop integration |
|
3327 | %gui wx # enable wxPython event loop integration | |
3328 | %gui qt4|qt # enable PyQt4 event loop integration |
|
3328 | %gui qt4|qt # enable PyQt4 event loop integration | |
3329 | %gui gtk # enable PyGTK event loop integration |
|
3329 | %gui gtk # enable PyGTK event loop integration | |
3330 | %gui tk # enable Tk event loop integration |
|
3330 | %gui tk # enable Tk event loop integration | |
3331 | %gui # disable all event loop integration |
|
3331 | %gui # disable all event loop integration | |
3332 |
|
3332 | |||
3333 | WARNING: after any of these has been called you can simply create |
|
3333 | WARNING: after any of these has been called you can simply create | |
3334 | an application object, but DO NOT start the event loop yourself, as |
|
3334 | an application object, but DO NOT start the event loop yourself, as | |
3335 | we have already handled that. |
|
3335 | we have already handled that. | |
3336 | """ |
|
3336 | """ | |
3337 | from IPython.lib.inputhook import enable_gui |
|
3337 | from IPython.lib.inputhook import enable_gui | |
3338 | opts, arg = self.parse_options(parameter_s, '') |
|
3338 | opts, arg = self.parse_options(parameter_s, '') | |
3339 | if arg=='': arg = None |
|
3339 | if arg=='': arg = None | |
3340 | return enable_gui(arg) |
|
3340 | return enable_gui(arg) | |
3341 |
|
3341 | |||
3342 | def magic_load_ext(self, module_str): |
|
3342 | def magic_load_ext(self, module_str): | |
3343 | """Load an IPython extension by its module name.""" |
|
3343 | """Load an IPython extension by its module name.""" | |
3344 | return self.extension_manager.load_extension(module_str) |
|
3344 | return self.extension_manager.load_extension(module_str) | |
3345 |
|
3345 | |||
3346 | def magic_unload_ext(self, module_str): |
|
3346 | def magic_unload_ext(self, module_str): | |
3347 | """Unload an IPython extension by its module name.""" |
|
3347 | """Unload an IPython extension by its module name.""" | |
3348 | self.extension_manager.unload_extension(module_str) |
|
3348 | self.extension_manager.unload_extension(module_str) | |
3349 |
|
3349 | |||
3350 | def magic_reload_ext(self, module_str): |
|
3350 | def magic_reload_ext(self, module_str): | |
3351 | """Reload an IPython extension by its module name.""" |
|
3351 | """Reload an IPython extension by its module name.""" | |
3352 | self.extension_manager.reload_extension(module_str) |
|
3352 | self.extension_manager.reload_extension(module_str) | |
3353 |
|
3353 | |||
3354 | @testdec.skip_doctest |
|
3354 | @testdec.skip_doctest | |
3355 | def magic_install_profiles(self, s): |
|
3355 | def magic_install_profiles(self, s): | |
3356 | """Install the default IPython profiles into the .ipython dir. |
|
3356 | """Install the default IPython profiles into the .ipython dir. | |
3357 |
|
3357 | |||
3358 | If the default profiles have already been installed, they will not |
|
3358 | If the default profiles have already been installed, they will not | |
3359 | be overwritten. You can force overwriting them by using the ``-o`` |
|
3359 | be overwritten. You can force overwriting them by using the ``-o`` | |
3360 | option:: |
|
3360 | option:: | |
3361 |
|
3361 | |||
3362 | In [1]: %install_profiles -o |
|
3362 | In [1]: %install_profiles -o | |
3363 | """ |
|
3363 | """ | |
3364 | if '-o' in s: |
|
3364 | if '-o' in s: | |
3365 | overwrite = True |
|
3365 | overwrite = True | |
3366 | else: |
|
3366 | else: | |
3367 | overwrite = False |
|
3367 | overwrite = False | |
3368 | from IPython.config import profile |
|
3368 | from IPython.config import profile | |
3369 | profile_dir = os.path.split(profile.__file__)[0] |
|
3369 | profile_dir = os.path.split(profile.__file__)[0] | |
3370 | ipython_dir = self.ipython_dir |
|
3370 | ipython_dir = self.ipython_dir | |
3371 | files = os.listdir(profile_dir) |
|
3371 | files = os.listdir(profile_dir) | |
3372 |
|
3372 | |||
3373 | to_install = [] |
|
3373 | to_install = [] | |
3374 | for f in files: |
|
3374 | for f in files: | |
3375 | if f.startswith('ipython_config'): |
|
3375 | if f.startswith('ipython_config'): | |
3376 | src = os.path.join(profile_dir, f) |
|
3376 | src = os.path.join(profile_dir, f) | |
3377 | dst = os.path.join(ipython_dir, f) |
|
3377 | dst = os.path.join(ipython_dir, f) | |
3378 | if (not os.path.isfile(dst)) or overwrite: |
|
3378 | if (not os.path.isfile(dst)) or overwrite: | |
3379 | to_install.append((f, src, dst)) |
|
3379 | to_install.append((f, src, dst)) | |
3380 | if len(to_install)>0: |
|
3380 | if len(to_install)>0: | |
3381 | print "Installing profiles to: ", ipython_dir |
|
3381 | print "Installing profiles to: ", ipython_dir | |
3382 | for (f, src, dst) in to_install: |
|
3382 | for (f, src, dst) in to_install: | |
3383 | shutil.copy(src, dst) |
|
3383 | shutil.copy(src, dst) | |
3384 | print " %s" % f |
|
3384 | print " %s" % f | |
3385 |
|
3385 | |||
3386 | def magic_install_default_config(self, s): |
|
3386 | def magic_install_default_config(self, s): | |
3387 | """Install IPython's default config file into the .ipython dir. |
|
3387 | """Install IPython's default config file into the .ipython dir. | |
3388 |
|
3388 | |||
3389 | If the default config file (:file:`ipython_config.py`) is already |
|
3389 | If the default config file (:file:`ipython_config.py`) is already | |
3390 | installed, it will not be overwritten. You can force overwriting |
|
3390 | installed, it will not be overwritten. You can force overwriting | |
3391 | by using the ``-o`` option:: |
|
3391 | by using the ``-o`` option:: | |
3392 |
|
3392 | |||
3393 | In [1]: %install_default_config |
|
3393 | In [1]: %install_default_config | |
3394 | """ |
|
3394 | """ | |
3395 | if '-o' in s: |
|
3395 | if '-o' in s: | |
3396 | overwrite = True |
|
3396 | overwrite = True | |
3397 | else: |
|
3397 | else: | |
3398 | overwrite = False |
|
3398 | overwrite = False | |
3399 | from IPython.config import default |
|
3399 | from IPython.config import default | |
3400 | config_dir = os.path.split(default.__file__)[0] |
|
3400 | config_dir = os.path.split(default.__file__)[0] | |
3401 | ipython_dir = self.ipython_dir |
|
3401 | ipython_dir = self.ipython_dir | |
3402 | default_config_file_name = 'ipython_config.py' |
|
3402 | default_config_file_name = 'ipython_config.py' | |
3403 | src = os.path.join(config_dir, default_config_file_name) |
|
3403 | src = os.path.join(config_dir, default_config_file_name) | |
3404 | dst = os.path.join(ipython_dir, default_config_file_name) |
|
3404 | dst = os.path.join(ipython_dir, default_config_file_name) | |
3405 | if (not os.path.isfile(dst)) or overwrite: |
|
3405 | if (not os.path.isfile(dst)) or overwrite: | |
3406 | shutil.copy(src, dst) |
|
3406 | shutil.copy(src, dst) | |
3407 | print "Installing default config file: %s" % dst |
|
3407 | print "Installing default config file: %s" % dst | |
3408 |
|
3408 | |||
3409 | # Pylab support: simple wrappers that activate pylab, load gui input |
|
3409 | # Pylab support: simple wrappers that activate pylab, load gui input | |
3410 | # handling and modify slightly %run |
|
3410 | # handling and modify slightly %run | |
3411 |
|
3411 | |||
3412 | @testdec.skip_doctest |
|
3412 | @testdec.skip_doctest | |
3413 | def _pylab_magic_run(self, parameter_s=''): |
|
3413 | def _pylab_magic_run(self, parameter_s=''): | |
3414 | Magic.magic_run(self, parameter_s, |
|
3414 | Magic.magic_run(self, parameter_s, | |
3415 | runner=mpl_runner(self.shell.safe_execfile)) |
|
3415 | runner=mpl_runner(self.shell.safe_execfile)) | |
3416 |
|
3416 | |||
3417 | _pylab_magic_run.__doc__ = magic_run.__doc__ |
|
3417 | _pylab_magic_run.__doc__ = magic_run.__doc__ | |
3418 |
|
3418 | |||
3419 | @testdec.skip_doctest |
|
3419 | @testdec.skip_doctest | |
3420 | def magic_pylab(self, s): |
|
3420 | def magic_pylab(self, s): | |
3421 | """Load numpy and matplotlib to work interactively. |
|
3421 | """Load numpy and matplotlib to work interactively. | |
3422 |
|
3422 | |||
3423 | %pylab [GUINAME] |
|
3423 | %pylab [GUINAME] | |
3424 |
|
3424 | |||
3425 | This function lets you activate pylab (matplotlib, numpy and |
|
3425 | This function lets you activate pylab (matplotlib, numpy and | |
3426 | interactive support) at any point during an IPython session. |
|
3426 | interactive support) at any point during an IPython session. | |
3427 |
|
3427 | |||
3428 | It will import at the top level numpy as np, pyplot as plt, matplotlib, |
|
3428 | It will import at the top level numpy as np, pyplot as plt, matplotlib, | |
3429 | pylab and mlab, as well as all names from numpy and pylab. |
|
3429 | pylab and mlab, as well as all names from numpy and pylab. | |
3430 |
|
3430 | |||
3431 | Parameters |
|
3431 | Parameters | |
3432 | ---------- |
|
3432 | ---------- | |
3433 | guiname : optional |
|
3433 | guiname : optional | |
3434 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or |
|
3434 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or | |
3435 | 'tk'). If given, the corresponding Matplotlib backend is used, |
|
3435 | 'tk'). If given, the corresponding Matplotlib backend is used, | |
3436 | otherwise matplotlib's default (which you can override in your |
|
3436 | otherwise matplotlib's default (which you can override in your | |
3437 | matplotlib config file) is used. |
|
3437 | matplotlib config file) is used. | |
3438 |
|
3438 | |||
3439 | Examples |
|
3439 | Examples | |
3440 | -------- |
|
3440 | -------- | |
3441 | In this case, where the MPL default is TkAgg: |
|
3441 | In this case, where the MPL default is TkAgg: | |
3442 | In [2]: %pylab |
|
3442 | In [2]: %pylab | |
3443 |
|
3443 | |||
3444 | Welcome to pylab, a matplotlib-based Python environment. |
|
3444 | Welcome to pylab, a matplotlib-based Python environment. | |
3445 | Backend in use: TkAgg |
|
3445 | Backend in use: TkAgg | |
3446 | For more information, type 'help(pylab)'. |
|
3446 | For more information, type 'help(pylab)'. | |
3447 |
|
3447 | |||
3448 | But you can explicitly request a different backend: |
|
3448 | But you can explicitly request a different backend: | |
3449 | In [3]: %pylab qt |
|
3449 | In [3]: %pylab qt | |
3450 |
|
3450 | |||
3451 | Welcome to pylab, a matplotlib-based Python environment. |
|
3451 | Welcome to pylab, a matplotlib-based Python environment. | |
3452 | Backend in use: Qt4Agg |
|
3452 | Backend in use: Qt4Agg | |
3453 | For more information, type 'help(pylab)'. |
|
3453 | For more information, type 'help(pylab)'. | |
3454 | """ |
|
3454 | """ | |
3455 | self.shell.enable_pylab(s) |
|
3455 | self.shell.enable_pylab(s) | |
3456 |
|
3456 | |||
3457 | def magic_tb(self, s): |
|
3457 | def magic_tb(self, s): | |
3458 | """Print the last traceback with the currently active exception mode. |
|
3458 | """Print the last traceback with the currently active exception mode. | |
3459 |
|
3459 | |||
3460 | See %xmode for changing exception reporting modes.""" |
|
3460 | See %xmode for changing exception reporting modes.""" | |
3461 | self.shell.showtraceback() |
|
3461 | self.shell.showtraceback() | |
3462 |
|
3462 | |||
3463 | @testdec.skip_doctest |
|
3463 | @testdec.skip_doctest | |
3464 | def magic_precision(self, s=''): |
|
3464 | def magic_precision(self, s=''): | |
3465 | """Set floating point precision for pretty printing. |
|
3465 | """Set floating point precision for pretty printing. | |
3466 |
|
3466 | |||
3467 | Can set either integer precision or a format string. |
|
3467 | Can set either integer precision or a format string. | |
3468 |
|
3468 | |||
3469 | If numpy has been imported and precision is an int, |
|
3469 | If numpy has been imported and precision is an int, | |
3470 | numpy display precision will also be set, via ``numpy.set_printoptions``. |
|
3470 | numpy display precision will also be set, via ``numpy.set_printoptions``. | |
3471 |
|
3471 | |||
3472 | If no argument is given, defaults will be restored. |
|
3472 | If no argument is given, defaults will be restored. | |
3473 |
|
3473 | |||
3474 | Examples |
|
3474 | Examples | |
3475 | -------- |
|
3475 | -------- | |
3476 | :: |
|
3476 | :: | |
3477 |
|
3477 | |||
3478 | In [1]: from math import pi |
|
3478 | In [1]: from math import pi | |
3479 |
|
3479 | |||
3480 | In [2]: %precision 3 |
|
3480 | In [2]: %precision 3 | |
3481 | Out[2]: '%.3f' |
|
3481 | Out[2]: '%.3f' | |
3482 |
|
3482 | |||
3483 | In [3]: pi |
|
3483 | In [3]: pi | |
3484 | Out[3]: 3.142 |
|
3484 | Out[3]: 3.142 | |
3485 |
|
3485 | |||
3486 | In [4]: %precision %i |
|
3486 | In [4]: %precision %i | |
3487 | Out[4]: '%i' |
|
3487 | Out[4]: '%i' | |
3488 |
|
3488 | |||
3489 | In [5]: pi |
|
3489 | In [5]: pi | |
3490 | Out[5]: 3 |
|
3490 | Out[5]: 3 | |
3491 |
|
3491 | |||
3492 | In [6]: %precision %e |
|
3492 | In [6]: %precision %e | |
3493 | Out[6]: '%e' |
|
3493 | Out[6]: '%e' | |
3494 |
|
3494 | |||
3495 | In [7]: pi**10 |
|
3495 | In [7]: pi**10 | |
3496 | Out[7]: 9.364805e+04 |
|
3496 | Out[7]: 9.364805e+04 | |
3497 |
|
3497 | |||
3498 | In [8]: %precision |
|
3498 | In [8]: %precision | |
3499 | Out[8]: '%r' |
|
3499 | Out[8]: '%r' | |
3500 |
|
3500 | |||
3501 | In [9]: pi**10 |
|
3501 | In [9]: pi**10 | |
3502 | Out[9]: 93648.047476082982 |
|
3502 | Out[9]: 93648.047476082982 | |
3503 |
|
3503 | |||
3504 | """ |
|
3504 | """ | |
3505 |
|
3505 | |||
3506 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
3506 | ptformatter = self.shell.display_formatter.formatters['text/plain'] | |
3507 | ptformatter.float_precision = s |
|
3507 | ptformatter.float_precision = s | |
3508 | return ptformatter.float_format |
|
3508 | return ptformatter.float_format | |
3509 |
|
3509 | |||
3510 | # end Magic |
|
3510 | # end Magic |
@@ -1,507 +1,508 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Usage information for the main IPython applications. |
|
2 | """Usage information for the main IPython applications. | |
3 | """ |
|
3 | """ | |
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Copyright (C) 2008-2010 The IPython Development Team |
|
5 | # Copyright (C) 2008-2010 The IPython Development Team | |
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
7 | # |
|
7 | # | |
8 | # Distributed under the terms of the BSD License. The full license is in |
|
8 | # Distributed under the terms of the BSD License. The full license is in | |
9 | # the file COPYING, distributed as part of this software. |
|
9 | # the file COPYING, distributed as part of this software. | |
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 |
|
11 | |||
12 | import sys |
|
12 | import sys | |
13 | from IPython.core import release |
|
13 | from IPython.core import release | |
14 |
|
14 | |||
15 | cl_usage = """\ |
|
15 | cl_usage = """\ | |
16 | ipython [options] [files] |
|
16 | ipython [options] [files] | |
17 |
|
17 | |||
18 | IPython: an enhanced interactive Python shell. |
|
18 | IPython: an enhanced interactive Python shell. | |
19 |
|
19 | |||
20 | A Python shell with automatic history (input and output), dynamic object |
|
20 | A Python shell with automatic history (input and output), dynamic object | |
21 | introspection, easier configuration, command completion, access to the |
|
21 | introspection, easier configuration, command completion, access to the | |
22 | system shell and more. IPython can also be embedded in running programs. |
|
22 | system shell and more. IPython can also be embedded in running programs. | |
23 |
|
23 | |||
24 | If invoked with no options, it executes all the files listed in sequence |
|
24 | If invoked with no options, it executes all the files listed in sequence | |
25 | and exits, use -i to enter interactive mode after running the files. Files |
|
25 | and exits, use -i to enter interactive mode after running the files. Files | |
26 | ending in .py will be treated as normal Python, but files ending in .ipy |
|
26 | ending in .py will be treated as normal Python, but files ending in .ipy | |
27 | can contain special IPython syntax (magic commands, shell expansions, etc.) |
|
27 | can contain special IPython syntax (magic commands, shell expansions, etc.) | |
28 |
|
28 | |||
29 | Please note that some of the configuration options are not available at the |
|
29 | Please note that some of the configuration options are not available at the | |
30 | command line, simply because they are not practical here. Look into your |
|
30 | command line, simply because they are not practical here. Look into your | |
31 | ipython_config.py configuration file for details on those. |
|
31 | ipython_config.py configuration file for details on those. | |
32 |
|
32 | |||
33 |
This file typically installed in the |
|
33 | This file is typically installed in the IPYTHON_DIR directory. For Linux | |
34 | users, $HOME resolves to C:\\Documents and Settings\\YourUserName in most |
|
34 | users, this will be $HOME/.config/ipython, and for other users it will be | |
35 | instances. |
|
35 | $HOME/.ipython. For Windows users, $HOME resolves to C:\\Documents and | |
|
36 | Settings\\YourUserName in most instances. | |||
36 |
|
37 | |||
37 | In IPython's documentation, we will refer to this directory as IPYTHON_DIR, |
|
38 | In IPython's documentation, we will refer to this directory as IPYTHON_DIR, | |
38 | you can change its default location by setting any path you want in this |
|
39 | you can change its default location by setting any path you want in this | |
39 | environment variable. |
|
40 | environment variable. | |
40 |
|
41 | |||
41 | For more information, see the manual available in HTML and PDF in your |
|
42 | For more information, see the manual available in HTML and PDF in your | |
42 | installation, or online at http://ipython.scipy.org. |
|
43 | installation, or online at http://ipython.scipy.org. | |
43 | """ |
|
44 | """ | |
44 |
|
45 | |||
45 | interactive_usage = """ |
|
46 | interactive_usage = """ | |
46 | IPython -- An enhanced Interactive Python |
|
47 | IPython -- An enhanced Interactive Python | |
47 | ========================================= |
|
48 | ========================================= | |
48 |
|
49 | |||
49 | IPython offers a combination of convenient shell features, special commands |
|
50 | IPython offers a combination of convenient shell features, special commands | |
50 | and a history mechanism for both input (command history) and output (results |
|
51 | and a history mechanism for both input (command history) and output (results | |
51 | caching, similar to Mathematica). It is intended to be a fully compatible |
|
52 | caching, similar to Mathematica). It is intended to be a fully compatible | |
52 | replacement for the standard Python interpreter, while offering vastly |
|
53 | replacement for the standard Python interpreter, while offering vastly | |
53 | improved functionality and flexibility. |
|
54 | improved functionality and flexibility. | |
54 |
|
55 | |||
55 | At your system command line, type 'ipython -help' to see the command line |
|
56 | At your system command line, type 'ipython -help' to see the command line | |
56 | options available. This document only describes interactive features. |
|
57 | options available. This document only describes interactive features. | |
57 |
|
58 | |||
58 | Warning: IPython relies on the existence of a global variable called __IP which |
|
59 | Warning: IPython relies on the existence of a global variable called __IP which | |
59 | controls the shell itself. If you redefine __IP to anything, bizarre behavior |
|
60 | controls the shell itself. If you redefine __IP to anything, bizarre behavior | |
60 | will quickly occur. |
|
61 | will quickly occur. | |
61 |
|
62 | |||
62 | MAIN FEATURES |
|
63 | MAIN FEATURES | |
63 |
|
64 | |||
64 | * Access to the standard Python help. As of Python 2.1, a help system is |
|
65 | * Access to the standard Python help. As of Python 2.1, a help system is | |
65 | available with access to object docstrings and the Python manuals. Simply |
|
66 | available with access to object docstrings and the Python manuals. Simply | |
66 | type 'help' (no quotes) to access it. |
|
67 | type 'help' (no quotes) to access it. | |
67 |
|
68 | |||
68 | * Magic commands: type %magic for information on the magic subsystem. |
|
69 | * Magic commands: type %magic for information on the magic subsystem. | |
69 |
|
70 | |||
70 | * System command aliases, via the %alias command or the ipythonrc config file. |
|
71 | * System command aliases, via the %alias command or the ipythonrc config file. | |
71 |
|
72 | |||
72 | * Dynamic object information: |
|
73 | * Dynamic object information: | |
73 |
|
74 | |||
74 | Typing ?word or word? prints detailed information about an object. If |
|
75 | Typing ?word or word? prints detailed information about an object. If | |
75 | certain strings in the object are too long (docstrings, code, etc.) they get |
|
76 | certain strings in the object are too long (docstrings, code, etc.) they get | |
76 | snipped in the center for brevity. |
|
77 | snipped in the center for brevity. | |
77 |
|
78 | |||
78 | Typing ??word or word?? gives access to the full information without |
|
79 | Typing ??word or word?? gives access to the full information without | |
79 | snipping long strings. Long strings are sent to the screen through the less |
|
80 | snipping long strings. Long strings are sent to the screen through the less | |
80 | pager if longer than the screen, printed otherwise. |
|
81 | pager if longer than the screen, printed otherwise. | |
81 |
|
82 | |||
82 | The ?/?? system gives access to the full source code for any object (if |
|
83 | The ?/?? system gives access to the full source code for any object (if | |
83 | available), shows function prototypes and other useful information. |
|
84 | available), shows function prototypes and other useful information. | |
84 |
|
85 | |||
85 | If you just want to see an object's docstring, type '%pdoc object' (without |
|
86 | If you just want to see an object's docstring, type '%pdoc object' (without | |
86 | quotes, and without % if you have automagic on). |
|
87 | quotes, and without % if you have automagic on). | |
87 |
|
88 | |||
88 | Both %pdoc and ?/?? give you access to documentation even on things which are |
|
89 | Both %pdoc and ?/?? give you access to documentation even on things which are | |
89 | not explicitely defined. Try for example typing {}.get? or after import os, |
|
90 | not explicitely defined. Try for example typing {}.get? or after import os, | |
90 | type os.path.abspath??. The magic functions %pdef, %source and %file operate |
|
91 | type os.path.abspath??. The magic functions %pdef, %source and %file operate | |
91 | similarly. |
|
92 | similarly. | |
92 |
|
93 | |||
93 | * Completion in the local namespace, by typing TAB at the prompt. |
|
94 | * Completion in the local namespace, by typing TAB at the prompt. | |
94 |
|
95 | |||
95 | At any time, hitting tab will complete any available python commands or |
|
96 | At any time, hitting tab will complete any available python commands or | |
96 | variable names, and show you a list of the possible completions if there's |
|
97 | variable names, and show you a list of the possible completions if there's | |
97 | no unambiguous one. It will also complete filenames in the current directory. |
|
98 | no unambiguous one. It will also complete filenames in the current directory. | |
98 |
|
99 | |||
99 | This feature requires the readline and rlcomplete modules, so it won't work |
|
100 | This feature requires the readline and rlcomplete modules, so it won't work | |
100 | if your Python lacks readline support (such as under Windows). |
|
101 | if your Python lacks readline support (such as under Windows). | |
101 |
|
102 | |||
102 | * Search previous command history in two ways (also requires readline): |
|
103 | * Search previous command history in two ways (also requires readline): | |
103 |
|
104 | |||
104 | - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to |
|
105 | - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to | |
105 | search through only the history items that match what you've typed so |
|
106 | search through only the history items that match what you've typed so | |
106 | far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like |
|
107 | far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like | |
107 | normal arrow keys. |
|
108 | normal arrow keys. | |
108 |
|
109 | |||
109 | - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches |
|
110 | - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches | |
110 | your history for lines that match what you've typed so far, completing as |
|
111 | your history for lines that match what you've typed so far, completing as | |
111 | much as it can. |
|
112 | much as it can. | |
112 |
|
113 | |||
113 | * Persistent command history across sessions (readline required). |
|
114 | * Persistent command history across sessions (readline required). | |
114 |
|
115 | |||
115 | * Logging of input with the ability to save and restore a working session. |
|
116 | * Logging of input with the ability to save and restore a working session. | |
116 |
|
117 | |||
117 | * System escape with !. Typing !ls will run 'ls' in the current directory. |
|
118 | * System escape with !. Typing !ls will run 'ls' in the current directory. | |
118 |
|
119 | |||
119 | * The reload command does a 'deep' reload of a module: changes made to the |
|
120 | * The reload command does a 'deep' reload of a module: changes made to the | |
120 | module since you imported will actually be available without having to exit. |
|
121 | module since you imported will actually be available without having to exit. | |
121 |
|
122 | |||
122 | * Verbose and colored exception traceback printouts. See the magic xmode and |
|
123 | * Verbose and colored exception traceback printouts. See the magic xmode and | |
123 | xcolor functions for details (just type %magic). |
|
124 | xcolor functions for details (just type %magic). | |
124 |
|
125 | |||
125 | * Input caching system: |
|
126 | * Input caching system: | |
126 |
|
127 | |||
127 | IPython offers numbered prompts (In/Out) with input and output caching. All |
|
128 | IPython offers numbered prompts (In/Out) with input and output caching. All | |
128 | input is saved and can be retrieved as variables (besides the usual arrow |
|
129 | input is saved and can be retrieved as variables (besides the usual arrow | |
129 | key recall). |
|
130 | key recall). | |
130 |
|
131 | |||
131 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
132 | The following GLOBAL variables always exist (so don't overwrite them!): | |
132 | _i: stores previous input. |
|
133 | _i: stores previous input. | |
133 | _ii: next previous. |
|
134 | _ii: next previous. | |
134 | _iii: next-next previous. |
|
135 | _iii: next-next previous. | |
135 | _ih : a list of all input _ih[n] is the input from line n. |
|
136 | _ih : a list of all input _ih[n] is the input from line n. | |
136 |
|
137 | |||
137 | Additionally, global variables named _i<n> are dynamically created (<n> |
|
138 | Additionally, global variables named _i<n> are dynamically created (<n> | |
138 | being the prompt counter), such that _i<n> == _ih[<n>] |
|
139 | being the prompt counter), such that _i<n> == _ih[<n>] | |
139 |
|
140 | |||
140 | For example, what you typed at prompt 14 is available as _i14 and _ih[14]. |
|
141 | For example, what you typed at prompt 14 is available as _i14 and _ih[14]. | |
141 |
|
142 | |||
142 | You can create macros which contain multiple input lines from this history, |
|
143 | You can create macros which contain multiple input lines from this history, | |
143 | for later re-execution, with the %macro function. |
|
144 | for later re-execution, with the %macro function. | |
144 |
|
145 | |||
145 | The history function %hist allows you to see any part of your input history |
|
146 | The history function %hist allows you to see any part of your input history | |
146 | by printing a range of the _i variables. Note that inputs which contain |
|
147 | by printing a range of the _i variables. Note that inputs which contain | |
147 | magic functions (%) appear in the history with a prepended comment. This is |
|
148 | magic functions (%) appear in the history with a prepended comment. This is | |
148 | because they aren't really valid Python code, so you can't exec them. |
|
149 | because they aren't really valid Python code, so you can't exec them. | |
149 |
|
150 | |||
150 | * Output caching system: |
|
151 | * Output caching system: | |
151 |
|
152 | |||
152 | For output that is returned from actions, a system similar to the input |
|
153 | For output that is returned from actions, a system similar to the input | |
153 | cache exists but using _ instead of _i. Only actions that produce a result |
|
154 | cache exists but using _ instead of _i. Only actions that produce a result | |
154 | (NOT assignments, for example) are cached. If you are familiar with |
|
155 | (NOT assignments, for example) are cached. If you are familiar with | |
155 | Mathematica, IPython's _ variables behave exactly like Mathematica's % |
|
156 | Mathematica, IPython's _ variables behave exactly like Mathematica's % | |
156 | variables. |
|
157 | variables. | |
157 |
|
158 | |||
158 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
159 | The following GLOBAL variables always exist (so don't overwrite them!): | |
159 | _ (one underscore): previous output. |
|
160 | _ (one underscore): previous output. | |
160 | __ (two underscores): next previous. |
|
161 | __ (two underscores): next previous. | |
161 | ___ (three underscores): next-next previous. |
|
162 | ___ (three underscores): next-next previous. | |
162 |
|
163 | |||
163 | Global variables named _<n> are dynamically created (<n> being the prompt |
|
164 | Global variables named _<n> are dynamically created (<n> being the prompt | |
164 | counter), such that the result of output <n> is always available as _<n>. |
|
165 | counter), such that the result of output <n> is always available as _<n>. | |
165 |
|
166 | |||
166 | Finally, a global dictionary named _oh exists with entries for all lines |
|
167 | Finally, a global dictionary named _oh exists with entries for all lines | |
167 | which generated output. |
|
168 | which generated output. | |
168 |
|
169 | |||
169 | * Directory history: |
|
170 | * Directory history: | |
170 |
|
171 | |||
171 | Your history of visited directories is kept in the global list _dh, and the |
|
172 | Your history of visited directories is kept in the global list _dh, and the | |
172 | magic %cd command can be used to go to any entry in that list. |
|
173 | magic %cd command can be used to go to any entry in that list. | |
173 |
|
174 | |||
174 | * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython) |
|
175 | * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython) | |
175 |
|
176 | |||
176 | 1. Auto-parentheses |
|
177 | 1. Auto-parentheses | |
177 | Callable objects (i.e. functions, methods, etc) can be invoked like |
|
178 | Callable objects (i.e. functions, methods, etc) can be invoked like | |
178 | this (notice the commas between the arguments): |
|
179 | this (notice the commas between the arguments): | |
179 | >>> callable_ob arg1, arg2, arg3 |
|
180 | >>> callable_ob arg1, arg2, arg3 | |
180 | and the input will be translated to this: |
|
181 | and the input will be translated to this: | |
181 | --> callable_ob(arg1, arg2, arg3) |
|
182 | --> callable_ob(arg1, arg2, arg3) | |
182 | You can force auto-parentheses by using '/' as the first character |
|
183 | You can force auto-parentheses by using '/' as the first character | |
183 | of a line. For example: |
|
184 | of a line. For example: | |
184 | >>> /globals # becomes 'globals()' |
|
185 | >>> /globals # becomes 'globals()' | |
185 | Note that the '/' MUST be the first character on the line! This |
|
186 | Note that the '/' MUST be the first character on the line! This | |
186 | won't work: |
|
187 | won't work: | |
187 | >>> print /globals # syntax error |
|
188 | >>> print /globals # syntax error | |
188 |
|
189 | |||
189 | In most cases the automatic algorithm should work, so you should |
|
190 | In most cases the automatic algorithm should work, so you should | |
190 | rarely need to explicitly invoke /. One notable exception is if you |
|
191 | rarely need to explicitly invoke /. One notable exception is if you | |
191 | are trying to call a function with a list of tuples as arguments (the |
|
192 | are trying to call a function with a list of tuples as arguments (the | |
192 | parenthesis will confuse IPython): |
|
193 | parenthesis will confuse IPython): | |
193 | In [1]: zip (1,2,3),(4,5,6) # won't work |
|
194 | In [1]: zip (1,2,3),(4,5,6) # won't work | |
194 | but this will work: |
|
195 | but this will work: | |
195 | In [2]: /zip (1,2,3),(4,5,6) |
|
196 | In [2]: /zip (1,2,3),(4,5,6) | |
196 | ------> zip ((1,2,3),(4,5,6)) |
|
197 | ------> zip ((1,2,3),(4,5,6)) | |
197 | Out[2]= [(1, 4), (2, 5), (3, 6)] |
|
198 | Out[2]= [(1, 4), (2, 5), (3, 6)] | |
198 |
|
199 | |||
199 | IPython tells you that it has altered your command line by |
|
200 | IPython tells you that it has altered your command line by | |
200 | displaying the new command line preceded by -->. e.g.: |
|
201 | displaying the new command line preceded by -->. e.g.: | |
201 | In [18]: callable list |
|
202 | In [18]: callable list | |
202 | -------> callable (list) |
|
203 | -------> callable (list) | |
203 |
|
204 | |||
204 | 2. Auto-Quoting |
|
205 | 2. Auto-Quoting | |
205 | You can force auto-quoting of a function's arguments by using ',' as |
|
206 | You can force auto-quoting of a function's arguments by using ',' as | |
206 | the first character of a line. For example: |
|
207 | the first character of a line. For example: | |
207 | >>> ,my_function /home/me # becomes my_function("/home/me") |
|
208 | >>> ,my_function /home/me # becomes my_function("/home/me") | |
208 |
|
209 | |||
209 | If you use ';' instead, the whole argument is quoted as a single |
|
210 | If you use ';' instead, the whole argument is quoted as a single | |
210 | string (while ',' splits on whitespace): |
|
211 | string (while ',' splits on whitespace): | |
211 | >>> ,my_function a b c # becomes my_function("a","b","c") |
|
212 | >>> ,my_function a b c # becomes my_function("a","b","c") | |
212 | >>> ;my_function a b c # becomes my_function("a b c") |
|
213 | >>> ;my_function a b c # becomes my_function("a b c") | |
213 |
|
214 | |||
214 | Note that the ',' MUST be the first character on the line! This |
|
215 | Note that the ',' MUST be the first character on the line! This | |
215 | won't work: |
|
216 | won't work: | |
216 | >>> x = ,my_function /home/me # syntax error |
|
217 | >>> x = ,my_function /home/me # syntax error | |
217 | """ |
|
218 | """ | |
218 |
|
219 | |||
219 | interactive_usage_min = """\ |
|
220 | interactive_usage_min = """\ | |
220 | An enhanced console for Python. |
|
221 | An enhanced console for Python. | |
221 | Some of its features are: |
|
222 | Some of its features are: | |
222 | - Readline support if the readline library is present. |
|
223 | - Readline support if the readline library is present. | |
223 | - Tab completion in the local namespace. |
|
224 | - Tab completion in the local namespace. | |
224 | - Logging of input, see command-line options. |
|
225 | - Logging of input, see command-line options. | |
225 | - System shell escape via ! , eg !ls. |
|
226 | - System shell escape via ! , eg !ls. | |
226 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) |
|
227 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) | |
227 | - Keeps track of locally defined variables via %who, %whos. |
|
228 | - Keeps track of locally defined variables via %who, %whos. | |
228 | - Show object information with a ? eg ?x or x? (use ?? for more info). |
|
229 | - Show object information with a ? eg ?x or x? (use ?? for more info). | |
229 | """ |
|
230 | """ | |
230 |
|
231 | |||
231 | quick_reference = r""" |
|
232 | quick_reference = r""" | |
232 | IPython -- An enhanced Interactive Python - Quick Reference Card |
|
233 | IPython -- An enhanced Interactive Python - Quick Reference Card | |
233 | ================================================================ |
|
234 | ================================================================ | |
234 |
|
235 | |||
235 | obj?, obj?? : Get help, or more help for object (also works as |
|
236 | obj?, obj?? : Get help, or more help for object (also works as | |
236 | ?obj, ??obj). |
|
237 | ?obj, ??obj). | |
237 | ?foo.*abc* : List names in 'foo' containing 'abc' in them. |
|
238 | ?foo.*abc* : List names in 'foo' containing 'abc' in them. | |
238 | %magic : Information about IPython's 'magic' % functions. |
|
239 | %magic : Information about IPython's 'magic' % functions. | |
239 |
|
240 | |||
240 | Magic functions are prefixed by %, and typically take their arguments without |
|
241 | Magic functions are prefixed by %, and typically take their arguments without | |
241 | parentheses, quotes or even commas for convenience. |
|
242 | parentheses, quotes or even commas for convenience. | |
242 |
|
243 | |||
243 | Example magic function calls: |
|
244 | Example magic function calls: | |
244 |
|
245 | |||
245 | %alias d ls -F : 'd' is now an alias for 'ls -F' |
|
246 | %alias d ls -F : 'd' is now an alias for 'ls -F' | |
246 | alias d ls -F : Works if 'alias' not a python name |
|
247 | alias d ls -F : Works if 'alias' not a python name | |
247 | alist = %alias : Get list of aliases to 'alist' |
|
248 | alist = %alias : Get list of aliases to 'alist' | |
248 | cd /usr/share : Obvious. cd -<tab> to choose from visited dirs. |
|
249 | cd /usr/share : Obvious. cd -<tab> to choose from visited dirs. | |
249 | %cd?? : See help AND source for magic %cd |
|
250 | %cd?? : See help AND source for magic %cd | |
250 |
|
251 | |||
251 | System commands: |
|
252 | System commands: | |
252 |
|
253 | |||
253 | !cp a.txt b/ : System command escape, calls os.system() |
|
254 | !cp a.txt b/ : System command escape, calls os.system() | |
254 | cp a.txt b/ : after %rehashx, most system commands work without ! |
|
255 | cp a.txt b/ : after %rehashx, most system commands work without ! | |
255 | cp ${f}.txt $bar : Variable expansion in magics and system commands |
|
256 | cp ${f}.txt $bar : Variable expansion in magics and system commands | |
256 | files = !ls /usr : Capture sytem command output |
|
257 | files = !ls /usr : Capture sytem command output | |
257 | files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc' |
|
258 | files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc' | |
258 |
|
259 | |||
259 | History: |
|
260 | History: | |
260 |
|
261 | |||
261 | _i, _ii, _iii : Previous, next previous, next next previous input |
|
262 | _i, _ii, _iii : Previous, next previous, next next previous input | |
262 | _i4, _ih[2:5] : Input history line 4, lines 2-4 |
|
263 | _i4, _ih[2:5] : Input history line 4, lines 2-4 | |
263 | exec _i81 : Execute input history line #81 again |
|
264 | exec _i81 : Execute input history line #81 again | |
264 | %rep 81 : Edit input history line #81 |
|
265 | %rep 81 : Edit input history line #81 | |
265 | _, __, ___ : previous, next previous, next next previous output |
|
266 | _, __, ___ : previous, next previous, next next previous output | |
266 | _dh : Directory history |
|
267 | _dh : Directory history | |
267 | _oh : Output history |
|
268 | _oh : Output history | |
268 | %hist : Command history. '%hist -g foo' search history for 'foo' |
|
269 | %hist : Command history. '%hist -g foo' search history for 'foo' | |
269 |
|
270 | |||
270 | Autocall: |
|
271 | Autocall: | |
271 |
|
272 | |||
272 | f 1,2 : f(1,2) |
|
273 | f 1,2 : f(1,2) | |
273 | /f 1,2 : f(1,2) (forced autoparen) |
|
274 | /f 1,2 : f(1,2) (forced autoparen) | |
274 | ,f 1 2 : f("1","2") |
|
275 | ,f 1 2 : f("1","2") | |
275 | ;f 1 2 : f("1 2") |
|
276 | ;f 1 2 : f("1 2") | |
276 |
|
277 | |||
277 | Remember: TAB completion works in many contexts, not just file names |
|
278 | Remember: TAB completion works in many contexts, not just file names | |
278 | or python names. |
|
279 | or python names. | |
279 |
|
280 | |||
280 | The following magic functions are currently available: |
|
281 | The following magic functions are currently available: | |
281 |
|
282 | |||
282 | """ |
|
283 | """ | |
283 |
|
284 | |||
284 | gui_reference = """\ |
|
285 | gui_reference = """\ | |
285 | =============================== |
|
286 | =============================== | |
286 | The graphical IPython console |
|
287 | The graphical IPython console | |
287 | =============================== |
|
288 | =============================== | |
288 |
|
289 | |||
289 | This console is designed to emulate the look, feel and workflow of a terminal |
|
290 | This console is designed to emulate the look, feel and workflow of a terminal | |
290 | environment, while adding a number of enhancements that are simply not possible |
|
291 | environment, while adding a number of enhancements that are simply not possible | |
291 | in a real terminal, such as inline syntax highlighting, true multiline editing, |
|
292 | in a real terminal, such as inline syntax highlighting, true multiline editing, | |
292 | inline graphics and much more. |
|
293 | inline graphics and much more. | |
293 |
|
294 | |||
294 | This quick reference document contains the basic information you'll need to |
|
295 | This quick reference document contains the basic information you'll need to | |
295 | know to make the most efficient use of it. For the various command line |
|
296 | know to make the most efficient use of it. For the various command line | |
296 | options available at startup, type ``--help`` at the command line. |
|
297 | options available at startup, type ``--help`` at the command line. | |
297 |
|
298 | |||
298 |
|
299 | |||
299 | Multiline editing |
|
300 | Multiline editing | |
300 | ================= |
|
301 | ================= | |
301 |
|
302 | |||
302 | The graphical console is capable of true multiline editing, but it also tries |
|
303 | The graphical console is capable of true multiline editing, but it also tries | |
303 | to behave intuitively like a terminal when possible. If you are used to |
|
304 | to behave intuitively like a terminal when possible. If you are used to | |
304 | IPyhton's old terminal behavior, you should find the transition painless, and |
|
305 | IPyhton's old terminal behavior, you should find the transition painless, and | |
305 | once you learn a few basic keybindings it will be a much more efficient |
|
306 | once you learn a few basic keybindings it will be a much more efficient | |
306 | environment. |
|
307 | environment. | |
307 |
|
308 | |||
308 | For single expressions or indented blocks, the console behaves almost like the |
|
309 | For single expressions or indented blocks, the console behaves almost like the | |
309 | terminal IPython: single expressions are immediately evaluated, and indented |
|
310 | terminal IPython: single expressions are immediately evaluated, and indented | |
310 | blocks are evaluated once a single blank line is entered:: |
|
311 | blocks are evaluated once a single blank line is entered:: | |
311 |
|
312 | |||
312 | In [1]: print "Hello IPython!" # Enter was pressed at the end of the line |
|
313 | In [1]: print "Hello IPython!" # Enter was pressed at the end of the line | |
313 | Hello IPython! |
|
314 | Hello IPython! | |
314 |
|
315 | |||
315 | In [2]: for i in range(10): |
|
316 | In [2]: for i in range(10): | |
316 | ...: print i, |
|
317 | ...: print i, | |
317 | ...: |
|
318 | ...: | |
318 | 0 1 2 3 4 5 6 7 8 9 |
|
319 | 0 1 2 3 4 5 6 7 8 9 | |
319 |
|
320 | |||
320 | If you want to enter more than one expression in a single input block |
|
321 | If you want to enter more than one expression in a single input block | |
321 | (something not possible in the terminal), you can use ``Control-Enter`` at the |
|
322 | (something not possible in the terminal), you can use ``Control-Enter`` at the | |
322 | end of your first line instead of ``Enter``. At that point the console goes |
|
323 | end of your first line instead of ``Enter``. At that point the console goes | |
323 | into 'cell mode' and even if your inputs are not indented, it will continue |
|
324 | into 'cell mode' and even if your inputs are not indented, it will continue | |
324 | accepting arbitrarily many lines until either you enter an extra blank line or |
|
325 | accepting arbitrarily many lines until either you enter an extra blank line or | |
325 | you hit ``Shift-Enter`` (the key binding that forces execution). When a |
|
326 | you hit ``Shift-Enter`` (the key binding that forces execution). When a | |
326 | multiline cell is entered, IPython analyzes it and executes its code producing |
|
327 | multiline cell is entered, IPython analyzes it and executes its code producing | |
327 | an ``Out[n]`` prompt only for the last expression in it, while the rest of the |
|
328 | an ``Out[n]`` prompt only for the last expression in it, while the rest of the | |
328 | cell is executed as if it was a script. An example should clarify this:: |
|
329 | cell is executed as if it was a script. An example should clarify this:: | |
329 |
|
330 | |||
330 | In [3]: x=1 # Hit C-Enter here |
|
331 | In [3]: x=1 # Hit C-Enter here | |
331 | ...: y=2 # from now on, regular Enter is sufficient |
|
332 | ...: y=2 # from now on, regular Enter is sufficient | |
332 | ...: z=3 |
|
333 | ...: z=3 | |
333 | ...: x**2 # This does *not* produce an Out[] value |
|
334 | ...: x**2 # This does *not* produce an Out[] value | |
334 | ...: x+y+z # Only the last expression does |
|
335 | ...: x+y+z # Only the last expression does | |
335 | ...: |
|
336 | ...: | |
336 | Out[3]: 6 |
|
337 | Out[3]: 6 | |
337 |
|
338 | |||
338 | The behavior where an extra blank line forces execution is only active if you |
|
339 | The behavior where an extra blank line forces execution is only active if you | |
339 | are actually typing at the keyboard each line, and is meant to make it mimic |
|
340 | are actually typing at the keyboard each line, and is meant to make it mimic | |
340 | the IPython terminal behavior. If you paste a long chunk of input (for example |
|
341 | the IPython terminal behavior. If you paste a long chunk of input (for example | |
341 | a long script copied form an editor or web browser), it can contain arbitrarily |
|
342 | a long script copied form an editor or web browser), it can contain arbitrarily | |
342 | many intermediate blank lines and they won't cause any problems. As always, |
|
343 | many intermediate blank lines and they won't cause any problems. As always, | |
343 | you can then make it execute by appending a blank line *at the end* or hitting |
|
344 | you can then make it execute by appending a blank line *at the end* or hitting | |
344 | ``Shift-Enter`` anywhere within the cell. |
|
345 | ``Shift-Enter`` anywhere within the cell. | |
345 |
|
346 | |||
346 | With the up arrow key, you can retrieve previous blocks of input that contain |
|
347 | With the up arrow key, you can retrieve previous blocks of input that contain | |
347 | multiple lines. You can move inside of a multiline cell like you would in any |
|
348 | multiple lines. You can move inside of a multiline cell like you would in any | |
348 | text editor. When you want it executed, the simplest thing to do is to hit the |
|
349 | text editor. When you want it executed, the simplest thing to do is to hit the | |
349 | force execution key, ``Shift-Enter`` (though you can also navigate to the end |
|
350 | force execution key, ``Shift-Enter`` (though you can also navigate to the end | |
350 | and append a blank line by using ``Enter`` twice). |
|
351 | and append a blank line by using ``Enter`` twice). | |
351 |
|
352 | |||
352 | If you've edited a multiline cell and accidentally navigate out of it with the |
|
353 | If you've edited a multiline cell and accidentally navigate out of it with the | |
353 | up or down arrow keys, IPython will clear the cell and replace it with the |
|
354 | up or down arrow keys, IPython will clear the cell and replace it with the | |
354 | contents of the one above or below that you navigated to. If this was an |
|
355 | contents of the one above or below that you navigated to. If this was an | |
355 | accident and you want to retrieve the cell you were editing, use the Undo |
|
356 | accident and you want to retrieve the cell you were editing, use the Undo | |
356 | keybinding, ``Control-z``. |
|
357 | keybinding, ``Control-z``. | |
357 |
|
358 | |||
358 |
|
359 | |||
359 | Key bindings |
|
360 | Key bindings | |
360 | ============ |
|
361 | ============ | |
361 |
|
362 | |||
362 | The IPython console supports most of the basic Emacs line-oriented keybindings, |
|
363 | The IPython console supports most of the basic Emacs line-oriented keybindings, | |
363 | in addition to some of its own. |
|
364 | in addition to some of its own. | |
364 |
|
365 | |||
365 | The keybinding prefixes mean: |
|
366 | The keybinding prefixes mean: | |
366 |
|
367 | |||
367 | - ``C``: Control |
|
368 | - ``C``: Control | |
368 | - ``S``: Shift |
|
369 | - ``S``: Shift | |
369 | - ``M``: Meta (typically the Alt key) |
|
370 | - ``M``: Meta (typically the Alt key) | |
370 |
|
371 | |||
371 | The keybindings themselves are: |
|
372 | The keybindings themselves are: | |
372 |
|
373 | |||
373 | - ``Enter``: insert new line (may cause execution, see above). |
|
374 | - ``Enter``: insert new line (may cause execution, see above). | |
374 | - ``C-Enter``: force new line, *never* causes execution. |
|
375 | - ``C-Enter``: force new line, *never* causes execution. | |
375 | - ``S-Enter``: *force* execution regardless of where cursor is, no newline added. |
|
376 | - ``S-Enter``: *force* execution regardless of where cursor is, no newline added. | |
376 | - ``C-c``: copy highlighted text to clipboard (prompts are automatically stripped). |
|
377 | - ``C-c``: copy highlighted text to clipboard (prompts are automatically stripped). | |
377 | - ``C-S-c``: copy highlighted text to clipboard (prompts are not stripped). |
|
378 | - ``C-S-c``: copy highlighted text to clipboard (prompts are not stripped). | |
378 | - ``C-v``: paste text from clipboard. |
|
379 | - ``C-v``: paste text from clipboard. | |
379 | - ``C-z``: undo (retrieves lost text if you move out of a cell with the arrows). |
|
380 | - ``C-z``: undo (retrieves lost text if you move out of a cell with the arrows). | |
380 | - ``C-S-z``: redo. |
|
381 | - ``C-S-z``: redo. | |
381 | - ``C-o``: move to 'other' area, between pager and terminal. |
|
382 | - ``C-o``: move to 'other' area, between pager and terminal. | |
382 | - ``C-l``: clear terminal. |
|
383 | - ``C-l``: clear terminal. | |
383 | - ``C-a``: go to beginning of line. |
|
384 | - ``C-a``: go to beginning of line. | |
384 | - ``C-e``: go to end of line. |
|
385 | - ``C-e``: go to end of line. | |
385 | - ``C-k``: kill from cursor to the end of the line. |
|
386 | - ``C-k``: kill from cursor to the end of the line. | |
386 | - ``C-y``: yank (paste) |
|
387 | - ``C-y``: yank (paste) | |
387 | - ``C-p``: previous line (like up arrow) |
|
388 | - ``C-p``: previous line (like up arrow) | |
388 | - ``C-n``: next line (like down arrow) |
|
389 | - ``C-n``: next line (like down arrow) | |
389 | - ``C-f``: forward (like right arrow) |
|
390 | - ``C-f``: forward (like right arrow) | |
390 | - ``C-b``: back (like left arrow) |
|
391 | - ``C-b``: back (like left arrow) | |
391 | - ``C-d``: delete next character. |
|
392 | - ``C-d``: delete next character. | |
392 | - ``M-<``: move to the beginning of the input region. |
|
393 | - ``M-<``: move to the beginning of the input region. | |
393 | - ``M->``: move to the end of the input region. |
|
394 | - ``M->``: move to the end of the input region. | |
394 | - ``M-d``: delete next word. |
|
395 | - ``M-d``: delete next word. | |
395 | - ``M-Backspace``: delete previous word. |
|
396 | - ``M-Backspace``: delete previous word. | |
396 | - ``C-.``: force a kernel restart (a confirmation dialog appears). |
|
397 | - ``C-.``: force a kernel restart (a confirmation dialog appears). | |
397 | - ``C-+``: increase font size. |
|
398 | - ``C-+``: increase font size. | |
398 | - ``C--``: decrease font size. |
|
399 | - ``C--``: decrease font size. | |
399 |
|
400 | |||
400 | The IPython pager |
|
401 | The IPython pager | |
401 | ================= |
|
402 | ================= | |
402 |
|
403 | |||
403 | IPython will show long blocks of text from many sources using a builtin pager. |
|
404 | IPython will show long blocks of text from many sources using a builtin pager. | |
404 | You can control where this pager appears with the ``--paging`` command-line |
|
405 | You can control where this pager appears with the ``--paging`` command-line | |
405 | flag: |
|
406 | flag: | |
406 |
|
407 | |||
407 | - default: it is overlaid on top of the main terminal. You must quit the pager |
|
408 | - default: it is overlaid on top of the main terminal. You must quit the pager | |
408 | to get back to the terminal (similar to how a pager such as ``less`` or |
|
409 | to get back to the terminal (similar to how a pager such as ``less`` or | |
409 | ``more`` works). |
|
410 | ``more`` works). | |
410 |
|
411 | |||
411 | - vertical: the console is made double-tall, and the pager appears on the |
|
412 | - vertical: the console is made double-tall, and the pager appears on the | |
412 | bottom area when needed. You can view its contents while using the terminal. |
|
413 | bottom area when needed. You can view its contents while using the terminal. | |
413 |
|
414 | |||
414 | - horizontal: the console is made double-wide, and the pager appears on the |
|
415 | - horizontal: the console is made double-wide, and the pager appears on the | |
415 | right area when needed. You can view its contents while using the terminal. |
|
416 | right area when needed. You can view its contents while using the terminal. | |
416 |
|
417 | |||
417 | If you use the vertical or horizontal paging modes, you can navigate between |
|
418 | If you use the vertical or horizontal paging modes, you can navigate between | |
418 | terminal and pager as follows: |
|
419 | terminal and pager as follows: | |
419 |
|
420 | |||
420 | - Tab key: goes from pager to terminal (but not the other way around). |
|
421 | - Tab key: goes from pager to terminal (but not the other way around). | |
421 | - Control-o: goes from one to another always. |
|
422 | - Control-o: goes from one to another always. | |
422 | - Mouse: click on either. |
|
423 | - Mouse: click on either. | |
423 |
|
424 | |||
424 | In all cases, the ``q`` or ``Escape`` keys quit the pager (when used with the |
|
425 | In all cases, the ``q`` or ``Escape`` keys quit the pager (when used with the | |
425 | focus on the pager area). |
|
426 | focus on the pager area). | |
426 |
|
427 | |||
427 |
|
428 | |||
428 | Running subprocesses |
|
429 | Running subprocesses | |
429 | ==================== |
|
430 | ==================== | |
430 |
|
431 | |||
431 | The graphical IPython console uses the ``pexpect`` module to run subprocesses |
|
432 | The graphical IPython console uses the ``pexpect`` module to run subprocesses | |
432 | when you type ``!command``. This has a number of advantages (true asynchronous |
|
433 | when you type ``!command``. This has a number of advantages (true asynchronous | |
433 | output from subprocesses as well as very robust termination of rogue |
|
434 | output from subprocesses as well as very robust termination of rogue | |
434 | subprocesses with ``Control-C``), as well as some limitations. The main |
|
435 | subprocesses with ``Control-C``), as well as some limitations. The main | |
435 | limitation is that you can *not* interact back with the subprocess, so anything |
|
436 | limitation is that you can *not* interact back with the subprocess, so anything | |
436 | that invokes a pager or expects you to type input into it will block and hang |
|
437 | that invokes a pager or expects you to type input into it will block and hang | |
437 | (you can kill it with ``Control-C``). |
|
438 | (you can kill it with ``Control-C``). | |
438 |
|
439 | |||
439 | We have provided as magics ``%less`` to page files (aliased to ``%more``), |
|
440 | We have provided as magics ``%less`` to page files (aliased to ``%more``), | |
440 | ``%clear`` to clear the terminal, and ``%man`` on Linux/OSX. These cover the |
|
441 | ``%clear`` to clear the terminal, and ``%man`` on Linux/OSX. These cover the | |
441 | most common commands you'd want to call in your subshell and that would cause |
|
442 | most common commands you'd want to call in your subshell and that would cause | |
442 | problems if invoked via ``!cmd``, but you need to be aware of this limitation. |
|
443 | problems if invoked via ``!cmd``, but you need to be aware of this limitation. | |
443 |
|
444 | |||
444 | Display |
|
445 | Display | |
445 | ======= |
|
446 | ======= | |
446 |
|
447 | |||
447 | The IPython console can now display objects in a variety of formats, including |
|
448 | The IPython console can now display objects in a variety of formats, including | |
448 | HTML, PNG and SVG. This is accomplished using the display functions in |
|
449 | HTML, PNG and SVG. This is accomplished using the display functions in | |
449 | ``IPython.core.display``:: |
|
450 | ``IPython.core.display``:: | |
450 |
|
451 | |||
451 | In [4]: from IPython.core.display import display, display_html |
|
452 | In [4]: from IPython.core.display import display, display_html | |
452 |
|
453 | |||
453 | In [5]: from IPython.core.display import display_png, display_svg |
|
454 | In [5]: from IPython.core.display import display_png, display_svg | |
454 |
|
455 | |||
455 | Python objects can simply be passed to these functions and the appropriate |
|
456 | Python objects can simply be passed to these functions and the appropriate | |
456 | representations will be displayed in the console as long as the objects know |
|
457 | representations will be displayed in the console as long as the objects know | |
457 | how to compute those representations. The easiest way of teaching objects how |
|
458 | how to compute those representations. The easiest way of teaching objects how | |
458 | to format themselves in various representations is to define special methods |
|
459 | to format themselves in various representations is to define special methods | |
459 | such as: ``__html``, ``__svg__`` and ``__png__``. IPython's display formatters |
|
460 | such as: ``__html``, ``__svg__`` and ``__png__``. IPython's display formatters | |
460 | can also be given custom formatter functions for various types:: |
|
461 | can also be given custom formatter functions for various types:: | |
461 |
|
462 | |||
462 | In [6]: ip = get_ipython() |
|
463 | In [6]: ip = get_ipython() | |
463 |
|
464 | |||
464 | In [7]: html_formatter = ip.display_formatter.formatters['text/html'] |
|
465 | In [7]: html_formatter = ip.display_formatter.formatters['text/html'] | |
465 |
|
466 | |||
466 | In [8]: html_formatter.for_type(Foo, foo_to_html) |
|
467 | In [8]: html_formatter.for_type(Foo, foo_to_html) | |
467 |
|
468 | |||
468 | For further details, see ``IPython.core.formatters``. |
|
469 | For further details, see ``IPython.core.formatters``. | |
469 |
|
470 | |||
470 | Inline matplotlib graphics |
|
471 | Inline matplotlib graphics | |
471 | ========================== |
|
472 | ========================== | |
472 |
|
473 | |||
473 | The IPython console is capable of displaying matplotlib figures inline, in SVG |
|
474 | The IPython console is capable of displaying matplotlib figures inline, in SVG | |
474 | format. If started with the ``--pylab inline`` flag, then all figures are |
|
475 | format. If started with the ``--pylab inline`` flag, then all figures are | |
475 | rendered inline automatically. If started with ``--pylab`` or ``--pylab <your |
|
476 | rendered inline automatically. If started with ``--pylab`` or ``--pylab <your | |
476 | backend>``, then a GUI backend will be used, but IPython's ``display()`` and |
|
477 | backend>``, then a GUI backend will be used, but IPython's ``display()`` and | |
477 | ``getfigs()`` functions can be used to view plots inline:: |
|
478 | ``getfigs()`` functions can be used to view plots inline:: | |
478 |
|
479 | |||
479 | In [9]: display(*getfigs()) # display all figures inline |
|
480 | In [9]: display(*getfigs()) # display all figures inline | |
480 |
|
481 | |||
481 | In[10]: display(*getfigs(1,2)) # display figures 1 and 2 inline |
|
482 | In[10]: display(*getfigs(1,2)) # display figures 1 and 2 inline | |
482 | """ |
|
483 | """ | |
483 |
|
484 | |||
484 |
|
485 | |||
485 | quick_guide = """\ |
|
486 | quick_guide = """\ | |
486 | ? -> Introduction and overview of IPython's features. |
|
487 | ? -> Introduction and overview of IPython's features. | |
487 | %quickref -> Quick reference. |
|
488 | %quickref -> Quick reference. | |
488 | help -> Python's own help system. |
|
489 | help -> Python's own help system. | |
489 | object? -> Details about 'object', use 'object??' for extra details. |
|
490 | object? -> Details about 'object', use 'object??' for extra details. | |
490 | """ |
|
491 | """ | |
491 |
|
492 | |||
492 | gui_note = """\ |
|
493 | gui_note = """\ | |
493 | %guiref -> A brief reference about the graphical user interface. |
|
494 | %guiref -> A brief reference about the graphical user interface. | |
494 | """ |
|
495 | """ | |
495 |
|
496 | |||
496 | default_banner_parts = [ |
|
497 | default_banner_parts = [ | |
497 | 'Python %s\n' % (sys.version.split('\n')[0],), |
|
498 | 'Python %s\n' % (sys.version.split('\n')[0],), | |
498 | 'Type "copyright", "credits" or "license" for more information.\n\n', |
|
499 | 'Type "copyright", "credits" or "license" for more information.\n\n', | |
499 | 'IPython %s -- An enhanced Interactive Python.\n' % (release.version,), |
|
500 | 'IPython %s -- An enhanced Interactive Python.\n' % (release.version,), | |
500 | quick_guide |
|
501 | quick_guide | |
501 | ] |
|
502 | ] | |
502 |
|
503 | |||
503 | default_gui_banner_parts = default_banner_parts + [gui_note] |
|
504 | default_gui_banner_parts = default_banner_parts + [gui_note] | |
504 |
|
505 | |||
505 | default_banner = ''.join(default_banner_parts) |
|
506 | default_banner = ''.join(default_banner_parts) | |
506 |
|
507 | |||
507 | default_gui_banner = ''.join(default_gui_banner_parts) |
|
508 | default_gui_banner = ''.join(default_gui_banner_parts) |
@@ -1,374 +1,374 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | # -*- test-case-name: IPython.kernel.test.test_controllerservice -*- |
|
2 | # -*- test-case-name: IPython.kernel.test.test_controllerservice -*- | |
3 |
|
3 | |||
4 | """A Twisted Service for the IPython Controller. |
|
4 | """A Twisted Service for the IPython Controller. | |
5 |
|
5 | |||
6 | The IPython Controller: |
|
6 | The IPython Controller: | |
7 |
|
7 | |||
8 | * Listens for Engines to connect and then manages access to those engines. |
|
8 | * Listens for Engines to connect and then manages access to those engines. | |
9 | * Listens for clients and passes commands from client to the Engines. |
|
9 | * Listens for clients and passes commands from client to the Engines. | |
10 | * Exposes an asynchronous interfaces to the Engines which themselves can block. |
|
10 | * Exposes an asynchronous interfaces to the Engines which themselves can block. | |
11 | * Acts as a gateway to the Engines. |
|
11 | * Acts as a gateway to the Engines. | |
12 |
|
12 | |||
13 | The design of the controller is somewhat abstract to allow flexibility in how |
|
13 | The design of the controller is somewhat abstract to allow flexibility in how | |
14 | the controller is presented to clients. This idea is that there is a basic |
|
14 | the controller is presented to clients. This idea is that there is a basic | |
15 | ControllerService class that allows engines to connect to it. But, this |
|
15 | ControllerService class that allows engines to connect to it. But, this | |
16 | basic class has no client interfaces. To expose client interfaces developers |
|
16 | basic class has no client interfaces. To expose client interfaces developers | |
17 | provide an adapter that makes the ControllerService look like something. For |
|
17 | provide an adapter that makes the ControllerService look like something. For | |
18 | example, one client interface might support task farming and another might |
|
18 | example, one client interface might support task farming and another might | |
19 | support interactive usage. The important thing is that by using interfaces |
|
19 | support interactive usage. The important thing is that by using interfaces | |
20 | and adapters, a single controller can be accessed from multiple interfaces. |
|
20 | and adapters, a single controller can be accessed from multiple interfaces. | |
21 | Furthermore, by adapting various client interfaces to various network |
|
21 | Furthermore, by adapting various client interfaces to various network | |
22 | protocols, each client interface can be exposed to multiple network protocols. |
|
22 | protocols, each client interface can be exposed to multiple network protocols. | |
23 | See multiengine.py for an example of how to adapt the ControllerService |
|
23 | See multiengine.py for an example of how to adapt the ControllerService | |
24 | to a client interface. |
|
24 | to a client interface. | |
25 | """ |
|
25 | """ | |
26 |
|
26 | |||
27 | __docformat__ = "restructuredtext en" |
|
27 | __docformat__ = "restructuredtext en" | |
28 |
|
28 | |||
29 | #------------------------------------------------------------------------------- |
|
29 | #------------------------------------------------------------------------------- | |
30 | # Copyright (C) 2008 The IPython Development Team |
|
30 | # Copyright (C) 2008 The IPython Development Team | |
31 | # |
|
31 | # | |
32 | # Distributed under the terms of the BSD License. The full license is in |
|
32 | # Distributed under the terms of the BSD License. The full license is in | |
33 | # the file COPYING, distributed as part of this software. |
|
33 | # the file COPYING, distributed as part of this software. | |
34 | #------------------------------------------------------------------------------- |
|
34 | #------------------------------------------------------------------------------- | |
35 |
|
35 | |||
36 | #------------------------------------------------------------------------------- |
|
36 | #------------------------------------------------------------------------------- | |
37 | # Imports |
|
37 | # Imports | |
38 | #------------------------------------------------------------------------------- |
|
38 | #------------------------------------------------------------------------------- | |
39 |
|
39 | |||
40 | import os |
|
40 | import os | |
41 |
|
41 | |||
42 | from twisted.application import service |
|
42 | from twisted.application import service | |
43 | from twisted.python import log |
|
43 | from twisted.python import log | |
44 | from zope.interface import Interface, implements, Attribute |
|
44 | from zope.interface import Interface, implements, Attribute | |
45 |
|
45 | |||
46 | from IPython.kernel.engineservice import \ |
|
46 | from IPython.kernel.engineservice import \ | |
47 | IEngineCore, \ |
|
47 | IEngineCore, \ | |
48 | IEngineSerialized, \ |
|
48 | IEngineSerialized, \ | |
49 | IEngineQueued |
|
49 | IEngineQueued | |
50 |
|
50 | |||
51 | from IPython.utils.path import get_ipython_dir |
|
51 | from IPython.utils.path import get_ipython_dir | |
52 | from IPython.kernel import codeutil |
|
52 | from IPython.kernel import codeutil | |
53 |
|
53 | |||
54 | #------------------------------------------------------------------------------- |
|
54 | #------------------------------------------------------------------------------- | |
55 | # Interfaces for the Controller |
|
55 | # Interfaces for the Controller | |
56 | #------------------------------------------------------------------------------- |
|
56 | #------------------------------------------------------------------------------- | |
57 |
|
57 | |||
58 | class IControllerCore(Interface): |
|
58 | class IControllerCore(Interface): | |
59 | """Basic methods any controller must have. |
|
59 | """Basic methods any controller must have. | |
60 |
|
60 | |||
61 | This is basically the aspect of the controller relevant to the |
|
61 | This is basically the aspect of the controller relevant to the | |
62 | engines and does not assume anything about how the engines will |
|
62 | engines and does not assume anything about how the engines will | |
63 | be presented to a client. |
|
63 | be presented to a client. | |
64 | """ |
|
64 | """ | |
65 |
|
65 | |||
66 | engines = Attribute("A dict of engine ids and engine instances.") |
|
66 | engines = Attribute("A dict of engine ids and engine instances.") | |
67 |
|
67 | |||
68 | def register_engine(remoteEngine, id=None, ip=None, port=None, |
|
68 | def register_engine(remoteEngine, id=None, ip=None, port=None, | |
69 | pid=None): |
|
69 | pid=None): | |
70 | """Register new remote engine. |
|
70 | """Register new remote engine. | |
71 |
|
71 | |||
72 | The controller can use the ip, port, pid of the engine to do useful things |
|
72 | The controller can use the ip, port, pid of the engine to do useful things | |
73 | like kill the engines. |
|
73 | like kill the engines. | |
74 |
|
74 | |||
75 | :Parameters: |
|
75 | :Parameters: | |
76 | remoteEngine |
|
76 | remoteEngine | |
77 | An implementer of IEngineCore, IEngineSerialized and IEngineQueued. |
|
77 | An implementer of IEngineCore, IEngineSerialized and IEngineQueued. | |
78 | id : int |
|
78 | id : int | |
79 | Requested id. |
|
79 | Requested id. | |
80 | ip : str |
|
80 | ip : str | |
81 | IP address the engine is running on. |
|
81 | IP address the engine is running on. | |
82 | port : int |
|
82 | port : int | |
83 | Port the engine is on. |
|
83 | Port the engine is on. | |
84 | pid : int |
|
84 | pid : int | |
85 | pid of the running engine. |
|
85 | pid of the running engine. | |
86 |
|
86 | |||
87 | :Returns: A dict of {'id':id} and possibly other key, value pairs. |
|
87 | :Returns: A dict of {'id':id} and possibly other key, value pairs. | |
88 | """ |
|
88 | """ | |
89 |
|
89 | |||
90 | def unregister_engine(id): |
|
90 | def unregister_engine(id): | |
91 | """Handle a disconnecting engine. |
|
91 | """Handle a disconnecting engine. | |
92 |
|
92 | |||
93 | :Parameters: |
|
93 | :Parameters: | |
94 | id |
|
94 | id | |
95 | The integer engine id of the engine to unregister. |
|
95 | The integer engine id of the engine to unregister. | |
96 | """ |
|
96 | """ | |
97 |
|
97 | |||
98 | def on_register_engine_do(f, includeID, *args, **kwargs): |
|
98 | def on_register_engine_do(f, includeID, *args, **kwargs): | |
99 | """Call ``f(*args, **kwargs)`` when an engine is registered. |
|
99 | """Call ``f(*args, **kwargs)`` when an engine is registered. | |
100 |
|
100 | |||
101 | :Parameters: |
|
101 | :Parameters: | |
102 | includeID : int |
|
102 | includeID : int | |
103 | If True the first argument to f will be the id of the engine. |
|
103 | If True the first argument to f will be the id of the engine. | |
104 | """ |
|
104 | """ | |
105 |
|
105 | |||
106 | def on_unregister_engine_do(f, includeID, *args, **kwargs): |
|
106 | def on_unregister_engine_do(f, includeID, *args, **kwargs): | |
107 | """Call ``f(*args, **kwargs)`` when an engine is unregistered. |
|
107 | """Call ``f(*args, **kwargs)`` when an engine is unregistered. | |
108 |
|
108 | |||
109 | :Parameters: |
|
109 | :Parameters: | |
110 | includeID : int |
|
110 | includeID : int | |
111 | If True the first argument to f will be the id of the engine. |
|
111 | If True the first argument to f will be the id of the engine. | |
112 | """ |
|
112 | """ | |
113 |
|
113 | |||
114 | def on_register_engine_do_not(f): |
|
114 | def on_register_engine_do_not(f): | |
115 | """Stop calling f on engine registration""" |
|
115 | """Stop calling f on engine registration""" | |
116 |
|
116 | |||
117 | def on_unregister_engine_do_not(f): |
|
117 | def on_unregister_engine_do_not(f): | |
118 | """Stop calling f on engine unregistration""" |
|
118 | """Stop calling f on engine unregistration""" | |
119 |
|
119 | |||
120 | def on_n_engines_registered_do(n, f, *arg, **kwargs): |
|
120 | def on_n_engines_registered_do(n, f, *arg, **kwargs): | |
121 | """Call f(*args, **kwargs) the first time the nth engine registers.""" |
|
121 | """Call f(*args, **kwargs) the first time the nth engine registers.""" | |
122 |
|
122 | |||
123 | class IControllerBase(IControllerCore): |
|
123 | class IControllerBase(IControllerCore): | |
124 | """The basic controller interface.""" |
|
124 | """The basic controller interface.""" | |
125 | pass |
|
125 | pass | |
126 |
|
126 | |||
127 |
|
127 | |||
128 | #------------------------------------------------------------------------------- |
|
128 | #------------------------------------------------------------------------------- | |
129 | # Implementation of the ControllerService |
|
129 | # Implementation of the ControllerService | |
130 | #------------------------------------------------------------------------------- |
|
130 | #------------------------------------------------------------------------------- | |
131 |
|
131 | |||
132 | class ControllerService(object, service.Service): |
|
132 | class ControllerService(object, service.Service): | |
133 | """A basic Controller represented as a Twisted Service. |
|
133 | """A basic Controller represented as a Twisted Service. | |
134 |
|
134 | |||
135 | This class doesn't implement any client notification mechanism. That |
|
135 | This class doesn't implement any client notification mechanism. That | |
136 | is up to adapted subclasses. |
|
136 | is up to adapted subclasses. | |
137 | """ |
|
137 | """ | |
138 |
|
138 | |||
139 | # I also pick up the IService interface by inheritance from service.Service |
|
139 | # I also pick up the IService interface by inheritance from service.Service | |
140 | implements(IControllerBase) |
|
140 | implements(IControllerBase) | |
141 | name = 'ControllerService' |
|
141 | name = 'ControllerService' | |
142 |
|
142 | |||
143 | def __init__(self, maxEngines=511, saveIDs=False): |
|
143 | def __init__(self, maxEngines=511, saveIDs=False): | |
144 | self.saveIDs = saveIDs |
|
144 | self.saveIDs = saveIDs | |
145 | self.engines = {} |
|
145 | self.engines = {} | |
146 | self.availableIDs = range(maxEngines,-1,-1) # [511,...,0] |
|
146 | self.availableIDs = range(maxEngines,-1,-1) # [511,...,0] | |
147 | self._onRegister = [] |
|
147 | self._onRegister = [] | |
148 | self._onUnregister = [] |
|
148 | self._onUnregister = [] | |
149 | self._onNRegistered = [] |
|
149 | self._onNRegistered = [] | |
150 |
|
150 | |||
151 | #--------------------------------------------------------------------------- |
|
151 | #--------------------------------------------------------------------------- | |
152 | # Methods used to save the engine info to a log file |
|
152 | # Methods used to save the engine info to a log file | |
153 | #--------------------------------------------------------------------------- |
|
153 | #--------------------------------------------------------------------------- | |
154 |
|
154 | |||
155 | def _buildEngineInfoString(self, id, ip, port, pid): |
|
155 | def _buildEngineInfoString(self, id, ip, port, pid): | |
156 | if id is None: |
|
156 | if id is None: | |
157 | id = -99 |
|
157 | id = -99 | |
158 | if ip is None: |
|
158 | if ip is None: | |
159 | ip = "-99" |
|
159 | ip = "-99" | |
160 | if port is None: |
|
160 | if port is None: | |
161 | port = -99 |
|
161 | port = -99 | |
162 | if pid is None: |
|
162 | if pid is None: | |
163 | pid = -99 |
|
163 | pid = -99 | |
164 | return "Engine Info: %d %s %d %d" % (id, ip , port, pid) |
|
164 | return "Engine Info: %d %s %d %d" % (id, ip , port, pid) | |
165 |
|
165 | |||
166 | def _logEngineInfo(self, id, ip, port, pid): |
|
166 | def _logEngineInfo(self, id, ip, port, pid): | |
167 | log.msg(self._buildEngineInfoString(id,ip,port,pid)) |
|
167 | log.msg(self._buildEngineInfoString(id,ip,port,pid)) | |
168 |
|
168 | |||
169 | def _getEngineInfoLogFile(self): |
|
169 | def _getEngineInfoLogFile(self): | |
170 | # Store all logs inside the ipython directory |
|
170 | # Store all logs inside the ipython directory | |
171 | ipdir = get_ipython_dir() |
|
171 | ipdir = get_ipython_dir() | |
172 | pjoin = os.path.join |
|
172 | pjoin = os.path.join | |
173 | logdir_base = pjoin(ipdir,'log') |
|
173 | logdir_base = pjoin(ipdir,'log') | |
174 | if not os.path.isdir(logdir_base): |
|
174 | if not os.path.isdir(logdir_base): | |
175 | os.makedirs(logdir_base) |
|
175 | os.makedirs(logdir_base) | |
176 | logfile = os.path.join(logdir_base,'ipcontroller-%s-engine-info.log' % os.getpid()) |
|
176 | logfile = os.path.join(logdir_base,'ipcontroller-%s-engine-info.log' % os.getpid()) | |
177 | return logfile |
|
177 | return logfile | |
178 |
|
178 | |||
179 | def _logEngineInfoToFile(self, id, ip, port, pid): |
|
179 | def _logEngineInfoToFile(self, id, ip, port, pid): | |
180 | """Log info about an engine to a log file. |
|
180 | """Log info about an engine to a log file. | |
181 |
|
181 | |||
182 | When an engine registers with a ControllerService, the ControllerService |
|
182 | When an engine registers with a ControllerService, the ControllerService | |
183 | saves information about the engine to a log file. That information |
|
183 | saves information about the engine to a log file. That information | |
184 | can be useful for various purposes, such as killing hung engines, etc. |
|
184 | can be useful for various purposes, such as killing hung engines, etc. | |
185 |
|
185 | |||
186 | This method takes the assigned id, ip/port and pid of the engine |
|
186 | This method takes the assigned id, ip/port and pid of the engine | |
187 | and saves it to a file of the form: |
|
187 | and saves it to a file of the form: | |
188 |
|
188 | |||
189 |
|
|
189 | IPYTHON_DIR/log/ipcontroller-###-engine-info.log | |
190 |
|
190 | |||
191 | where ### is the pid of the controller. |
|
191 | where ### is the pid of the controller. | |
192 |
|
192 | |||
193 | Each line of this file has the form: |
|
193 | Each line of this file has the form: | |
194 |
|
194 | |||
195 | Engine Info: ip ip port pid |
|
195 | Engine Info: ip ip port pid | |
196 |
|
196 | |||
197 | If any of the entries are not known, they are replaced by -99. |
|
197 | If any of the entries are not known, they are replaced by -99. | |
198 | """ |
|
198 | """ | |
199 |
|
199 | |||
200 | fname = self._getEngineInfoLogFile() |
|
200 | fname = self._getEngineInfoLogFile() | |
201 | f = open(fname, 'a') |
|
201 | f = open(fname, 'a') | |
202 | s = self._buildEngineInfoString(id,ip,port,pid) |
|
202 | s = self._buildEngineInfoString(id,ip,port,pid) | |
203 | f.write(s + '\n') |
|
203 | f.write(s + '\n') | |
204 | f.close() |
|
204 | f.close() | |
205 |
|
205 | |||
206 | #--------------------------------------------------------------------------- |
|
206 | #--------------------------------------------------------------------------- | |
207 | # IControllerCore methods |
|
207 | # IControllerCore methods | |
208 | #--------------------------------------------------------------------------- |
|
208 | #--------------------------------------------------------------------------- | |
209 |
|
209 | |||
210 | def register_engine(self, remoteEngine, id=None, |
|
210 | def register_engine(self, remoteEngine, id=None, | |
211 | ip=None, port=None, pid=None): |
|
211 | ip=None, port=None, pid=None): | |
212 | """Register new engine connection""" |
|
212 | """Register new engine connection""" | |
213 |
|
213 | |||
214 | # What happens if these assertions fail? |
|
214 | # What happens if these assertions fail? | |
215 | assert IEngineCore.providedBy(remoteEngine), \ |
|
215 | assert IEngineCore.providedBy(remoteEngine), \ | |
216 | "engine passed to register_engine doesn't provide IEngineCore" |
|
216 | "engine passed to register_engine doesn't provide IEngineCore" | |
217 | assert IEngineSerialized.providedBy(remoteEngine), \ |
|
217 | assert IEngineSerialized.providedBy(remoteEngine), \ | |
218 | "engine passed to register_engine doesn't provide IEngineSerialized" |
|
218 | "engine passed to register_engine doesn't provide IEngineSerialized" | |
219 | assert IEngineQueued.providedBy(remoteEngine), \ |
|
219 | assert IEngineQueued.providedBy(remoteEngine), \ | |
220 | "engine passed to register_engine doesn't provide IEngineQueued" |
|
220 | "engine passed to register_engine doesn't provide IEngineQueued" | |
221 | assert isinstance(id, int) or id is None, \ |
|
221 | assert isinstance(id, int) or id is None, \ | |
222 | "id to register_engine must be an integer or None" |
|
222 | "id to register_engine must be an integer or None" | |
223 | assert isinstance(ip, str) or ip is None, \ |
|
223 | assert isinstance(ip, str) or ip is None, \ | |
224 | "ip to register_engine must be a string or None" |
|
224 | "ip to register_engine must be a string or None" | |
225 | assert isinstance(port, int) or port is None, \ |
|
225 | assert isinstance(port, int) or port is None, \ | |
226 | "port to register_engine must be an integer or None" |
|
226 | "port to register_engine must be an integer or None" | |
227 | assert isinstance(pid, int) or pid is None, \ |
|
227 | assert isinstance(pid, int) or pid is None, \ | |
228 | "pid to register_engine must be an integer or None" |
|
228 | "pid to register_engine must be an integer or None" | |
229 |
|
229 | |||
230 | desiredID = id |
|
230 | desiredID = id | |
231 | if desiredID in self.engines.keys(): |
|
231 | if desiredID in self.engines.keys(): | |
232 | desiredID = None |
|
232 | desiredID = None | |
233 |
|
233 | |||
234 | if desiredID in self.availableIDs: |
|
234 | if desiredID in self.availableIDs: | |
235 | getID = desiredID |
|
235 | getID = desiredID | |
236 | self.availableIDs.remove(desiredID) |
|
236 | self.availableIDs.remove(desiredID) | |
237 | else: |
|
237 | else: | |
238 | getID = self.availableIDs.pop() |
|
238 | getID = self.availableIDs.pop() | |
239 | remoteEngine.id = getID |
|
239 | remoteEngine.id = getID | |
240 | remoteEngine.service = self |
|
240 | remoteEngine.service = self | |
241 | self.engines[getID] = remoteEngine |
|
241 | self.engines[getID] = remoteEngine | |
242 |
|
242 | |||
243 | # Log the Engine Information for monitoring purposes |
|
243 | # Log the Engine Information for monitoring purposes | |
244 | self._logEngineInfoToFile(getID, ip, port, pid) |
|
244 | self._logEngineInfoToFile(getID, ip, port, pid) | |
245 |
|
245 | |||
246 | msg = "registered engine with id: %i" %getID |
|
246 | msg = "registered engine with id: %i" %getID | |
247 | log.msg(msg) |
|
247 | log.msg(msg) | |
248 |
|
248 | |||
249 | for i in range(len(self._onRegister)): |
|
249 | for i in range(len(self._onRegister)): | |
250 | (f,args,kwargs,ifid) = self._onRegister[i] |
|
250 | (f,args,kwargs,ifid) = self._onRegister[i] | |
251 | try: |
|
251 | try: | |
252 | if ifid: |
|
252 | if ifid: | |
253 | f(getID, *args, **kwargs) |
|
253 | f(getID, *args, **kwargs) | |
254 | else: |
|
254 | else: | |
255 | f(*args, **kwargs) |
|
255 | f(*args, **kwargs) | |
256 | except: |
|
256 | except: | |
257 | self._onRegister.pop(i) |
|
257 | self._onRegister.pop(i) | |
258 |
|
258 | |||
259 | # Call functions when the nth engine is registered and them remove them |
|
259 | # Call functions when the nth engine is registered and them remove them | |
260 | for i, (n, f, args, kwargs) in enumerate(self._onNRegistered): |
|
260 | for i, (n, f, args, kwargs) in enumerate(self._onNRegistered): | |
261 | if len(self.engines.keys()) == n: |
|
261 | if len(self.engines.keys()) == n: | |
262 | try: |
|
262 | try: | |
263 | try: |
|
263 | try: | |
264 | f(*args, **kwargs) |
|
264 | f(*args, **kwargs) | |
265 | except: |
|
265 | except: | |
266 | log.msg("Function %r failed when the %ith engine registered" % (f, n)) |
|
266 | log.msg("Function %r failed when the %ith engine registered" % (f, n)) | |
267 | finally: |
|
267 | finally: | |
268 | self._onNRegistered.pop(i) |
|
268 | self._onNRegistered.pop(i) | |
269 |
|
269 | |||
270 | return {'id':getID} |
|
270 | return {'id':getID} | |
271 |
|
271 | |||
272 | def unregister_engine(self, id): |
|
272 | def unregister_engine(self, id): | |
273 | """Unregister engine by id.""" |
|
273 | """Unregister engine by id.""" | |
274 |
|
274 | |||
275 | assert isinstance(id, int) or id is None, \ |
|
275 | assert isinstance(id, int) or id is None, \ | |
276 | "id to unregister_engine must be an integer or None" |
|
276 | "id to unregister_engine must be an integer or None" | |
277 |
|
277 | |||
278 | msg = "unregistered engine with id: %i" %id |
|
278 | msg = "unregistered engine with id: %i" %id | |
279 | log.msg(msg) |
|
279 | log.msg(msg) | |
280 | try: |
|
280 | try: | |
281 | del self.engines[id] |
|
281 | del self.engines[id] | |
282 | except KeyError: |
|
282 | except KeyError: | |
283 | log.msg("engine with id %i was not registered" % id) |
|
283 | log.msg("engine with id %i was not registered" % id) | |
284 | else: |
|
284 | else: | |
285 | if not self.saveIDs: |
|
285 | if not self.saveIDs: | |
286 | self.availableIDs.append(id) |
|
286 | self.availableIDs.append(id) | |
287 | # Sort to assign lower ids first |
|
287 | # Sort to assign lower ids first | |
288 | self.availableIDs.sort(reverse=True) |
|
288 | self.availableIDs.sort(reverse=True) | |
289 | else: |
|
289 | else: | |
290 | log.msg("preserving id %i" %id) |
|
290 | log.msg("preserving id %i" %id) | |
291 |
|
291 | |||
292 | for i in range(len(self._onUnregister)): |
|
292 | for i in range(len(self._onUnregister)): | |
293 | (f,args,kwargs,ifid) = self._onUnregister[i] |
|
293 | (f,args,kwargs,ifid) = self._onUnregister[i] | |
294 | try: |
|
294 | try: | |
295 | if ifid: |
|
295 | if ifid: | |
296 | f(id, *args, **kwargs) |
|
296 | f(id, *args, **kwargs) | |
297 | else: |
|
297 | else: | |
298 | f(*args, **kwargs) |
|
298 | f(*args, **kwargs) | |
299 | except: |
|
299 | except: | |
300 | self._onUnregister.pop(i) |
|
300 | self._onUnregister.pop(i) | |
301 |
|
301 | |||
302 | def on_register_engine_do(self, f, includeID, *args, **kwargs): |
|
302 | def on_register_engine_do(self, f, includeID, *args, **kwargs): | |
303 | assert callable(f), "f must be callable" |
|
303 | assert callable(f), "f must be callable" | |
304 | self._onRegister.append((f,args,kwargs,includeID)) |
|
304 | self._onRegister.append((f,args,kwargs,includeID)) | |
305 |
|
305 | |||
306 | def on_unregister_engine_do(self, f, includeID, *args, **kwargs): |
|
306 | def on_unregister_engine_do(self, f, includeID, *args, **kwargs): | |
307 | assert callable(f), "f must be callable" |
|
307 | assert callable(f), "f must be callable" | |
308 | self._onUnregister.append((f,args,kwargs,includeID)) |
|
308 | self._onUnregister.append((f,args,kwargs,includeID)) | |
309 |
|
309 | |||
310 | def on_register_engine_do_not(self, f): |
|
310 | def on_register_engine_do_not(self, f): | |
311 | for i in range(len(self._onRegister)): |
|
311 | for i in range(len(self._onRegister)): | |
312 | g = self._onRegister[i][0] |
|
312 | g = self._onRegister[i][0] | |
313 | if f == g: |
|
313 | if f == g: | |
314 | self._onRegister.pop(i) |
|
314 | self._onRegister.pop(i) | |
315 | return |
|
315 | return | |
316 |
|
316 | |||
317 | def on_unregister_engine_do_not(self, f): |
|
317 | def on_unregister_engine_do_not(self, f): | |
318 | for i in range(len(self._onUnregister)): |
|
318 | for i in range(len(self._onUnregister)): | |
319 | g = self._onUnregister[i][0] |
|
319 | g = self._onUnregister[i][0] | |
320 | if f == g: |
|
320 | if f == g: | |
321 | self._onUnregister.pop(i) |
|
321 | self._onUnregister.pop(i) | |
322 | return |
|
322 | return | |
323 |
|
323 | |||
324 | def on_n_engines_registered_do(self, n, f, *args, **kwargs): |
|
324 | def on_n_engines_registered_do(self, n, f, *args, **kwargs): | |
325 | if len(self.engines.keys()) >= n: |
|
325 | if len(self.engines.keys()) >= n: | |
326 | f(*args, **kwargs) |
|
326 | f(*args, **kwargs) | |
327 | else: |
|
327 | else: | |
328 | self._onNRegistered.append((n,f,args,kwargs)) |
|
328 | self._onNRegistered.append((n,f,args,kwargs)) | |
329 |
|
329 | |||
330 |
|
330 | |||
331 | #------------------------------------------------------------------------------- |
|
331 | #------------------------------------------------------------------------------- | |
332 | # Base class for adapting controller to different client APIs |
|
332 | # Base class for adapting controller to different client APIs | |
333 | #------------------------------------------------------------------------------- |
|
333 | #------------------------------------------------------------------------------- | |
334 |
|
334 | |||
335 | class ControllerAdapterBase(object): |
|
335 | class ControllerAdapterBase(object): | |
336 | """All Controller adapters should inherit from this class. |
|
336 | """All Controller adapters should inherit from this class. | |
337 |
|
337 | |||
338 | This class provides a wrapped version of the IControllerBase interface that |
|
338 | This class provides a wrapped version of the IControllerBase interface that | |
339 | can be used to easily create new custom controllers. Subclasses of this |
|
339 | can be used to easily create new custom controllers. Subclasses of this | |
340 | will provide a full implementation of IControllerBase. |
|
340 | will provide a full implementation of IControllerBase. | |
341 |
|
341 | |||
342 | This class doesn't implement any client notification mechanism. That |
|
342 | This class doesn't implement any client notification mechanism. That | |
343 | is up to subclasses. |
|
343 | is up to subclasses. | |
344 | """ |
|
344 | """ | |
345 |
|
345 | |||
346 | implements(IControllerBase) |
|
346 | implements(IControllerBase) | |
347 |
|
347 | |||
348 | def __init__(self, controller): |
|
348 | def __init__(self, controller): | |
349 | self.controller = controller |
|
349 | self.controller = controller | |
350 | # Needed for IControllerCore |
|
350 | # Needed for IControllerCore | |
351 | self.engines = self.controller.engines |
|
351 | self.engines = self.controller.engines | |
352 |
|
352 | |||
353 | def register_engine(self, remoteEngine, id=None, |
|
353 | def register_engine(self, remoteEngine, id=None, | |
354 | ip=None, port=None, pid=None): |
|
354 | ip=None, port=None, pid=None): | |
355 | return self.controller.register_engine(remoteEngine, |
|
355 | return self.controller.register_engine(remoteEngine, | |
356 | id, ip, port, pid) |
|
356 | id, ip, port, pid) | |
357 |
|
357 | |||
358 | def unregister_engine(self, id): |
|
358 | def unregister_engine(self, id): | |
359 | return self.controller.unregister_engine(id) |
|
359 | return self.controller.unregister_engine(id) | |
360 |
|
360 | |||
361 | def on_register_engine_do(self, f, includeID, *args, **kwargs): |
|
361 | def on_register_engine_do(self, f, includeID, *args, **kwargs): | |
362 | return self.controller.on_register_engine_do(f, includeID, *args, **kwargs) |
|
362 | return self.controller.on_register_engine_do(f, includeID, *args, **kwargs) | |
363 |
|
363 | |||
364 | def on_unregister_engine_do(self, f, includeID, *args, **kwargs): |
|
364 | def on_unregister_engine_do(self, f, includeID, *args, **kwargs): | |
365 | return self.controller.on_unregister_engine_do(f, includeID, *args, **kwargs) |
|
365 | return self.controller.on_unregister_engine_do(f, includeID, *args, **kwargs) | |
366 |
|
366 | |||
367 | def on_register_engine_do_not(self, f): |
|
367 | def on_register_engine_do_not(self, f): | |
368 | return self.controller.on_register_engine_do_not(f) |
|
368 | return self.controller.on_register_engine_do_not(f) | |
369 |
|
369 | |||
370 | def on_unregister_engine_do_not(self, f): |
|
370 | def on_unregister_engine_do_not(self, f): | |
371 | return self.controller.on_unregister_engine_do_not(f) |
|
371 | return self.controller.on_unregister_engine_do_not(f) | |
372 |
|
372 | |||
373 | def on_n_engines_registered_do(self, n, f, *args, **kwargs): |
|
373 | def on_n_engines_registered_do(self, n, f, *args, **kwargs): | |
374 | return self.controller.on_n_engines_registered_do(n, f, *args, **kwargs) |
|
374 | return self.controller.on_n_engines_registered_do(n, f, *args, **kwargs) |
@@ -1,271 +1,271 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | The IPython controller application. |
|
4 | The IPython controller application. | |
5 | """ |
|
5 | """ | |
6 |
|
6 | |||
7 | #----------------------------------------------------------------------------- |
|
7 | #----------------------------------------------------------------------------- | |
8 | # Copyright (C) 2008-2009 The IPython Development Team |
|
8 | # Copyright (C) 2008-2009 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 | from __future__ import with_statement |
|
18 | from __future__ import with_statement | |
19 |
|
19 | |||
20 | import copy |
|
20 | import copy | |
21 | import sys |
|
21 | import sys | |
22 |
|
22 | |||
23 | from twisted.application import service |
|
23 | from twisted.application import service | |
24 | from twisted.internet import reactor |
|
24 | from twisted.internet import reactor | |
25 | from twisted.python import log |
|
25 | from twisted.python import log | |
26 |
|
26 | |||
27 | from IPython.config.loader import Config |
|
27 | from IPython.config.loader import Config | |
28 | from IPython.kernel import controllerservice |
|
28 | from IPython.kernel import controllerservice | |
29 | from IPython.kernel.clusterdir import ( |
|
29 | from IPython.kernel.clusterdir import ( | |
30 | ApplicationWithClusterDir, |
|
30 | ApplicationWithClusterDir, | |
31 | ClusterDirConfigLoader |
|
31 | ClusterDirConfigLoader | |
32 | ) |
|
32 | ) | |
33 | from IPython.kernel.fcutil import FCServiceFactory, FURLError |
|
33 | from IPython.kernel.fcutil import FCServiceFactory, FURLError | |
34 | from IPython.utils.traitlets import Instance, Unicode |
|
34 | from IPython.utils.traitlets import Instance, Unicode | |
35 |
|
35 | |||
36 |
|
36 | |||
37 | #----------------------------------------------------------------------------- |
|
37 | #----------------------------------------------------------------------------- | |
38 | # Module level variables |
|
38 | # Module level variables | |
39 | #----------------------------------------------------------------------------- |
|
39 | #----------------------------------------------------------------------------- | |
40 |
|
40 | |||
41 |
|
41 | |||
42 | #: The default config file name for this application |
|
42 | #: The default config file name for this application | |
43 | default_config_file_name = u'ipcontroller_config.py' |
|
43 | default_config_file_name = u'ipcontroller_config.py' | |
44 |
|
44 | |||
45 |
|
45 | |||
46 | _description = """Start the IPython controller for parallel computing. |
|
46 | _description = """Start the IPython controller for parallel computing. | |
47 |
|
47 | |||
48 | The IPython controller provides a gateway between the IPython engines and |
|
48 | The IPython controller provides a gateway between the IPython engines and | |
49 | clients. The controller needs to be started before the engines and can be |
|
49 | clients. The controller needs to be started before the engines and can be | |
50 | configured using command line options or using a cluster directory. Cluster |
|
50 | configured using command line options or using a cluster directory. Cluster | |
51 | directories contain config, log and security files and are usually located in |
|
51 | directories contain config, log and security files and are usually located in | |
52 |
your |
|
52 | your ipython directory and named as "cluster_<profile>". See the --profile | |
53 | and --cluster-dir options for details. |
|
53 | and --cluster-dir options for details. | |
54 | """ |
|
54 | """ | |
55 |
|
55 | |||
56 | #----------------------------------------------------------------------------- |
|
56 | #----------------------------------------------------------------------------- | |
57 | # Default interfaces |
|
57 | # Default interfaces | |
58 | #----------------------------------------------------------------------------- |
|
58 | #----------------------------------------------------------------------------- | |
59 |
|
59 | |||
60 | # The default client interfaces for FCClientServiceFactory.interfaces |
|
60 | # The default client interfaces for FCClientServiceFactory.interfaces | |
61 | default_client_interfaces = Config() |
|
61 | default_client_interfaces = Config() | |
62 | default_client_interfaces.Task.interface_chain = [ |
|
62 | default_client_interfaces.Task.interface_chain = [ | |
63 | 'IPython.kernel.task.ITaskController', |
|
63 | 'IPython.kernel.task.ITaskController', | |
64 | 'IPython.kernel.taskfc.IFCTaskController' |
|
64 | 'IPython.kernel.taskfc.IFCTaskController' | |
65 | ] |
|
65 | ] | |
66 |
|
66 | |||
67 | default_client_interfaces.Task.furl_file = 'ipcontroller-tc.furl' |
|
67 | default_client_interfaces.Task.furl_file = 'ipcontroller-tc.furl' | |
68 |
|
68 | |||
69 | default_client_interfaces.MultiEngine.interface_chain = [ |
|
69 | default_client_interfaces.MultiEngine.interface_chain = [ | |
70 | 'IPython.kernel.multiengine.IMultiEngine', |
|
70 | 'IPython.kernel.multiengine.IMultiEngine', | |
71 | 'IPython.kernel.multienginefc.IFCSynchronousMultiEngine' |
|
71 | 'IPython.kernel.multienginefc.IFCSynchronousMultiEngine' | |
72 | ] |
|
72 | ] | |
73 |
|
73 | |||
74 | default_client_interfaces.MultiEngine.furl_file = u'ipcontroller-mec.furl' |
|
74 | default_client_interfaces.MultiEngine.furl_file = u'ipcontroller-mec.furl' | |
75 |
|
75 | |||
76 | # Make this a dict we can pass to Config.__init__ for the default |
|
76 | # Make this a dict we can pass to Config.__init__ for the default | |
77 | default_client_interfaces = dict(copy.deepcopy(default_client_interfaces.items())) |
|
77 | default_client_interfaces = dict(copy.deepcopy(default_client_interfaces.items())) | |
78 |
|
78 | |||
79 |
|
79 | |||
80 |
|
80 | |||
81 | # The default engine interfaces for FCEngineServiceFactory.interfaces |
|
81 | # The default engine interfaces for FCEngineServiceFactory.interfaces | |
82 | default_engine_interfaces = Config() |
|
82 | default_engine_interfaces = Config() | |
83 | default_engine_interfaces.Default.interface_chain = [ |
|
83 | default_engine_interfaces.Default.interface_chain = [ | |
84 | 'IPython.kernel.enginefc.IFCControllerBase' |
|
84 | 'IPython.kernel.enginefc.IFCControllerBase' | |
85 | ] |
|
85 | ] | |
86 |
|
86 | |||
87 | default_engine_interfaces.Default.furl_file = u'ipcontroller-engine.furl' |
|
87 | default_engine_interfaces.Default.furl_file = u'ipcontroller-engine.furl' | |
88 |
|
88 | |||
89 | # Make this a dict we can pass to Config.__init__ for the default |
|
89 | # Make this a dict we can pass to Config.__init__ for the default | |
90 | default_engine_interfaces = dict(copy.deepcopy(default_engine_interfaces.items())) |
|
90 | default_engine_interfaces = dict(copy.deepcopy(default_engine_interfaces.items())) | |
91 |
|
91 | |||
92 |
|
92 | |||
93 | #----------------------------------------------------------------------------- |
|
93 | #----------------------------------------------------------------------------- | |
94 | # Service factories |
|
94 | # Service factories | |
95 | #----------------------------------------------------------------------------- |
|
95 | #----------------------------------------------------------------------------- | |
96 |
|
96 | |||
97 |
|
97 | |||
98 | class FCClientServiceFactory(FCServiceFactory): |
|
98 | class FCClientServiceFactory(FCServiceFactory): | |
99 | """A Foolscap implementation of the client services.""" |
|
99 | """A Foolscap implementation of the client services.""" | |
100 |
|
100 | |||
101 | cert_file = Unicode(u'ipcontroller-client.pem', config=True) |
|
101 | cert_file = Unicode(u'ipcontroller-client.pem', config=True) | |
102 | interfaces = Instance(klass=Config, kw=default_client_interfaces, |
|
102 | interfaces = Instance(klass=Config, kw=default_client_interfaces, | |
103 | allow_none=False, config=True) |
|
103 | allow_none=False, config=True) | |
104 |
|
104 | |||
105 |
|
105 | |||
106 | class FCEngineServiceFactory(FCServiceFactory): |
|
106 | class FCEngineServiceFactory(FCServiceFactory): | |
107 | """A Foolscap implementation of the engine services.""" |
|
107 | """A Foolscap implementation of the engine services.""" | |
108 |
|
108 | |||
109 | cert_file = Unicode(u'ipcontroller-engine.pem', config=True) |
|
109 | cert_file = Unicode(u'ipcontroller-engine.pem', config=True) | |
110 | interfaces = Instance(klass=dict, kw=default_engine_interfaces, |
|
110 | interfaces = Instance(klass=dict, kw=default_engine_interfaces, | |
111 | allow_none=False, config=True) |
|
111 | allow_none=False, config=True) | |
112 |
|
112 | |||
113 |
|
113 | |||
114 | #----------------------------------------------------------------------------- |
|
114 | #----------------------------------------------------------------------------- | |
115 | # Command line options |
|
115 | # Command line options | |
116 | #----------------------------------------------------------------------------- |
|
116 | #----------------------------------------------------------------------------- | |
117 |
|
117 | |||
118 |
|
118 | |||
119 | class IPControllerAppConfigLoader(ClusterDirConfigLoader): |
|
119 | class IPControllerAppConfigLoader(ClusterDirConfigLoader): | |
120 |
|
120 | |||
121 | def _add_arguments(self): |
|
121 | def _add_arguments(self): | |
122 | super(IPControllerAppConfigLoader, self)._add_arguments() |
|
122 | super(IPControllerAppConfigLoader, self)._add_arguments() | |
123 | paa = self.parser.add_argument |
|
123 | paa = self.parser.add_argument | |
124 | # Client config |
|
124 | # Client config | |
125 | paa('--client-ip', |
|
125 | paa('--client-ip', | |
126 | type=str, dest='FCClientServiceFactory.ip', |
|
126 | type=str, dest='FCClientServiceFactory.ip', | |
127 | help='The IP address or hostname the controller will listen on for ' |
|
127 | help='The IP address or hostname the controller will listen on for ' | |
128 | 'client connections.', |
|
128 | 'client connections.', | |
129 | metavar='FCClientServiceFactory.ip') |
|
129 | metavar='FCClientServiceFactory.ip') | |
130 | paa('--client-port', |
|
130 | paa('--client-port', | |
131 | type=int, dest='FCClientServiceFactory.port', |
|
131 | type=int, dest='FCClientServiceFactory.port', | |
132 | help='The port the controller will listen on for client connections. ' |
|
132 | help='The port the controller will listen on for client connections. ' | |
133 | 'The default is to use 0, which will autoselect an open port.', |
|
133 | 'The default is to use 0, which will autoselect an open port.', | |
134 | metavar='FCClientServiceFactory.port') |
|
134 | metavar='FCClientServiceFactory.port') | |
135 | paa('--client-location',), dict( |
|
135 | paa('--client-location',), dict( | |
136 | type=str, dest='FCClientServiceFactory.location', |
|
136 | type=str, dest='FCClientServiceFactory.location', | |
137 | help='The hostname or IP that clients should connect to. This does ' |
|
137 | help='The hostname or IP that clients should connect to. This does ' | |
138 | 'not control which interface the controller listens on. Instead, this ' |
|
138 | 'not control which interface the controller listens on. Instead, this ' | |
139 | 'determines the hostname/IP that is listed in the FURL, which is how ' |
|
139 | 'determines the hostname/IP that is listed in the FURL, which is how ' | |
140 | 'clients know where to connect. Useful if the controller is listening ' |
|
140 | 'clients know where to connect. Useful if the controller is listening ' | |
141 | 'on multiple interfaces.', |
|
141 | 'on multiple interfaces.', | |
142 | metavar='FCClientServiceFactory.location') |
|
142 | metavar='FCClientServiceFactory.location') | |
143 | # Engine config |
|
143 | # Engine config | |
144 | paa('--engine-ip', |
|
144 | paa('--engine-ip', | |
145 | type=str, dest='FCEngineServiceFactory.ip', |
|
145 | type=str, dest='FCEngineServiceFactory.ip', | |
146 | help='The IP address or hostname the controller will listen on for ' |
|
146 | help='The IP address or hostname the controller will listen on for ' | |
147 | 'engine connections.', |
|
147 | 'engine connections.', | |
148 | metavar='FCEngineServiceFactory.ip') |
|
148 | metavar='FCEngineServiceFactory.ip') | |
149 | paa('--engine-port', |
|
149 | paa('--engine-port', | |
150 | type=int, dest='FCEngineServiceFactory.port', |
|
150 | type=int, dest='FCEngineServiceFactory.port', | |
151 | help='The port the controller will listen on for engine connections. ' |
|
151 | help='The port the controller will listen on for engine connections. ' | |
152 | 'The default is to use 0, which will autoselect an open port.', |
|
152 | 'The default is to use 0, which will autoselect an open port.', | |
153 | metavar='FCEngineServiceFactory.port') |
|
153 | metavar='FCEngineServiceFactory.port') | |
154 | paa('--engine-location', |
|
154 | paa('--engine-location', | |
155 | type=str, dest='FCEngineServiceFactory.location', |
|
155 | type=str, dest='FCEngineServiceFactory.location', | |
156 | help='The hostname or IP that engines should connect to. This does ' |
|
156 | help='The hostname or IP that engines should connect to. This does ' | |
157 | 'not control which interface the controller listens on. Instead, this ' |
|
157 | 'not control which interface the controller listens on. Instead, this ' | |
158 | 'determines the hostname/IP that is listed in the FURL, which is how ' |
|
158 | 'determines the hostname/IP that is listed in the FURL, which is how ' | |
159 | 'engines know where to connect. Useful if the controller is listening ' |
|
159 | 'engines know where to connect. Useful if the controller is listening ' | |
160 | 'on multiple interfaces.', |
|
160 | 'on multiple interfaces.', | |
161 | metavar='FCEngineServiceFactory.location') |
|
161 | metavar='FCEngineServiceFactory.location') | |
162 | # Global config |
|
162 | # Global config | |
163 | paa('--log-to-file', |
|
163 | paa('--log-to-file', | |
164 | action='store_true', dest='Global.log_to_file', |
|
164 | action='store_true', dest='Global.log_to_file', | |
165 | help='Log to a file in the log directory (default is stdout)') |
|
165 | help='Log to a file in the log directory (default is stdout)') | |
166 | paa('-r','--reuse-furls', |
|
166 | paa('-r','--reuse-furls', | |
167 | action='store_true', dest='Global.reuse_furls', |
|
167 | action='store_true', dest='Global.reuse_furls', | |
168 | help='Try to reuse all FURL files. If this is not set all FURL files ' |
|
168 | help='Try to reuse all FURL files. If this is not set all FURL files ' | |
169 | 'are deleted before the controller starts. This must be set if ' |
|
169 | 'are deleted before the controller starts. This must be set if ' | |
170 | 'specific ports are specified by --engine-port or --client-port.') |
|
170 | 'specific ports are specified by --engine-port or --client-port.') | |
171 | paa('--no-secure', |
|
171 | paa('--no-secure', | |
172 | action='store_false', dest='Global.secure', |
|
172 | action='store_false', dest='Global.secure', | |
173 | help='Turn off SSL encryption for all connections.') |
|
173 | help='Turn off SSL encryption for all connections.') | |
174 | paa('--secure', |
|
174 | paa('--secure', | |
175 | action='store_true', dest='Global.secure', |
|
175 | action='store_true', dest='Global.secure', | |
176 | help='Turn off SSL encryption for all connections.') |
|
176 | help='Turn off SSL encryption for all connections.') | |
177 |
|
177 | |||
178 |
|
178 | |||
179 | #----------------------------------------------------------------------------- |
|
179 | #----------------------------------------------------------------------------- | |
180 | # The main application |
|
180 | # The main application | |
181 | #----------------------------------------------------------------------------- |
|
181 | #----------------------------------------------------------------------------- | |
182 |
|
182 | |||
183 |
|
183 | |||
184 | class IPControllerApp(ApplicationWithClusterDir): |
|
184 | class IPControllerApp(ApplicationWithClusterDir): | |
185 |
|
185 | |||
186 | name = u'ipcontroller' |
|
186 | name = u'ipcontroller' | |
187 | description = _description |
|
187 | description = _description | |
188 | command_line_loader = IPControllerAppConfigLoader |
|
188 | command_line_loader = IPControllerAppConfigLoader | |
189 | default_config_file_name = default_config_file_name |
|
189 | default_config_file_name = default_config_file_name | |
190 | auto_create_cluster_dir = True |
|
190 | auto_create_cluster_dir = True | |
191 |
|
191 | |||
192 | def create_default_config(self): |
|
192 | def create_default_config(self): | |
193 | super(IPControllerApp, self).create_default_config() |
|
193 | super(IPControllerApp, self).create_default_config() | |
194 | # Don't set defaults for Global.secure or Global.reuse_furls |
|
194 | # Don't set defaults for Global.secure or Global.reuse_furls | |
195 | # as those are set in a component. |
|
195 | # as those are set in a component. | |
196 | self.default_config.Global.import_statements = [] |
|
196 | self.default_config.Global.import_statements = [] | |
197 | self.default_config.Global.clean_logs = True |
|
197 | self.default_config.Global.clean_logs = True | |
198 |
|
198 | |||
199 | def pre_construct(self): |
|
199 | def pre_construct(self): | |
200 | super(IPControllerApp, self).pre_construct() |
|
200 | super(IPControllerApp, self).pre_construct() | |
201 | c = self.master_config |
|
201 | c = self.master_config | |
202 | # The defaults for these are set in FCClientServiceFactory and |
|
202 | # The defaults for these are set in FCClientServiceFactory and | |
203 | # FCEngineServiceFactory, so we only set them here if the global |
|
203 | # FCEngineServiceFactory, so we only set them here if the global | |
204 | # options have be set to override the class level defaults. |
|
204 | # options have be set to override the class level defaults. | |
205 | if hasattr(c.Global, 'reuse_furls'): |
|
205 | if hasattr(c.Global, 'reuse_furls'): | |
206 | c.FCClientServiceFactory.reuse_furls = c.Global.reuse_furls |
|
206 | c.FCClientServiceFactory.reuse_furls = c.Global.reuse_furls | |
207 | c.FCEngineServiceFactory.reuse_furls = c.Global.reuse_furls |
|
207 | c.FCEngineServiceFactory.reuse_furls = c.Global.reuse_furls | |
208 | del c.Global.reuse_furls |
|
208 | del c.Global.reuse_furls | |
209 | if hasattr(c.Global, 'secure'): |
|
209 | if hasattr(c.Global, 'secure'): | |
210 | c.FCClientServiceFactory.secure = c.Global.secure |
|
210 | c.FCClientServiceFactory.secure = c.Global.secure | |
211 | c.FCEngineServiceFactory.secure = c.Global.secure |
|
211 | c.FCEngineServiceFactory.secure = c.Global.secure | |
212 | del c.Global.secure |
|
212 | del c.Global.secure | |
213 |
|
213 | |||
214 | def construct(self): |
|
214 | def construct(self): | |
215 | # This is the working dir by now. |
|
215 | # This is the working dir by now. | |
216 | sys.path.insert(0, '') |
|
216 | sys.path.insert(0, '') | |
217 |
|
217 | |||
218 | self.start_logging() |
|
218 | self.start_logging() | |
219 | self.import_statements() |
|
219 | self.import_statements() | |
220 |
|
220 | |||
221 | # Create the service hierarchy |
|
221 | # Create the service hierarchy | |
222 | self.main_service = service.MultiService() |
|
222 | self.main_service = service.MultiService() | |
223 | # The controller service |
|
223 | # The controller service | |
224 | controller_service = controllerservice.ControllerService() |
|
224 | controller_service = controllerservice.ControllerService() | |
225 | controller_service.setServiceParent(self.main_service) |
|
225 | controller_service.setServiceParent(self.main_service) | |
226 | # The client tub and all its refereceables |
|
226 | # The client tub and all its refereceables | |
227 | try: |
|
227 | try: | |
228 | csfactory = FCClientServiceFactory(config=self.master_config, adaptee=controller_service) |
|
228 | csfactory = FCClientServiceFactory(config=self.master_config, adaptee=controller_service) | |
229 | except FURLError, e: |
|
229 | except FURLError, e: | |
230 | log.err(e) |
|
230 | log.err(e) | |
231 | self.exit(0) |
|
231 | self.exit(0) | |
232 | client_service = csfactory.create() |
|
232 | client_service = csfactory.create() | |
233 | client_service.setServiceParent(self.main_service) |
|
233 | client_service.setServiceParent(self.main_service) | |
234 | # The engine tub |
|
234 | # The engine tub | |
235 | try: |
|
235 | try: | |
236 | esfactory = FCEngineServiceFactory(config=self.master_config, adaptee=controller_service) |
|
236 | esfactory = FCEngineServiceFactory(config=self.master_config, adaptee=controller_service) | |
237 | except FURLError, e: |
|
237 | except FURLError, e: | |
238 | log.err(e) |
|
238 | log.err(e) | |
239 | self.exit(0) |
|
239 | self.exit(0) | |
240 | engine_service = esfactory.create() |
|
240 | engine_service = esfactory.create() | |
241 | engine_service.setServiceParent(self.main_service) |
|
241 | engine_service.setServiceParent(self.main_service) | |
242 |
|
242 | |||
243 | def import_statements(self): |
|
243 | def import_statements(self): | |
244 | statements = self.master_config.Global.import_statements |
|
244 | statements = self.master_config.Global.import_statements | |
245 | for s in statements: |
|
245 | for s in statements: | |
246 | try: |
|
246 | try: | |
247 | log.msg("Executing statement: '%s'" % s) |
|
247 | log.msg("Executing statement: '%s'" % s) | |
248 | exec s in globals(), locals() |
|
248 | exec s in globals(), locals() | |
249 | except: |
|
249 | except: | |
250 | log.msg("Error running statement: %s" % s) |
|
250 | log.msg("Error running statement: %s" % s) | |
251 |
|
251 | |||
252 | def start_app(self): |
|
252 | def start_app(self): | |
253 | # Start the controller service. |
|
253 | # Start the controller service. | |
254 | self.main_service.startService() |
|
254 | self.main_service.startService() | |
255 | # Write the .pid file overwriting old ones. This allow multiple |
|
255 | # Write the .pid file overwriting old ones. This allow multiple | |
256 | # controllers to clober each other. But Windows is not cleaning |
|
256 | # controllers to clober each other. But Windows is not cleaning | |
257 | # these up properly. |
|
257 | # these up properly. | |
258 | self.write_pid_file(overwrite=True) |
|
258 | self.write_pid_file(overwrite=True) | |
259 | # Add a trigger to delete the .pid file upon shutting down. |
|
259 | # Add a trigger to delete the .pid file upon shutting down. | |
260 | reactor.addSystemEventTrigger('during','shutdown', self.remove_pid_file) |
|
260 | reactor.addSystemEventTrigger('during','shutdown', self.remove_pid_file) | |
261 | reactor.run() |
|
261 | reactor.run() | |
262 |
|
262 | |||
263 |
|
263 | |||
264 | def launch_new_instance(): |
|
264 | def launch_new_instance(): | |
265 | """Create and run the IPython controller""" |
|
265 | """Create and run the IPython controller""" | |
266 | app = IPControllerApp() |
|
266 | app = IPControllerApp() | |
267 | app.start() |
|
267 | app.start() | |
268 |
|
268 | |||
269 |
|
269 | |||
270 | if __name__ == '__main__': |
|
270 | if __name__ == '__main__': | |
271 | launch_new_instance() |
|
271 | launch_new_instance() |
@@ -1,242 +1,242 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | The IPython controller application |
|
4 | The IPython controller application | |
5 | """ |
|
5 | """ | |
6 |
|
6 | |||
7 | #----------------------------------------------------------------------------- |
|
7 | #----------------------------------------------------------------------------- | |
8 | # Copyright (C) 2008-2009 The IPython Development Team |
|
8 | # Copyright (C) 2008-2009 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 os |
|
18 | import os | |
19 | import sys |
|
19 | import sys | |
20 |
|
20 | |||
21 | from twisted.application import service |
|
21 | from twisted.application import service | |
22 | from twisted.internet import reactor |
|
22 | from twisted.internet import reactor | |
23 | from twisted.python import log |
|
23 | from twisted.python import log | |
24 |
|
24 | |||
25 | from IPython.kernel.clusterdir import ( |
|
25 | from IPython.kernel.clusterdir import ( | |
26 | ApplicationWithClusterDir, |
|
26 | ApplicationWithClusterDir, | |
27 | ClusterDirConfigLoader |
|
27 | ClusterDirConfigLoader | |
28 | ) |
|
28 | ) | |
29 | from IPython.kernel.engineconnector import EngineConnector |
|
29 | from IPython.kernel.engineconnector import EngineConnector | |
30 | from IPython.kernel.engineservice import EngineService |
|
30 | from IPython.kernel.engineservice import EngineService | |
31 | from IPython.kernel.fcutil import Tub |
|
31 | from IPython.kernel.fcutil import Tub | |
32 | from IPython.utils.importstring import import_item |
|
32 | from IPython.utils.importstring import import_item | |
33 |
|
33 | |||
34 | #----------------------------------------------------------------------------- |
|
34 | #----------------------------------------------------------------------------- | |
35 | # Module level variables |
|
35 | # Module level variables | |
36 | #----------------------------------------------------------------------------- |
|
36 | #----------------------------------------------------------------------------- | |
37 |
|
37 | |||
38 | #: The default config file name for this application |
|
38 | #: The default config file name for this application | |
39 | default_config_file_name = u'ipengine_config.py' |
|
39 | default_config_file_name = u'ipengine_config.py' | |
40 |
|
40 | |||
41 |
|
41 | |||
42 | mpi4py_init = """from mpi4py import MPI as mpi |
|
42 | mpi4py_init = """from mpi4py import MPI as mpi | |
43 | mpi.size = mpi.COMM_WORLD.Get_size() |
|
43 | mpi.size = mpi.COMM_WORLD.Get_size() | |
44 | mpi.rank = mpi.COMM_WORLD.Get_rank() |
|
44 | mpi.rank = mpi.COMM_WORLD.Get_rank() | |
45 | """ |
|
45 | """ | |
46 |
|
46 | |||
47 |
|
47 | |||
48 | pytrilinos_init = """from PyTrilinos import Epetra |
|
48 | pytrilinos_init = """from PyTrilinos import Epetra | |
49 | class SimpleStruct: |
|
49 | class SimpleStruct: | |
50 | pass |
|
50 | pass | |
51 | mpi = SimpleStruct() |
|
51 | mpi = SimpleStruct() | |
52 | mpi.rank = 0 |
|
52 | mpi.rank = 0 | |
53 | mpi.size = 0 |
|
53 | mpi.size = 0 | |
54 | """ |
|
54 | """ | |
55 |
|
55 | |||
56 |
|
56 | |||
57 | _description = """Start an IPython engine for parallel computing.\n\n |
|
57 | _description = """Start an IPython engine for parallel computing.\n\n | |
58 |
|
58 | |||
59 | IPython engines run in parallel and perform computations on behalf of a client |
|
59 | IPython engines run in parallel and perform computations on behalf of a client | |
60 | and controller. A controller needs to be started before the engines. The |
|
60 | and controller. A controller needs to be started before the engines. The | |
61 | engine can be configured using command line options or using a cluster |
|
61 | engine can be configured using command line options or using a cluster | |
62 | directory. Cluster directories contain config, log and security files and are |
|
62 | directory. Cluster directories contain config, log and security files and are | |
63 |
usually located in your |
|
63 | usually located in your ipython directory and named as "cluster_<profile>". | |
64 | See the --profile and --cluster-dir options for details. |
|
64 | See the --profile and --cluster-dir options for details. | |
65 | """ |
|
65 | """ | |
66 |
|
66 | |||
67 | #----------------------------------------------------------------------------- |
|
67 | #----------------------------------------------------------------------------- | |
68 | # Command line options |
|
68 | # Command line options | |
69 | #----------------------------------------------------------------------------- |
|
69 | #----------------------------------------------------------------------------- | |
70 |
|
70 | |||
71 |
|
71 | |||
72 | class IPEngineAppConfigLoader(ClusterDirConfigLoader): |
|
72 | class IPEngineAppConfigLoader(ClusterDirConfigLoader): | |
73 |
|
73 | |||
74 | def _add_arguments(self): |
|
74 | def _add_arguments(self): | |
75 | super(IPEngineAppConfigLoader, self)._add_arguments() |
|
75 | super(IPEngineAppConfigLoader, self)._add_arguments() | |
76 | paa = self.parser.add_argument |
|
76 | paa = self.parser.add_argument | |
77 | # Controller config |
|
77 | # Controller config | |
78 | paa('--furl-file', |
|
78 | paa('--furl-file', | |
79 | type=unicode, dest='Global.furl_file', |
|
79 | type=unicode, dest='Global.furl_file', | |
80 | help='The full location of the file containing the FURL of the ' |
|
80 | help='The full location of the file containing the FURL of the ' | |
81 | 'controller. If this is not given, the FURL file must be in the ' |
|
81 | 'controller. If this is not given, the FURL file must be in the ' | |
82 | 'security directory of the cluster directory. This location is ' |
|
82 | 'security directory of the cluster directory. This location is ' | |
83 | 'resolved using the --profile and --app-dir options.', |
|
83 | 'resolved using the --profile and --app-dir options.', | |
84 | metavar='Global.furl_file') |
|
84 | metavar='Global.furl_file') | |
85 | # MPI |
|
85 | # MPI | |
86 | paa('--mpi', |
|
86 | paa('--mpi', | |
87 | type=str, dest='MPI.use', |
|
87 | type=str, dest='MPI.use', | |
88 | help='How to enable MPI (mpi4py, pytrilinos, or empty string to disable).', |
|
88 | help='How to enable MPI (mpi4py, pytrilinos, or empty string to disable).', | |
89 | metavar='MPI.use') |
|
89 | metavar='MPI.use') | |
90 | # Global config |
|
90 | # Global config | |
91 | paa('--log-to-file', |
|
91 | paa('--log-to-file', | |
92 | action='store_true', dest='Global.log_to_file', |
|
92 | action='store_true', dest='Global.log_to_file', | |
93 | help='Log to a file in the log directory (default is stdout)') |
|
93 | help='Log to a file in the log directory (default is stdout)') | |
94 |
|
94 | |||
95 |
|
95 | |||
96 | #----------------------------------------------------------------------------- |
|
96 | #----------------------------------------------------------------------------- | |
97 | # Main application |
|
97 | # Main application | |
98 | #----------------------------------------------------------------------------- |
|
98 | #----------------------------------------------------------------------------- | |
99 |
|
99 | |||
100 |
|
100 | |||
101 | class IPEngineApp(ApplicationWithClusterDir): |
|
101 | class IPEngineApp(ApplicationWithClusterDir): | |
102 |
|
102 | |||
103 | name = u'ipengine' |
|
103 | name = u'ipengine' | |
104 | description = _description |
|
104 | description = _description | |
105 | command_line_loader = IPEngineAppConfigLoader |
|
105 | command_line_loader = IPEngineAppConfigLoader | |
106 | default_config_file_name = default_config_file_name |
|
106 | default_config_file_name = default_config_file_name | |
107 | auto_create_cluster_dir = True |
|
107 | auto_create_cluster_dir = True | |
108 |
|
108 | |||
109 | def create_default_config(self): |
|
109 | def create_default_config(self): | |
110 | super(IPEngineApp, self).create_default_config() |
|
110 | super(IPEngineApp, self).create_default_config() | |
111 |
|
111 | |||
112 | # The engine should not clean logs as we don't want to remove the |
|
112 | # The engine should not clean logs as we don't want to remove the | |
113 | # active log files of other running engines. |
|
113 | # active log files of other running engines. | |
114 | self.default_config.Global.clean_logs = False |
|
114 | self.default_config.Global.clean_logs = False | |
115 |
|
115 | |||
116 | # Global config attributes |
|
116 | # Global config attributes | |
117 | self.default_config.Global.exec_lines = [] |
|
117 | self.default_config.Global.exec_lines = [] | |
118 | self.default_config.Global.shell_class = 'IPython.kernel.core.interpreter.Interpreter' |
|
118 | self.default_config.Global.shell_class = 'IPython.kernel.core.interpreter.Interpreter' | |
119 |
|
119 | |||
120 | # Configuration related to the controller |
|
120 | # Configuration related to the controller | |
121 | # This must match the filename (path not included) that the controller |
|
121 | # This must match the filename (path not included) that the controller | |
122 | # used for the FURL file. |
|
122 | # used for the FURL file. | |
123 | self.default_config.Global.furl_file_name = u'ipcontroller-engine.furl' |
|
123 | self.default_config.Global.furl_file_name = u'ipcontroller-engine.furl' | |
124 | # If given, this is the actual location of the controller's FURL file. |
|
124 | # If given, this is the actual location of the controller's FURL file. | |
125 | # If not, this is computed using the profile, app_dir and furl_file_name |
|
125 | # If not, this is computed using the profile, app_dir and furl_file_name | |
126 | self.default_config.Global.furl_file = u'' |
|
126 | self.default_config.Global.furl_file = u'' | |
127 |
|
127 | |||
128 | # The max number of connection attemps and the initial delay between |
|
128 | # The max number of connection attemps and the initial delay between | |
129 | # those attemps. |
|
129 | # those attemps. | |
130 | self.default_config.Global.connect_delay = 0.1 |
|
130 | self.default_config.Global.connect_delay = 0.1 | |
131 | self.default_config.Global.connect_max_tries = 15 |
|
131 | self.default_config.Global.connect_max_tries = 15 | |
132 |
|
132 | |||
133 | # MPI related config attributes |
|
133 | # MPI related config attributes | |
134 | self.default_config.MPI.use = '' |
|
134 | self.default_config.MPI.use = '' | |
135 | self.default_config.MPI.mpi4py = mpi4py_init |
|
135 | self.default_config.MPI.mpi4py = mpi4py_init | |
136 | self.default_config.MPI.pytrilinos = pytrilinos_init |
|
136 | self.default_config.MPI.pytrilinos = pytrilinos_init | |
137 |
|
137 | |||
138 | def post_load_command_line_config(self): |
|
138 | def post_load_command_line_config(self): | |
139 | pass |
|
139 | pass | |
140 |
|
140 | |||
141 | def pre_construct(self): |
|
141 | def pre_construct(self): | |
142 | super(IPEngineApp, self).pre_construct() |
|
142 | super(IPEngineApp, self).pre_construct() | |
143 | self.find_cont_furl_file() |
|
143 | self.find_cont_furl_file() | |
144 |
|
144 | |||
145 | def find_cont_furl_file(self): |
|
145 | def find_cont_furl_file(self): | |
146 | """Set the furl file. |
|
146 | """Set the furl file. | |
147 |
|
147 | |||
148 | Here we don't try to actually see if it exists for is valid as that |
|
148 | Here we don't try to actually see if it exists for is valid as that | |
149 | is hadled by the connection logic. |
|
149 | is hadled by the connection logic. | |
150 | """ |
|
150 | """ | |
151 | config = self.master_config |
|
151 | config = self.master_config | |
152 | # Find the actual controller FURL file |
|
152 | # Find the actual controller FURL file | |
153 | if not config.Global.furl_file: |
|
153 | if not config.Global.furl_file: | |
154 | try_this = os.path.join( |
|
154 | try_this = os.path.join( | |
155 | config.Global.cluster_dir, |
|
155 | config.Global.cluster_dir, | |
156 | config.Global.security_dir, |
|
156 | config.Global.security_dir, | |
157 | config.Global.furl_file_name |
|
157 | config.Global.furl_file_name | |
158 | ) |
|
158 | ) | |
159 | config.Global.furl_file = try_this |
|
159 | config.Global.furl_file = try_this | |
160 |
|
160 | |||
161 | def construct(self): |
|
161 | def construct(self): | |
162 | # This is the working dir by now. |
|
162 | # This is the working dir by now. | |
163 | sys.path.insert(0, '') |
|
163 | sys.path.insert(0, '') | |
164 |
|
164 | |||
165 | self.start_mpi() |
|
165 | self.start_mpi() | |
166 | self.start_logging() |
|
166 | self.start_logging() | |
167 |
|
167 | |||
168 | # Create the underlying shell class and EngineService |
|
168 | # Create the underlying shell class and EngineService | |
169 | shell_class = import_item(self.master_config.Global.shell_class) |
|
169 | shell_class = import_item(self.master_config.Global.shell_class) | |
170 | self.engine_service = EngineService(shell_class, mpi=mpi) |
|
170 | self.engine_service = EngineService(shell_class, mpi=mpi) | |
171 |
|
171 | |||
172 | self.exec_lines() |
|
172 | self.exec_lines() | |
173 |
|
173 | |||
174 | # Create the service hierarchy |
|
174 | # Create the service hierarchy | |
175 | self.main_service = service.MultiService() |
|
175 | self.main_service = service.MultiService() | |
176 | self.engine_service.setServiceParent(self.main_service) |
|
176 | self.engine_service.setServiceParent(self.main_service) | |
177 | self.tub_service = Tub() |
|
177 | self.tub_service = Tub() | |
178 | self.tub_service.setServiceParent(self.main_service) |
|
178 | self.tub_service.setServiceParent(self.main_service) | |
179 | # This needs to be called before the connection is initiated |
|
179 | # This needs to be called before the connection is initiated | |
180 | self.main_service.startService() |
|
180 | self.main_service.startService() | |
181 |
|
181 | |||
182 | # This initiates the connection to the controller and calls |
|
182 | # This initiates the connection to the controller and calls | |
183 | # register_engine to tell the controller we are ready to do work |
|
183 | # register_engine to tell the controller we are ready to do work | |
184 | self.engine_connector = EngineConnector(self.tub_service) |
|
184 | self.engine_connector = EngineConnector(self.tub_service) | |
185 |
|
185 | |||
186 | log.msg("Using furl file: %s" % self.master_config.Global.furl_file) |
|
186 | log.msg("Using furl file: %s" % self.master_config.Global.furl_file) | |
187 |
|
187 | |||
188 | reactor.callWhenRunning(self.call_connect) |
|
188 | reactor.callWhenRunning(self.call_connect) | |
189 |
|
189 | |||
190 | def call_connect(self): |
|
190 | def call_connect(self): | |
191 | d = self.engine_connector.connect_to_controller( |
|
191 | d = self.engine_connector.connect_to_controller( | |
192 | self.engine_service, |
|
192 | self.engine_service, | |
193 | self.master_config.Global.furl_file, |
|
193 | self.master_config.Global.furl_file, | |
194 | self.master_config.Global.connect_delay, |
|
194 | self.master_config.Global.connect_delay, | |
195 | self.master_config.Global.connect_max_tries |
|
195 | self.master_config.Global.connect_max_tries | |
196 | ) |
|
196 | ) | |
197 |
|
197 | |||
198 | def handle_error(f): |
|
198 | def handle_error(f): | |
199 | log.msg('Error connecting to controller. This usually means that ' |
|
199 | log.msg('Error connecting to controller. This usually means that ' | |
200 | 'i) the controller was not started, ii) a firewall was blocking ' |
|
200 | 'i) the controller was not started, ii) a firewall was blocking ' | |
201 | 'the engine from connecting to the controller or iii) the engine ' |
|
201 | 'the engine from connecting to the controller or iii) the engine ' | |
202 | ' was not pointed at the right FURL file:') |
|
202 | ' was not pointed at the right FURL file:') | |
203 | log.msg(f.getErrorMessage()) |
|
203 | log.msg(f.getErrorMessage()) | |
204 | reactor.callLater(0.1, reactor.stop) |
|
204 | reactor.callLater(0.1, reactor.stop) | |
205 |
|
205 | |||
206 | d.addErrback(handle_error) |
|
206 | d.addErrback(handle_error) | |
207 |
|
207 | |||
208 | def start_mpi(self): |
|
208 | def start_mpi(self): | |
209 | global mpi |
|
209 | global mpi | |
210 | mpikey = self.master_config.MPI.use |
|
210 | mpikey = self.master_config.MPI.use | |
211 | mpi_import_statement = self.master_config.MPI.get(mpikey, None) |
|
211 | mpi_import_statement = self.master_config.MPI.get(mpikey, None) | |
212 | if mpi_import_statement is not None: |
|
212 | if mpi_import_statement is not None: | |
213 | try: |
|
213 | try: | |
214 | self.log.info("Initializing MPI:") |
|
214 | self.log.info("Initializing MPI:") | |
215 | self.log.info(mpi_import_statement) |
|
215 | self.log.info(mpi_import_statement) | |
216 | exec mpi_import_statement in globals() |
|
216 | exec mpi_import_statement in globals() | |
217 | except: |
|
217 | except: | |
218 | mpi = None |
|
218 | mpi = None | |
219 | else: |
|
219 | else: | |
220 | mpi = None |
|
220 | mpi = None | |
221 |
|
221 | |||
222 | def exec_lines(self): |
|
222 | def exec_lines(self): | |
223 | for line in self.master_config.Global.exec_lines: |
|
223 | for line in self.master_config.Global.exec_lines: | |
224 | try: |
|
224 | try: | |
225 | log.msg("Executing statement: '%s'" % line) |
|
225 | log.msg("Executing statement: '%s'" % line) | |
226 | self.engine_service.execute(line) |
|
226 | self.engine_service.execute(line) | |
227 | except: |
|
227 | except: | |
228 | log.msg("Error executing statement: %s" % line) |
|
228 | log.msg("Error executing statement: %s" % line) | |
229 |
|
229 | |||
230 | def start_app(self): |
|
230 | def start_app(self): | |
231 | reactor.run() |
|
231 | reactor.run() | |
232 |
|
232 | |||
233 |
|
233 | |||
234 | def launch_new_instance(): |
|
234 | def launch_new_instance(): | |
235 | """Create and run the IPython controller""" |
|
235 | """Create and run the IPython controller""" | |
236 | app = IPEngineApp() |
|
236 | app = IPEngineApp() | |
237 | app.start() |
|
237 | app.start() | |
238 |
|
238 | |||
239 |
|
239 | |||
240 | if __name__ == '__main__': |
|
240 | if __name__ == '__main__': | |
241 | launch_new_instance() |
|
241 | launch_new_instance() | |
242 |
|
242 |
@@ -1,345 +1,383 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """ |
|
2 | """ | |
3 | Utilities for path handling. |
|
3 | Utilities for path handling. | |
4 | """ |
|
4 | """ | |
5 |
|
5 | |||
6 | #----------------------------------------------------------------------------- |
|
6 | #----------------------------------------------------------------------------- | |
7 | # Copyright (C) 2008-2009 The IPython Development Team |
|
7 | # Copyright (C) 2008-2009 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 |
|
16 | |||
17 | import os |
|
17 | import os | |
18 | import sys |
|
18 | import sys | |
19 |
|
19 | |||
20 | import IPython |
|
20 | import IPython | |
21 | from IPython.utils.process import system |
|
21 | from IPython.utils.process import system | |
22 | from IPython.utils.importstring import import_item |
|
22 | from IPython.utils.importstring import import_item | |
23 |
|
23 | |||
24 | #----------------------------------------------------------------------------- |
|
24 | #----------------------------------------------------------------------------- | |
25 | # Code |
|
25 | # Code | |
26 | #----------------------------------------------------------------------------- |
|
26 | #----------------------------------------------------------------------------- | |
27 |
|
27 | |||
28 |
|
28 | |||
29 | def _get_long_path_name(path): |
|
29 | def _get_long_path_name(path): | |
30 | """Dummy no-op.""" |
|
30 | """Dummy no-op.""" | |
31 | return path |
|
31 | return path | |
32 |
|
32 | |||
33 |
|
33 | |||
34 | if sys.platform == 'win32': |
|
34 | if sys.platform == 'win32': | |
35 | def _get_long_path_name(path): |
|
35 | def _get_long_path_name(path): | |
36 | """Get a long path name (expand ~) on Windows using ctypes. |
|
36 | """Get a long path name (expand ~) on Windows using ctypes. | |
37 |
|
37 | |||
38 | Examples |
|
38 | Examples | |
39 | -------- |
|
39 | -------- | |
40 |
|
40 | |||
41 | >>> get_long_path_name('c:\\docume~1') |
|
41 | >>> get_long_path_name('c:\\docume~1') | |
42 | u'c:\\\\Documents and Settings' |
|
42 | u'c:\\\\Documents and Settings' | |
43 |
|
43 | |||
44 | """ |
|
44 | """ | |
45 | try: |
|
45 | try: | |
46 | import ctypes |
|
46 | import ctypes | |
47 | except ImportError: |
|
47 | except ImportError: | |
48 | raise ImportError('you need to have ctypes installed for this to work') |
|
48 | raise ImportError('you need to have ctypes installed for this to work') | |
49 | _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW |
|
49 | _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW | |
50 | _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, |
|
50 | _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, | |
51 | ctypes.c_uint ] |
|
51 | ctypes.c_uint ] | |
52 |
|
52 | |||
53 | buf = ctypes.create_unicode_buffer(260) |
|
53 | buf = ctypes.create_unicode_buffer(260) | |
54 | rv = _GetLongPathName(path, buf, 260) |
|
54 | rv = _GetLongPathName(path, buf, 260) | |
55 | if rv == 0 or rv > 260: |
|
55 | if rv == 0 or rv > 260: | |
56 | return path |
|
56 | return path | |
57 | else: |
|
57 | else: | |
58 | return buf.value |
|
58 | return buf.value | |
59 |
|
59 | |||
60 |
|
60 | |||
61 | def get_long_path_name(path): |
|
61 | def get_long_path_name(path): | |
62 | """Expand a path into its long form. |
|
62 | """Expand a path into its long form. | |
63 |
|
63 | |||
64 | On Windows this expands any ~ in the paths. On other platforms, it is |
|
64 | On Windows this expands any ~ in the paths. On other platforms, it is | |
65 | a null operation. |
|
65 | a null operation. | |
66 | """ |
|
66 | """ | |
67 | return _get_long_path_name(path) |
|
67 | return _get_long_path_name(path) | |
68 |
|
68 | |||
69 |
|
69 | |||
70 | def get_py_filename(name): |
|
70 | def get_py_filename(name): | |
71 | """Return a valid python filename in the current directory. |
|
71 | """Return a valid python filename in the current directory. | |
72 |
|
72 | |||
73 | If the given name is not a file, it adds '.py' and searches again. |
|
73 | If the given name is not a file, it adds '.py' and searches again. | |
74 | Raises IOError with an informative message if the file isn't found.""" |
|
74 | Raises IOError with an informative message if the file isn't found.""" | |
75 |
|
75 | |||
76 | name = os.path.expanduser(name) |
|
76 | name = os.path.expanduser(name) | |
77 | if not os.path.isfile(name) and not name.endswith('.py'): |
|
77 | if not os.path.isfile(name) and not name.endswith('.py'): | |
78 | name += '.py' |
|
78 | name += '.py' | |
79 | if os.path.isfile(name): |
|
79 | if os.path.isfile(name): | |
80 | return name |
|
80 | return name | |
81 | else: |
|
81 | else: | |
82 | raise IOError,'File `%s` not found.' % name |
|
82 | raise IOError,'File `%s` not found.' % name | |
83 |
|
83 | |||
84 |
|
84 | |||
85 | def filefind(filename, path_dirs=None): |
|
85 | def filefind(filename, path_dirs=None): | |
86 | """Find a file by looking through a sequence of paths. |
|
86 | """Find a file by looking through a sequence of paths. | |
87 |
|
87 | |||
88 | This iterates through a sequence of paths looking for a file and returns |
|
88 | This iterates through a sequence of paths looking for a file and returns | |
89 | the full, absolute path of the first occurence of the file. If no set of |
|
89 | the full, absolute path of the first occurence of the file. If no set of | |
90 | path dirs is given, the filename is tested as is, after running through |
|
90 | path dirs is given, the filename is tested as is, after running through | |
91 | :func:`expandvars` and :func:`expanduser`. Thus a simple call:: |
|
91 | :func:`expandvars` and :func:`expanduser`. Thus a simple call:: | |
92 |
|
92 | |||
93 | filefind('myfile.txt') |
|
93 | filefind('myfile.txt') | |
94 |
|
94 | |||
95 | will find the file in the current working dir, but:: |
|
95 | will find the file in the current working dir, but:: | |
96 |
|
96 | |||
97 | filefind('~/myfile.txt') |
|
97 | filefind('~/myfile.txt') | |
98 |
|
98 | |||
99 | Will find the file in the users home directory. This function does not |
|
99 | Will find the file in the users home directory. This function does not | |
100 | automatically try any paths, such as the cwd or the user's home directory. |
|
100 | automatically try any paths, such as the cwd or the user's home directory. | |
101 |
|
101 | |||
102 | Parameters |
|
102 | Parameters | |
103 | ---------- |
|
103 | ---------- | |
104 | filename : str |
|
104 | filename : str | |
105 | The filename to look for. |
|
105 | The filename to look for. | |
106 | path_dirs : str, None or sequence of str |
|
106 | path_dirs : str, None or sequence of str | |
107 | The sequence of paths to look for the file in. If None, the filename |
|
107 | The sequence of paths to look for the file in. If None, the filename | |
108 | need to be absolute or be in the cwd. If a string, the string is |
|
108 | need to be absolute or be in the cwd. If a string, the string is | |
109 | put into a sequence and the searched. If a sequence, walk through |
|
109 | put into a sequence and the searched. If a sequence, walk through | |
110 | each element and join with ``filename``, calling :func:`expandvars` |
|
110 | each element and join with ``filename``, calling :func:`expandvars` | |
111 | and :func:`expanduser` before testing for existence. |
|
111 | and :func:`expanduser` before testing for existence. | |
112 |
|
112 | |||
113 | Returns |
|
113 | Returns | |
114 | ------- |
|
114 | ------- | |
115 | Raises :exc:`IOError` or returns absolute path to file. |
|
115 | Raises :exc:`IOError` or returns absolute path to file. | |
116 | """ |
|
116 | """ | |
117 |
|
117 | |||
118 | # If paths are quoted, abspath gets confused, strip them... |
|
118 | # If paths are quoted, abspath gets confused, strip them... | |
119 | filename = filename.strip('"').strip("'") |
|
119 | filename = filename.strip('"').strip("'") | |
120 | # If the input is an absolute path, just check it exists |
|
120 | # If the input is an absolute path, just check it exists | |
121 | if os.path.isabs(filename) and os.path.isfile(filename): |
|
121 | if os.path.isabs(filename) and os.path.isfile(filename): | |
122 | return filename |
|
122 | return filename | |
123 |
|
123 | |||
124 | if path_dirs is None: |
|
124 | if path_dirs is None: | |
125 | path_dirs = ("",) |
|
125 | path_dirs = ("",) | |
126 | elif isinstance(path_dirs, basestring): |
|
126 | elif isinstance(path_dirs, basestring): | |
127 | path_dirs = (path_dirs,) |
|
127 | path_dirs = (path_dirs,) | |
128 |
|
128 | |||
129 | for path in path_dirs: |
|
129 | for path in path_dirs: | |
130 | if path == '.': path = os.getcwd() |
|
130 | if path == '.': path = os.getcwd() | |
131 | testname = expand_path(os.path.join(path, filename)) |
|
131 | testname = expand_path(os.path.join(path, filename)) | |
132 | if os.path.isfile(testname): |
|
132 | if os.path.isfile(testname): | |
133 | return os.path.abspath(testname) |
|
133 | return os.path.abspath(testname) | |
134 |
|
134 | |||
135 | raise IOError("File %r does not exist in any of the search paths: %r" % |
|
135 | raise IOError("File %r does not exist in any of the search paths: %r" % | |
136 | (filename, path_dirs) ) |
|
136 | (filename, path_dirs) ) | |
137 |
|
137 | |||
138 |
|
138 | |||
139 | class HomeDirError(Exception): |
|
139 | class HomeDirError(Exception): | |
140 | pass |
|
140 | pass | |
141 |
|
141 | |||
142 |
|
142 | |||
143 | def get_home_dir(): |
|
143 | def get_home_dir(): | |
144 | """Return the closest possible equivalent to a 'home' directory. |
|
144 | """Return the closest possible equivalent to a 'home' directory. | |
145 |
|
145 | |||
146 | * On POSIX, we try $HOME. |
|
146 | * On POSIX, we try $HOME. | |
147 | * On Windows we try: |
|
147 | * On Windows we try: | |
148 | - %HOMESHARE% |
|
148 | - %HOMESHARE% | |
149 | - %HOMEDRIVE\%HOMEPATH% |
|
149 | - %HOMEDRIVE\%HOMEPATH% | |
150 | - %USERPROFILE% |
|
150 | - %USERPROFILE% | |
151 | - Registry hack for My Documents |
|
151 | - Registry hack for My Documents | |
152 | - %HOME%: rare, but some people with unix-like setups may have defined it |
|
152 | - %HOME%: rare, but some people with unix-like setups may have defined it | |
153 | * On Dos C:\ |
|
153 | * On Dos C:\ | |
154 |
|
154 | |||
155 | Currently only Posix and NT are implemented, a HomeDirError exception is |
|
155 | Currently only Posix and NT are implemented, a HomeDirError exception is | |
156 | raised for all other OSes. |
|
156 | raised for all other OSes. | |
157 | """ |
|
157 | """ | |
158 |
|
158 | |||
159 | isdir = os.path.isdir |
|
159 | isdir = os.path.isdir | |
160 | env = os.environ |
|
160 | env = os.environ | |
161 |
|
161 | |||
162 | # first, check py2exe distribution root directory for _ipython. |
|
162 | # first, check py2exe distribution root directory for _ipython. | |
163 | # This overrides all. Normally does not exist. |
|
163 | # This overrides all. Normally does not exist. | |
164 |
|
164 | |||
165 | if hasattr(sys, "frozen"): #Is frozen by py2exe |
|
165 | if hasattr(sys, "frozen"): #Is frozen by py2exe | |
166 | if '\\library.zip\\' in IPython.__file__.lower():#libraries compressed to zip-file |
|
166 | if '\\library.zip\\' in IPython.__file__.lower():#libraries compressed to zip-file | |
167 | root, rest = IPython.__file__.lower().split('library.zip') |
|
167 | root, rest = IPython.__file__.lower().split('library.zip') | |
168 | else: |
|
168 | else: | |
169 | root=os.path.join(os.path.split(IPython.__file__)[0],"../../") |
|
169 | root=os.path.join(os.path.split(IPython.__file__)[0],"../../") | |
170 | root=os.path.abspath(root).rstrip('\\') |
|
170 | root=os.path.abspath(root).rstrip('\\') | |
171 | if isdir(os.path.join(root, '_ipython')): |
|
171 | if isdir(os.path.join(root, '_ipython')): | |
172 | os.environ["IPYKITROOT"] = root |
|
172 | os.environ["IPYKITROOT"] = root | |
173 | return root.decode(sys.getfilesystemencoding()) |
|
173 | return root.decode(sys.getfilesystemencoding()) | |
174 |
|
174 | |||
175 | if os.name == 'posix': |
|
175 | if os.name == 'posix': | |
176 | # Linux, Unix, AIX, OS X |
|
176 | # Linux, Unix, AIX, OS X | |
177 | try: |
|
177 | try: | |
178 | homedir = env['HOME'] |
|
178 | homedir = env['HOME'] | |
179 | except KeyError: |
|
179 | except KeyError: | |
180 | raise HomeDirError('Undefined $HOME, IPython cannot proceed.') |
|
180 | raise HomeDirError('Undefined $HOME, IPython cannot proceed.') | |
181 | else: |
|
181 | else: | |
182 | return homedir.decode(sys.getfilesystemencoding()) |
|
182 | return homedir.decode(sys.getfilesystemencoding()) | |
183 | elif os.name == 'nt': |
|
183 | elif os.name == 'nt': | |
184 | # Now for win9x, XP, Vista, 7? |
|
184 | # Now for win9x, XP, Vista, 7? | |
185 | # For some strange reason all of these return 'nt' for os.name. |
|
185 | # For some strange reason all of these return 'nt' for os.name. | |
186 | # First look for a network home directory. This will return the UNC |
|
186 | # First look for a network home directory. This will return the UNC | |
187 | # path (\\server\\Users\%username%) not the mapped path (Z:\). This |
|
187 | # path (\\server\\Users\%username%) not the mapped path (Z:\). This | |
188 | # is needed when running IPython on cluster where all paths have to |
|
188 | # is needed when running IPython on cluster where all paths have to | |
189 | # be UNC. |
|
189 | # be UNC. | |
190 | try: |
|
190 | try: | |
191 | homedir = env['HOMESHARE'] |
|
191 | homedir = env['HOMESHARE'] | |
192 | except KeyError: |
|
192 | except KeyError: | |
193 | pass |
|
193 | pass | |
194 | else: |
|
194 | else: | |
195 | if isdir(homedir): |
|
195 | if isdir(homedir): | |
196 | return homedir.decode(sys.getfilesystemencoding()) |
|
196 | return homedir.decode(sys.getfilesystemencoding()) | |
197 |
|
197 | |||
198 | # Now look for a local home directory |
|
198 | # Now look for a local home directory | |
199 | try: |
|
199 | try: | |
200 | homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH']) |
|
200 | homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH']) | |
201 | except KeyError: |
|
201 | except KeyError: | |
202 | pass |
|
202 | pass | |
203 | else: |
|
203 | else: | |
204 | if isdir(homedir): |
|
204 | if isdir(homedir): | |
205 | return homedir.decode(sys.getfilesystemencoding()) |
|
205 | return homedir.decode(sys.getfilesystemencoding()) | |
206 |
|
206 | |||
207 | # Now the users profile directory |
|
207 | # Now the users profile directory | |
208 | try: |
|
208 | try: | |
209 | homedir = os.path.join(env['USERPROFILE']) |
|
209 | homedir = os.path.join(env['USERPROFILE']) | |
210 | except KeyError: |
|
210 | except KeyError: | |
211 | pass |
|
211 | pass | |
212 | else: |
|
212 | else: | |
213 | if isdir(homedir): |
|
213 | if isdir(homedir): | |
214 | return homedir.decode(sys.getfilesystemencoding()) |
|
214 | return homedir.decode(sys.getfilesystemencoding()) | |
215 |
|
215 | |||
216 | # Use the registry to get the 'My Documents' folder. |
|
216 | # Use the registry to get the 'My Documents' folder. | |
217 | try: |
|
217 | try: | |
218 | import _winreg as wreg |
|
218 | import _winreg as wreg | |
219 | key = wreg.OpenKey( |
|
219 | key = wreg.OpenKey( | |
220 | wreg.HKEY_CURRENT_USER, |
|
220 | wreg.HKEY_CURRENT_USER, | |
221 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" |
|
221 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" | |
222 | ) |
|
222 | ) | |
223 | homedir = wreg.QueryValueEx(key,'Personal')[0] |
|
223 | homedir = wreg.QueryValueEx(key,'Personal')[0] | |
224 | key.Close() |
|
224 | key.Close() | |
225 | except: |
|
225 | except: | |
226 | pass |
|
226 | pass | |
227 | else: |
|
227 | else: | |
228 | if isdir(homedir): |
|
228 | if isdir(homedir): | |
229 | return homedir.decode(sys.getfilesystemencoding()) |
|
229 | return homedir.decode(sys.getfilesystemencoding()) | |
230 |
|
230 | |||
231 | # A user with a lot of unix tools in win32 may have defined $HOME. |
|
231 | # A user with a lot of unix tools in win32 may have defined $HOME. | |
232 | # Try this as a last ditch option. |
|
232 | # Try this as a last ditch option. | |
233 | try: |
|
233 | try: | |
234 | homedir = env['HOME'] |
|
234 | homedir = env['HOME'] | |
235 | except KeyError: |
|
235 | except KeyError: | |
236 | pass |
|
236 | pass | |
237 | else: |
|
237 | else: | |
238 | if isdir(homedir): |
|
238 | if isdir(homedir): | |
239 | return homedir.decode(sys.getfilesystemencoding()) |
|
239 | return homedir.decode(sys.getfilesystemencoding()) | |
240 |
|
240 | |||
241 | # If all else fails, raise HomeDirError |
|
241 | # If all else fails, raise HomeDirError | |
242 | raise HomeDirError('No valid home directory could be found') |
|
242 | raise HomeDirError('No valid home directory could be found') | |
243 | elif os.name == 'dos': |
|
243 | elif os.name == 'dos': | |
244 | # Desperate, may do absurd things in classic MacOS. May work under DOS. |
|
244 | # Desperate, may do absurd things in classic MacOS. May work under DOS. | |
245 | return 'C:\\'.decode(sys.getfilesystemencoding()) |
|
245 | return 'C:\\'.decode(sys.getfilesystemencoding()) | |
246 | else: |
|
246 | else: | |
247 | raise HomeDirError('No valid home directory could be found for your OS') |
|
247 | raise HomeDirError('No valid home directory could be found for your OS') | |
248 |
|
248 | |||
|
249 | def get_xdg_dir(): | |||
|
250 | """Return the XDG_CONFIG_HOME, if it is defined and exists, else None. | |||
|
251 | ||||
|
252 | This is only for posix (Linux,Unix,OS X, etc) systems. | |||
|
253 | """ | |||
|
254 | ||||
|
255 | isdir = os.path.isdir | |||
|
256 | env = os.environ | |||
|
257 | ||||
|
258 | if os.name == 'posix': | |||
|
259 | # Linux, Unix, AIX, OS X | |||
|
260 | # use ~/.config if not set OR empty | |||
|
261 | xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config') | |||
|
262 | if xdg and isdir(xdg): | |||
|
263 | return xdg.decode(sys.getfilesystemencoding()) | |||
|
264 | ||||
|
265 | return None | |||
|
266 | ||||
249 |
|
267 | |||
250 | def get_ipython_dir(): |
|
268 | def get_ipython_dir(): | |
251 | """Get the IPython directory for this platform and user. |
|
269 | """Get the IPython directory for this platform and user. | |
252 |
|
270 | |||
253 | This uses the logic in `get_home_dir` to find the home directory |
|
271 | This uses the logic in `get_home_dir` to find the home directory | |
254 | and the adds .ipython to the end of the path. |
|
272 | and the adds .ipython to the end of the path. | |
255 | """ |
|
273 | """ | |
|
274 | ||||
|
275 | env = os.environ | |||
|
276 | pjoin = os.path.join | |||
|
277 | exists = os.path.exists | |||
|
278 | ||||
256 | ipdir_def = '.ipython' |
|
279 | ipdir_def = '.ipython' | |
|
280 | xdg_def = 'ipython' | |||
|
281 | ||||
257 | home_dir = get_home_dir() |
|
282 | home_dir = get_home_dir() | |
|
283 | xdg_dir = get_xdg_dir() | |||
258 | # import pdb; pdb.set_trace() # dbg |
|
284 | # import pdb; pdb.set_trace() # dbg | |
259 | ipdir = os.environ.get( |
|
285 | ipdir = env.get('IPYTHON_DIR', env.get('IPYTHONDIR', None)) | |
260 | 'IPYTHON_DIR', os.environ.get( |
|
286 | if ipdir is None: | |
261 | 'IPYTHONDIR', os.path.join(home_dir, ipdir_def) |
|
287 | # not set explicitly, use XDG_CONFIG_HOME or HOME | |
262 | ) |
|
288 | home_ipdir = pjoin(home_dir, ipdir_def) | |
263 | ) |
|
289 | if xdg_dir: | |
|
290 | # use XDG, as long as the user isn't already | |||
|
291 | # using $HOME/.ipython and *not* XDG/ipython | |||
|
292 | ||||
|
293 | xdg_ipdir = pjoin(xdg_dir, xdg_def) | |||
|
294 | ||||
|
295 | if exists(xdg_ipdir) or not exists(home_ipdir): | |||
|
296 | ipdir = xdg_ipdir | |||
|
297 | ||||
|
298 | if ipdir is None: | |||
|
299 | # not using XDG | |||
|
300 | ipdir = home_ipdir | |||
|
301 | ||||
264 | return ipdir.decode(sys.getfilesystemencoding()) |
|
302 | return ipdir.decode(sys.getfilesystemencoding()) | |
265 |
|
303 | |||
266 |
|
304 | |||
267 | def get_ipython_package_dir(): |
|
305 | def get_ipython_package_dir(): | |
268 | """Get the base directory where IPython itself is installed.""" |
|
306 | """Get the base directory where IPython itself is installed.""" | |
269 | ipdir = os.path.dirname(IPython.__file__) |
|
307 | ipdir = os.path.dirname(IPython.__file__) | |
270 | return ipdir.decode(sys.getfilesystemencoding()) |
|
308 | return ipdir.decode(sys.getfilesystemencoding()) | |
271 |
|
309 | |||
272 |
|
310 | |||
273 | def get_ipython_module_path(module_str): |
|
311 | def get_ipython_module_path(module_str): | |
274 | """Find the path to an IPython module in this version of IPython. |
|
312 | """Find the path to an IPython module in this version of IPython. | |
275 |
|
313 | |||
276 | This will always find the version of the module that is in this importable |
|
314 | This will always find the version of the module that is in this importable | |
277 | IPython package. This will always return the path to the ``.py`` |
|
315 | IPython package. This will always return the path to the ``.py`` | |
278 | version of the module. |
|
316 | version of the module. | |
279 | """ |
|
317 | """ | |
280 | if module_str == 'IPython': |
|
318 | if module_str == 'IPython': | |
281 | return os.path.join(get_ipython_package_dir(), '__init__.py') |
|
319 | return os.path.join(get_ipython_package_dir(), '__init__.py') | |
282 | mod = import_item(module_str) |
|
320 | mod = import_item(module_str) | |
283 | the_path = mod.__file__.replace('.pyc', '.py') |
|
321 | the_path = mod.__file__.replace('.pyc', '.py') | |
284 | the_path = the_path.replace('.pyo', '.py') |
|
322 | the_path = the_path.replace('.pyo', '.py') | |
285 | return the_path.decode(sys.getfilesystemencoding()) |
|
323 | return the_path.decode(sys.getfilesystemencoding()) | |
286 |
|
324 | |||
287 |
|
325 | |||
288 | def expand_path(s): |
|
326 | def expand_path(s): | |
289 | """Expand $VARS and ~names in a string, like a shell |
|
327 | """Expand $VARS and ~names in a string, like a shell | |
290 |
|
328 | |||
291 | :Examples: |
|
329 | :Examples: | |
292 |
|
330 | |||
293 | In [2]: os.environ['FOO']='test' |
|
331 | In [2]: os.environ['FOO']='test' | |
294 |
|
332 | |||
295 | In [3]: expand_path('variable FOO is $FOO') |
|
333 | In [3]: expand_path('variable FOO is $FOO') | |
296 | Out[3]: 'variable FOO is test' |
|
334 | Out[3]: 'variable FOO is test' | |
297 | """ |
|
335 | """ | |
298 | # This is a pretty subtle hack. When expand user is given a UNC path |
|
336 | # This is a pretty subtle hack. When expand user is given a UNC path | |
299 | # on Windows (\\server\share$\%username%), os.path.expandvars, removes |
|
337 | # on Windows (\\server\share$\%username%), os.path.expandvars, removes | |
300 | # the $ to get (\\server\share\%username%). I think it considered $ |
|
338 | # the $ to get (\\server\share\%username%). I think it considered $ | |
301 | # alone an empty var. But, we need the $ to remains there (it indicates |
|
339 | # alone an empty var. But, we need the $ to remains there (it indicates | |
302 | # a hidden share). |
|
340 | # a hidden share). | |
303 | if os.name=='nt': |
|
341 | if os.name=='nt': | |
304 | s = s.replace('$\\', 'IPYTHON_TEMP') |
|
342 | s = s.replace('$\\', 'IPYTHON_TEMP') | |
305 | s = os.path.expandvars(os.path.expanduser(s)) |
|
343 | s = os.path.expandvars(os.path.expanduser(s)) | |
306 | if os.name=='nt': |
|
344 | if os.name=='nt': | |
307 | s = s.replace('IPYTHON_TEMP', '$\\') |
|
345 | s = s.replace('IPYTHON_TEMP', '$\\') | |
308 | return s |
|
346 | return s | |
309 |
|
347 | |||
310 |
|
348 | |||
311 | def target_outdated(target,deps): |
|
349 | def target_outdated(target,deps): | |
312 | """Determine whether a target is out of date. |
|
350 | """Determine whether a target is out of date. | |
313 |
|
351 | |||
314 | target_outdated(target,deps) -> 1/0 |
|
352 | target_outdated(target,deps) -> 1/0 | |
315 |
|
353 | |||
316 | deps: list of filenames which MUST exist. |
|
354 | deps: list of filenames which MUST exist. | |
317 | target: single filename which may or may not exist. |
|
355 | target: single filename which may or may not exist. | |
318 |
|
356 | |||
319 | If target doesn't exist or is older than any file listed in deps, return |
|
357 | If target doesn't exist or is older than any file listed in deps, return | |
320 | true, otherwise return false. |
|
358 | true, otherwise return false. | |
321 | """ |
|
359 | """ | |
322 | try: |
|
360 | try: | |
323 | target_time = os.path.getmtime(target) |
|
361 | target_time = os.path.getmtime(target) | |
324 | except os.error: |
|
362 | except os.error: | |
325 | return 1 |
|
363 | return 1 | |
326 | for dep in deps: |
|
364 | for dep in deps: | |
327 | dep_time = os.path.getmtime(dep) |
|
365 | dep_time = os.path.getmtime(dep) | |
328 | if dep_time > target_time: |
|
366 | if dep_time > target_time: | |
329 | #print "For target",target,"Dep failed:",dep # dbg |
|
367 | #print "For target",target,"Dep failed:",dep # dbg | |
330 | #print "times (dep,tar):",dep_time,target_time # dbg |
|
368 | #print "times (dep,tar):",dep_time,target_time # dbg | |
331 | return 1 |
|
369 | return 1 | |
332 | return 0 |
|
370 | return 0 | |
333 |
|
371 | |||
334 |
|
372 | |||
335 | def target_update(target,deps,cmd): |
|
373 | def target_update(target,deps,cmd): | |
336 | """Update a target with a given command given a list of dependencies. |
|
374 | """Update a target with a given command given a list of dependencies. | |
337 |
|
375 | |||
338 | target_update(target,deps,cmd) -> runs cmd if target is outdated. |
|
376 | target_update(target,deps,cmd) -> runs cmd if target is outdated. | |
339 |
|
377 | |||
340 | This is just a wrapper around target_outdated() which calls the given |
|
378 | This is just a wrapper around target_outdated() which calls the given | |
341 | command if target is outdated.""" |
|
379 | command if target is outdated.""" | |
342 |
|
380 | |||
343 | if target_outdated(target,deps): |
|
381 | if target_outdated(target,deps): | |
344 | system(cmd) |
|
382 | system(cmd) | |
345 |
|
383 |
@@ -1,272 +1,358 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """Tests for IPython.utils.path.py""" |
|
2 | """Tests for IPython.utils.path.py""" | |
3 |
|
3 | |||
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Copyright (C) 2008 The IPython Development Team |
|
5 | # Copyright (C) 2008 The IPython Development Team | |
6 | # |
|
6 | # | |
7 | # Distributed under the terms of the BSD License. The full license is in |
|
7 | # Distributed under the terms of the BSD License. The full license is in | |
8 | # the file COPYING, distributed as part of this software. |
|
8 | # the file COPYING, distributed as part of this software. | |
9 | #----------------------------------------------------------------------------- |
|
9 | #----------------------------------------------------------------------------- | |
10 |
|
10 | |||
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 | # Imports |
|
12 | # Imports | |
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 |
|
14 | |||
15 | import os |
|
15 | import os | |
16 | import shutil |
|
16 | import shutil | |
17 | import sys |
|
17 | import sys | |
18 | import tempfile |
|
18 | import tempfile | |
19 |
|
19 | |||
20 | from os.path import join, abspath, split |
|
20 | from os.path import join, abspath, split | |
21 |
|
21 | |||
22 | import nose.tools as nt |
|
22 | import nose.tools as nt | |
23 |
|
23 | |||
24 | from nose import with_setup |
|
24 | from nose import with_setup | |
25 |
|
25 | |||
26 | import IPython |
|
26 | import IPython | |
27 | from IPython.testing import decorators as dec |
|
27 | from IPython.testing import decorators as dec | |
28 | from IPython.testing.decorators import skip_if_not_win32, skip_win32 |
|
28 | from IPython.testing.decorators import skip_if_not_win32, skip_win32 | |
29 | from IPython.utils import path |
|
29 | from IPython.utils import path | |
30 |
|
30 | |||
31 | # Platform-dependent imports |
|
31 | # Platform-dependent imports | |
32 | try: |
|
32 | try: | |
33 | import _winreg as wreg |
|
33 | import _winreg as wreg | |
34 | except ImportError: |
|
34 | except ImportError: | |
35 | #Fake _winreg module on none windows platforms |
|
35 | #Fake _winreg module on none windows platforms | |
36 | import new |
|
36 | import new | |
37 | sys.modules["_winreg"] = new.module("_winreg") |
|
37 | sys.modules["_winreg"] = new.module("_winreg") | |
38 | import _winreg as wreg |
|
38 | import _winreg as wreg | |
39 | #Add entries that needs to be stubbed by the testing code |
|
39 | #Add entries that needs to be stubbed by the testing code | |
40 | (wreg.OpenKey, wreg.QueryValueEx,) = (None, None) |
|
40 | (wreg.OpenKey, wreg.QueryValueEx,) = (None, None) | |
41 |
|
41 | |||
42 | #----------------------------------------------------------------------------- |
|
42 | #----------------------------------------------------------------------------- | |
43 | # Globals |
|
43 | # Globals | |
44 | #----------------------------------------------------------------------------- |
|
44 | #----------------------------------------------------------------------------- | |
45 | env = os.environ |
|
45 | env = os.environ | |
46 | TEST_FILE_PATH = split(abspath(__file__))[0] |
|
46 | TEST_FILE_PATH = split(abspath(__file__))[0] | |
47 | TMP_TEST_DIR = tempfile.mkdtemp() |
|
47 | TMP_TEST_DIR = tempfile.mkdtemp() | |
48 | HOME_TEST_DIR = join(TMP_TEST_DIR, "home_test_dir") |
|
48 | HOME_TEST_DIR = join(TMP_TEST_DIR, "home_test_dir") | |
|
49 | XDG_TEST_DIR = join(HOME_TEST_DIR, "xdg_test_dir") | |||
49 | IP_TEST_DIR = join(HOME_TEST_DIR,'.ipython') |
|
50 | IP_TEST_DIR = join(HOME_TEST_DIR,'.ipython') | |
50 | # |
|
51 | # | |
51 | # Setup/teardown functions/decorators |
|
52 | # Setup/teardown functions/decorators | |
52 | # |
|
53 | # | |
53 |
|
54 | |||
54 | def setup(): |
|
55 | def setup(): | |
55 | """Setup testenvironment for the module: |
|
56 | """Setup testenvironment for the module: | |
56 |
|
57 | |||
57 | - Adds dummy home dir tree |
|
58 | - Adds dummy home dir tree | |
58 | """ |
|
59 | """ | |
59 | # Do not mask exceptions here. In particular, catching WindowsError is a |
|
60 | # Do not mask exceptions here. In particular, catching WindowsError is a | |
60 | # problem because that exception is only defined on Windows... |
|
61 | # problem because that exception is only defined on Windows... | |
61 | os.makedirs(IP_TEST_DIR) |
|
62 | os.makedirs(IP_TEST_DIR) | |
|
63 | os.makedirs(os.path.join(XDG_TEST_DIR, 'ipython')) | |||
62 |
|
64 | |||
63 |
|
65 | |||
64 | def teardown(): |
|
66 | def teardown(): | |
65 | """Teardown testenvironment for the module: |
|
67 | """Teardown testenvironment for the module: | |
66 |
|
68 | |||
67 | - Remove dummy home dir tree |
|
69 | - Remove dummy home dir tree | |
68 | """ |
|
70 | """ | |
69 | # Note: we remove the parent test dir, which is the root of all test |
|
71 | # Note: we remove the parent test dir, which is the root of all test | |
70 | # subdirs we may have created. Use shutil instead of os.removedirs, so |
|
72 | # subdirs we may have created. Use shutil instead of os.removedirs, so | |
71 | # that non-empty directories are all recursively removed. |
|
73 | # that non-empty directories are all recursively removed. | |
72 | shutil.rmtree(TMP_TEST_DIR) |
|
74 | shutil.rmtree(TMP_TEST_DIR) | |
73 |
|
75 | |||
74 |
|
76 | |||
75 | def setup_environment(): |
|
77 | def setup_environment(): | |
76 | """Setup testenvironment for some functions that are tested |
|
78 | """Setup testenvironment for some functions that are tested | |
77 | in this module. In particular this functions stores attributes |
|
79 | in this module. In particular this functions stores attributes | |
78 | and other things that we need to stub in some test functions. |
|
80 | and other things that we need to stub in some test functions. | |
79 | This needs to be done on a function level and not module level because |
|
81 | This needs to be done on a function level and not module level because | |
80 | each testfunction needs a pristine environment. |
|
82 | each testfunction needs a pristine environment. | |
81 | """ |
|
83 | """ | |
82 | global oldstuff, platformstuff |
|
84 | global oldstuff, platformstuff | |
83 | oldstuff = (env.copy(), os.name, path.get_home_dir, IPython.__file__) |
|
85 | oldstuff = (env.copy(), os.name, path.get_home_dir, IPython.__file__) | |
84 |
|
86 | |||
85 | if os.name == 'nt': |
|
87 | if os.name == 'nt': | |
86 | platformstuff = (wreg.OpenKey, wreg.QueryValueEx,) |
|
88 | platformstuff = (wreg.OpenKey, wreg.QueryValueEx,) | |
87 |
|
89 | |||
88 |
|
90 | |||
89 | def teardown_environment(): |
|
91 | def teardown_environment(): | |
90 | """Restore things that were remebered by the setup_environment function |
|
92 | """Restore things that were remebered by the setup_environment function | |
91 | """ |
|
93 | """ | |
92 | (oldenv, os.name, get_home_dir, IPython.__file__,) = oldstuff |
|
94 | (oldenv, os.name, get_home_dir, IPython.__file__,) = oldstuff | |
93 |
|
95 | |||
94 | for key in env.keys(): |
|
96 | for key in env.keys(): | |
95 | if key not in oldenv: |
|
97 | if key not in oldenv: | |
96 | del env[key] |
|
98 | del env[key] | |
97 | env.update(oldenv) |
|
99 | env.update(oldenv) | |
98 | if hasattr(sys, 'frozen'): |
|
100 | if hasattr(sys, 'frozen'): | |
99 | del sys.frozen |
|
101 | del sys.frozen | |
100 | if os.name == 'nt': |
|
102 | if os.name == 'nt': | |
101 | (wreg.OpenKey, wreg.QueryValueEx,) = platformstuff |
|
103 | (wreg.OpenKey, wreg.QueryValueEx,) = platformstuff | |
102 |
|
104 | |||
103 | # Build decorator that uses the setup_environment/setup_environment |
|
105 | # Build decorator that uses the setup_environment/setup_environment | |
104 | with_environment = with_setup(setup_environment, teardown_environment) |
|
106 | with_environment = with_setup(setup_environment, teardown_environment) | |
105 |
|
107 | |||
106 |
|
108 | |||
107 | @skip_if_not_win32 |
|
109 | @skip_if_not_win32 | |
108 | @with_environment |
|
110 | @with_environment | |
109 | def test_get_home_dir_1(): |
|
111 | def test_get_home_dir_1(): | |
110 | """Testcase for py2exe logic, un-compressed lib |
|
112 | """Testcase for py2exe logic, un-compressed lib | |
111 | """ |
|
113 | """ | |
112 | sys.frozen = True |
|
114 | sys.frozen = True | |
113 |
|
115 | |||
114 | #fake filename for IPython.__init__ |
|
116 | #fake filename for IPython.__init__ | |
115 | IPython.__file__ = abspath(join(HOME_TEST_DIR, "Lib/IPython/__init__.py")) |
|
117 | IPython.__file__ = abspath(join(HOME_TEST_DIR, "Lib/IPython/__init__.py")) | |
116 |
|
118 | |||
117 | home_dir = path.get_home_dir() |
|
119 | home_dir = path.get_home_dir() | |
118 | nt.assert_equal(home_dir, abspath(HOME_TEST_DIR)) |
|
120 | nt.assert_equal(home_dir, abspath(HOME_TEST_DIR)) | |
119 |
|
121 | |||
120 |
|
122 | |||
121 | @skip_if_not_win32 |
|
123 | @skip_if_not_win32 | |
122 | @with_environment |
|
124 | @with_environment | |
123 | def test_get_home_dir_2(): |
|
125 | def test_get_home_dir_2(): | |
124 | """Testcase for py2exe logic, compressed lib |
|
126 | """Testcase for py2exe logic, compressed lib | |
125 | """ |
|
127 | """ | |
126 | sys.frozen = True |
|
128 | sys.frozen = True | |
127 | #fake filename for IPython.__init__ |
|
129 | #fake filename for IPython.__init__ | |
128 | IPython.__file__ = abspath(join(HOME_TEST_DIR, "Library.zip/IPython/__init__.py")).lower() |
|
130 | IPython.__file__ = abspath(join(HOME_TEST_DIR, "Library.zip/IPython/__init__.py")).lower() | |
129 |
|
131 | |||
130 | home_dir = path.get_home_dir() |
|
132 | home_dir = path.get_home_dir() | |
131 | nt.assert_equal(home_dir, abspath(HOME_TEST_DIR).lower()) |
|
133 | nt.assert_equal(home_dir, abspath(HOME_TEST_DIR).lower()) | |
132 |
|
134 | |||
133 |
|
135 | |||
134 | @with_environment |
|
136 | @with_environment | |
135 | @skip_win32 |
|
137 | @skip_win32 | |
136 | def test_get_home_dir_3(): |
|
138 | def test_get_home_dir_3(): | |
137 | """Testcase $HOME is set, then use its value as home directory.""" |
|
139 | """Testcase $HOME is set, then use its value as home directory.""" | |
138 | env["HOME"] = HOME_TEST_DIR |
|
140 | env["HOME"] = HOME_TEST_DIR | |
139 | home_dir = path.get_home_dir() |
|
141 | home_dir = path.get_home_dir() | |
140 | nt.assert_equal(home_dir, env["HOME"]) |
|
142 | nt.assert_equal(home_dir, env["HOME"]) | |
141 |
|
143 | |||
142 |
|
144 | |||
143 | @with_environment |
|
145 | @with_environment | |
144 | def test_get_home_dir_4(): |
|
146 | def test_get_home_dir_4(): | |
145 | """Testcase $HOME is not set, os=='posix'. |
|
147 | """Testcase $HOME is not set, os=='posix'. | |
146 | This should fail with HomeDirError""" |
|
148 | This should fail with HomeDirError""" | |
147 |
|
149 | |||
148 | os.name = 'posix' |
|
150 | os.name = 'posix' | |
149 | if 'HOME' in env: del env['HOME'] |
|
151 | if 'HOME' in env: del env['HOME'] | |
150 | nt.assert_raises(path.HomeDirError, path.get_home_dir) |
|
152 | nt.assert_raises(path.HomeDirError, path.get_home_dir) | |
151 |
|
153 | |||
152 |
|
154 | |||
153 | @skip_if_not_win32 |
|
155 | @skip_if_not_win32 | |
154 | @with_environment |
|
156 | @with_environment | |
155 | def test_get_home_dir_5(): |
|
157 | def test_get_home_dir_5(): | |
156 | """Using HOMEDRIVE + HOMEPATH, os=='nt'. |
|
158 | """Using HOMEDRIVE + HOMEPATH, os=='nt'. | |
157 |
|
159 | |||
158 | HOMESHARE is missing. |
|
160 | HOMESHARE is missing. | |
159 | """ |
|
161 | """ | |
160 |
|
162 | |||
161 | os.name = 'nt' |
|
163 | os.name = 'nt' | |
162 | env.pop('HOMESHARE', None) |
|
164 | env.pop('HOMESHARE', None) | |
163 | env['HOMEDRIVE'], env['HOMEPATH'] = os.path.splitdrive(HOME_TEST_DIR) |
|
165 | env['HOMEDRIVE'], env['HOMEPATH'] = os.path.splitdrive(HOME_TEST_DIR) | |
164 | home_dir = path.get_home_dir() |
|
166 | home_dir = path.get_home_dir() | |
165 | nt.assert_equal(home_dir, abspath(HOME_TEST_DIR)) |
|
167 | nt.assert_equal(home_dir, abspath(HOME_TEST_DIR)) | |
166 |
|
168 | |||
167 |
|
169 | |||
168 | @skip_if_not_win32 |
|
170 | @skip_if_not_win32 | |
169 | @with_environment |
|
171 | @with_environment | |
170 | def test_get_home_dir_6(): |
|
172 | def test_get_home_dir_6(): | |
171 | """Using USERPROFILE, os=='nt'. |
|
173 | """Using USERPROFILE, os=='nt'. | |
172 |
|
174 | |||
173 | HOMESHARE, HOMEDRIVE, HOMEPATH are missing. |
|
175 | HOMESHARE, HOMEDRIVE, HOMEPATH are missing. | |
174 | """ |
|
176 | """ | |
175 |
|
177 | |||
176 | os.name = 'nt' |
|
178 | os.name = 'nt' | |
177 | env.pop('HOMESHARE', None) |
|
179 | env.pop('HOMESHARE', None) | |
178 | env.pop('HOMEDRIVE', None) |
|
180 | env.pop('HOMEDRIVE', None) | |
179 | env.pop('HOMEPATH', None) |
|
181 | env.pop('HOMEPATH', None) | |
180 | env["USERPROFILE"] = abspath(HOME_TEST_DIR) |
|
182 | env["USERPROFILE"] = abspath(HOME_TEST_DIR) | |
181 | home_dir = path.get_home_dir() |
|
183 | home_dir = path.get_home_dir() | |
182 | nt.assert_equal(home_dir, abspath(HOME_TEST_DIR)) |
|
184 | nt.assert_equal(home_dir, abspath(HOME_TEST_DIR)) | |
183 |
|
185 | |||
184 |
|
186 | |||
185 | @skip_if_not_win32 |
|
187 | @skip_if_not_win32 | |
186 | @with_environment |
|
188 | @with_environment | |
187 | def test_get_home_dir_7(): |
|
189 | def test_get_home_dir_7(): | |
188 | """Using HOMESHARE, os=='nt'.""" |
|
190 | """Using HOMESHARE, os=='nt'.""" | |
189 |
|
191 | |||
190 | os.name = 'nt' |
|
192 | os.name = 'nt' | |
191 | env["HOMESHARE"] = abspath(HOME_TEST_DIR) |
|
193 | env["HOMESHARE"] = abspath(HOME_TEST_DIR) | |
192 | home_dir = path.get_home_dir() |
|
194 | home_dir = path.get_home_dir() | |
193 | nt.assert_equal(home_dir, abspath(HOME_TEST_DIR)) |
|
195 | nt.assert_equal(home_dir, abspath(HOME_TEST_DIR)) | |
194 |
|
196 | |||
195 | # Should we stub wreg fully so we can run the test on all platforms? |
|
197 | # Should we stub wreg fully so we can run the test on all platforms? | |
196 | @skip_if_not_win32 |
|
198 | @skip_if_not_win32 | |
197 | @with_environment |
|
199 | @with_environment | |
198 | def test_get_home_dir_8(): |
|
200 | def test_get_home_dir_8(): | |
199 | """Using registry hack for 'My Documents', os=='nt' |
|
201 | """Using registry hack for 'My Documents', os=='nt' | |
200 |
|
202 | |||
201 | HOMESHARE, HOMEDRIVE, HOMEPATH, USERPROFILE and others are missing. |
|
203 | HOMESHARE, HOMEDRIVE, HOMEPATH, USERPROFILE and others are missing. | |
202 | """ |
|
204 | """ | |
203 | os.name = 'nt' |
|
205 | os.name = 'nt' | |
204 | # Remove from stub environment all keys that may be set |
|
206 | # Remove from stub environment all keys that may be set | |
205 | for key in ['HOME', 'HOMESHARE', 'HOMEDRIVE', 'HOMEPATH', 'USERPROFILE']: |
|
207 | for key in ['HOME', 'HOMESHARE', 'HOMEDRIVE', 'HOMEPATH', 'USERPROFILE']: | |
206 | env.pop(key, None) |
|
208 | env.pop(key, None) | |
207 |
|
209 | |||
208 | #Stub windows registry functions |
|
210 | #Stub windows registry functions | |
209 | def OpenKey(x, y): |
|
211 | def OpenKey(x, y): | |
210 | class key: |
|
212 | class key: | |
211 | def Close(self): |
|
213 | def Close(self): | |
212 | pass |
|
214 | pass | |
213 | return key() |
|
215 | return key() | |
214 | def QueryValueEx(x, y): |
|
216 | def QueryValueEx(x, y): | |
215 | return [abspath(HOME_TEST_DIR)] |
|
217 | return [abspath(HOME_TEST_DIR)] | |
216 |
|
218 | |||
217 | wreg.OpenKey = OpenKey |
|
219 | wreg.OpenKey = OpenKey | |
218 | wreg.QueryValueEx = QueryValueEx |
|
220 | wreg.QueryValueEx = QueryValueEx | |
219 |
|
221 | |||
220 | home_dir = path.get_home_dir() |
|
222 | home_dir = path.get_home_dir() | |
221 | nt.assert_equal(home_dir, abspath(HOME_TEST_DIR)) |
|
223 | nt.assert_equal(home_dir, abspath(HOME_TEST_DIR)) | |
222 |
|
224 | |||
223 |
|
225 | |||
224 | @with_environment |
|
226 | @with_environment | |
225 | def test_get_ipython_dir_1(): |
|
227 | def test_get_ipython_dir_1(): | |
226 | """test_get_ipython_dir_1, Testcase to see if we can call get_ipython_dir without Exceptions.""" |
|
228 | """test_get_ipython_dir_1, Testcase to see if we can call get_ipython_dir without Exceptions.""" | |
227 | env['IPYTHON_DIR'] = "someplace/.ipython" |
|
229 | env['IPYTHON_DIR'] = "someplace/.ipython" | |
228 | ipdir = path.get_ipython_dir() |
|
230 | ipdir = path.get_ipython_dir() | |
229 | nt.assert_equal(ipdir, "someplace/.ipython") |
|
231 | nt.assert_equal(ipdir, "someplace/.ipython") | |
230 |
|
232 | |||
231 |
|
233 | |||
232 | @with_environment |
|
234 | @with_environment | |
233 | def test_get_ipython_dir_2(): |
|
235 | def test_get_ipython_dir_2(): | |
234 | """test_get_ipython_dir_2, Testcase to see if we can call get_ipython_dir without Exceptions.""" |
|
236 | """test_get_ipython_dir_2, Testcase to see if we can call get_ipython_dir without Exceptions.""" | |
235 | path.get_home_dir = lambda : "someplace" |
|
237 | path.get_home_dir = lambda : "someplace" | |
236 | os.name = "posix" |
|
238 | os.name = "posix" | |
237 | env.pop('IPYTHON_DIR', None) |
|
239 | env.pop('IPYTHON_DIR', None) | |
238 | env.pop('IPYTHONDIR', None) |
|
240 | env.pop('IPYTHONDIR', None) | |
|
241 | env.pop('XDG_CONFIG_HOME', None) | |||
239 | ipdir = path.get_ipython_dir() |
|
242 | ipdir = path.get_ipython_dir() | |
240 | nt.assert_equal(ipdir, os.path.join("someplace", ".ipython")) |
|
243 | nt.assert_equal(ipdir, os.path.join("someplace", ".ipython")) | |
241 |
|
244 | |||
|
245 | @with_environment | |||
|
246 | def test_get_ipython_dir_3(): | |||
|
247 | """test_get_ipython_dir_3, use XDG if defined, and .ipython doesn't exist.""" | |||
|
248 | path.get_home_dir = lambda : "someplace" | |||
|
249 | os.name = "posix" | |||
|
250 | env.pop('IPYTHON_DIR', None) | |||
|
251 | env.pop('IPYTHONDIR', None) | |||
|
252 | env['XDG_CONFIG_HOME'] = XDG_TEST_DIR | |||
|
253 | ipdir = path.get_ipython_dir() | |||
|
254 | nt.assert_equal(ipdir, os.path.join(XDG_TEST_DIR, "ipython")) | |||
|
255 | ||||
|
256 | @with_environment | |||
|
257 | def test_get_ipython_dir_4(): | |||
|
258 | """test_get_ipython_dir_4, use XDG if both exist.""" | |||
|
259 | path.get_home_dir = lambda : HOME_TEST_DIR | |||
|
260 | os.name = "posix" | |||
|
261 | env.pop('IPYTHON_DIR', None) | |||
|
262 | env.pop('IPYTHONDIR', None) | |||
|
263 | env['XDG_CONFIG_HOME'] = XDG_TEST_DIR | |||
|
264 | xdg_ipdir = os.path.join(XDG_TEST_DIR, "ipython") | |||
|
265 | ipdir = path.get_ipython_dir() | |||
|
266 | nt.assert_equal(ipdir, xdg_ipdir) | |||
|
267 | ||||
|
268 | @with_environment | |||
|
269 | def test_get_ipython_dir_5(): | |||
|
270 | """test_get_ipython_dir_5, use .ipython if exists and XDG defined, but doesn't exist.""" | |||
|
271 | os.name = "posix" | |||
|
272 | env.pop('IPYTHON_DIR', None) | |||
|
273 | env.pop('IPYTHONDIR', None) | |||
|
274 | env['XDG_CONFIG_HOME'] = XDG_TEST_DIR | |||
|
275 | os.rmdir(os.path.join(XDG_TEST_DIR, 'ipython')) | |||
|
276 | ipdir = path.get_ipython_dir() | |||
|
277 | nt.assert_equal(ipdir, IP_TEST_DIR) | |||
|
278 | ||||
|
279 | @with_environment | |||
|
280 | def test_get_ipython_dir_6(): | |||
|
281 | """test_get_ipython_dir_6, use XDG if defined and neither exist.""" | |||
|
282 | path.get_home_dir = lambda : 'somehome' | |||
|
283 | path.get_xdg_dir = lambda : 'somexdg' | |||
|
284 | os.name = "posix" | |||
|
285 | env.pop('IPYTHON_DIR', None) | |||
|
286 | env.pop('IPYTHONDIR', None) | |||
|
287 | xdg_ipdir = os.path.join("somexdg", "ipython") | |||
|
288 | ipdir = path.get_ipython_dir() | |||
|
289 | nt.assert_equal(ipdir, xdg_ipdir) | |||
|
290 | ||||
|
291 | @with_environment | |||
|
292 | def test_get_xdg_dir_1(): | |||
|
293 | """test_get_xdg_dir_1, check xdg_dir""" | |||
|
294 | reload(path) | |||
|
295 | path.get_home_dir = lambda : 'somewhere' | |||
|
296 | os.name = "posix" | |||
|
297 | env.pop('IPYTHON_DIR', None) | |||
|
298 | env.pop('IPYTHONDIR', None) | |||
|
299 | env.pop('XDG_CONFIG_HOME', None) | |||
|
300 | ||||
|
301 | nt.assert_equal(path.get_xdg_dir(), os.path.join('somewhere', '.config')) | |||
|
302 | ||||
|
303 | ||||
|
304 | @with_environment | |||
|
305 | def test_get_xdg_dir_1(): | |||
|
306 | """test_get_xdg_dir_1, check nonexistant xdg_dir""" | |||
|
307 | reload(path) | |||
|
308 | path.get_home_dir = lambda : HOME_TEST_DIR | |||
|
309 | os.name = "posix" | |||
|
310 | env.pop('IPYTHON_DIR', None) | |||
|
311 | env.pop('IPYTHONDIR', None) | |||
|
312 | env.pop('XDG_CONFIG_HOME', None) | |||
|
313 | nt.assert_equal(path.get_xdg_dir(), None) | |||
|
314 | ||||
|
315 | @with_environment | |||
|
316 | def test_get_xdg_dir_2(): | |||
|
317 | """test_get_xdg_dir_2, check xdg_dir default to ~/.config""" | |||
|
318 | reload(path) | |||
|
319 | path.get_home_dir = lambda : HOME_TEST_DIR | |||
|
320 | os.name = "posix" | |||
|
321 | env.pop('IPYTHON_DIR', None) | |||
|
322 | env.pop('IPYTHONDIR', None) | |||
|
323 | env.pop('XDG_CONFIG_HOME', None) | |||
|
324 | cfgdir=os.path.join(path.get_home_dir(), '.config') | |||
|
325 | os.makedirs(cfgdir) | |||
|
326 | ||||
|
327 | nt.assert_equal(path.get_xdg_dir(), cfgdir) | |||
242 |
|
328 | |||
243 | def test_filefind(): |
|
329 | def test_filefind(): | |
244 | """Various tests for filefind""" |
|
330 | """Various tests for filefind""" | |
245 | f = tempfile.NamedTemporaryFile() |
|
331 | f = tempfile.NamedTemporaryFile() | |
246 | # print 'fname:',f.name |
|
332 | # print 'fname:',f.name | |
247 | alt_dirs = path.get_ipython_dir() |
|
333 | alt_dirs = path.get_ipython_dir() | |
248 | t = path.filefind(f.name, alt_dirs) |
|
334 | t = path.filefind(f.name, alt_dirs) | |
249 | # print 'found:',t |
|
335 | # print 'found:',t | |
250 |
|
336 | |||
251 |
|
337 | |||
252 | def test_get_ipython_package_dir(): |
|
338 | def test_get_ipython_package_dir(): | |
253 | ipdir = path.get_ipython_package_dir() |
|
339 | ipdir = path.get_ipython_package_dir() | |
254 | nt.assert_true(os.path.isdir(ipdir)) |
|
340 | nt.assert_true(os.path.isdir(ipdir)) | |
255 |
|
341 | |||
256 |
|
342 | |||
257 | def test_get_ipython_module_path(): |
|
343 | def test_get_ipython_module_path(): | |
258 | ipapp_path = path.get_ipython_module_path('IPython.frontend.terminal.ipapp') |
|
344 | ipapp_path = path.get_ipython_module_path('IPython.frontend.terminal.ipapp') | |
259 | nt.assert_true(os.path.isfile(ipapp_path)) |
|
345 | nt.assert_true(os.path.isfile(ipapp_path)) | |
260 |
|
346 | |||
261 |
|
347 | |||
262 | @dec.skip_if_not_win32 |
|
348 | @dec.skip_if_not_win32 | |
263 | def test_get_long_path_name_win32(): |
|
349 | def test_get_long_path_name_win32(): | |
264 | p = path.get_long_path_name('c:\\docume~1') |
|
350 | p = path.get_long_path_name('c:\\docume~1') | |
265 | nt.assert_equals(p,u'c:\\Documents and Settings') |
|
351 | nt.assert_equals(p,u'c:\\Documents and Settings') | |
266 |
|
352 | |||
267 |
|
353 | |||
268 | @dec.skip_win32 |
|
354 | @dec.skip_win32 | |
269 | def test_get_long_path_name(): |
|
355 | def test_get_long_path_name(): | |
270 | p = path.get_long_path_name('/usr/local') |
|
356 | p = path.get_long_path_name('/usr/local') | |
271 | nt.assert_equals(p,'/usr/local') |
|
357 | nt.assert_equals(p,'/usr/local') | |
272 |
|
358 |
@@ -1,230 +1,231 b'' | |||||
1 | .. _initial config: |
|
1 | .. _initial config: | |
2 |
|
2 | |||
3 | ============================================================= |
|
3 | ============================================================= | |
4 | Outdated configuration information that might still be useful |
|
4 | Outdated configuration information that might still be useful | |
5 | ============================================================= |
|
5 | ============================================================= | |
6 |
|
6 | |||
7 | .. warning:: |
|
7 | .. warning:: | |
8 |
|
8 | |||
9 | All of the information in this file is outdated. Until the new |
|
9 | All of the information in this file is outdated. Until the new | |
10 | configuration system is better documented, this material is being kept. |
|
10 | configuration system is better documented, this material is being kept. | |
11 |
|
11 | |||
12 | This section will help you set various things in your environment for |
|
12 | This section will help you set various things in your environment for | |
13 | your IPython sessions to be as efficient as possible. All of IPython's |
|
13 | your IPython sessions to be as efficient as possible. All of IPython's | |
14 | configuration information, along with several example files, is stored |
|
14 | configuration information, along with several example files, is stored | |
15 |
in a directory named by default $HOME/.ipython |
|
15 | in a directory named by default $HOME/.config/ipython if $HOME/.config | |
|
16 | exists (Linux), or $HOME/.ipython as a secondary default. You can change this by | |||
16 | defining the environment variable IPYTHONDIR, or at runtime with the |
|
17 | defining the environment variable IPYTHONDIR, or at runtime with the | |
17 | command line option -ipythondir. |
|
18 | command line option -ipythondir. | |
18 |
|
19 | |||
19 | If all goes well, the first time you run IPython it should automatically create |
|
20 | If all goes well, the first time you run IPython it should automatically create | |
20 | a user copy of the config directory for you, based on its builtin defaults. You |
|
21 | a user copy of the config directory for you, based on its builtin defaults. You | |
21 | can look at the files it creates to learn more about configuring the |
|
22 | can look at the files it creates to learn more about configuring the | |
22 | system. The main file you will modify to configure IPython's behavior is called |
|
23 | system. The main file you will modify to configure IPython's behavior is called | |
23 | ipythonrc (with a .ini extension under Windows), included for reference |
|
24 | ipythonrc (with a .ini extension under Windows), included for reference | |
24 | :ref:`here <ipythonrc>`. This file is very commented and has many variables you |
|
25 | :ref:`here <ipythonrc>`. This file is very commented and has many variables you | |
25 | can change to suit your taste, you can find more details :ref:`here |
|
26 | can change to suit your taste, you can find more details :ref:`here | |
26 | <customization>`. Here we discuss the basic things you will want to make sure |
|
27 | <customization>`. Here we discuss the basic things you will want to make sure | |
27 | things are working properly from the beginning. |
|
28 | things are working properly from the beginning. | |
28 |
|
29 | |||
29 | Color |
|
30 | Color | |
30 | ===== |
|
31 | ===== | |
31 |
|
32 | |||
32 | The default IPython configuration has most bells and whistles turned on |
|
33 | The default IPython configuration has most bells and whistles turned on | |
33 | (they're pretty safe). But there's one that may cause problems on some |
|
34 | (they're pretty safe). But there's one that may cause problems on some | |
34 | systems: the use of color on screen for displaying information. This is |
|
35 | systems: the use of color on screen for displaying information. This is | |
35 | very useful, since IPython can show prompts and exception tracebacks |
|
36 | very useful, since IPython can show prompts and exception tracebacks | |
36 | with various colors, display syntax-highlighted source code, and in |
|
37 | with various colors, display syntax-highlighted source code, and in | |
37 | general make it easier to visually parse information. |
|
38 | general make it easier to visually parse information. | |
38 |
|
39 | |||
39 | The following terminals seem to handle the color sequences fine: |
|
40 | The following terminals seem to handle the color sequences fine: | |
40 |
|
41 | |||
41 | * Linux main text console, KDE Konsole, Gnome Terminal, E-term, |
|
42 | * Linux main text console, KDE Konsole, Gnome Terminal, E-term, | |
42 | rxvt, xterm. |
|
43 | rxvt, xterm. | |
43 | * CDE terminal (tested under Solaris). This one boldfaces light colors. |
|
44 | * CDE terminal (tested under Solaris). This one boldfaces light colors. | |
44 | * (X)Emacs buffers. See the emacs_ section for more details on |
|
45 | * (X)Emacs buffers. See the emacs_ section for more details on | |
45 | using IPython with (X)Emacs. |
|
46 | using IPython with (X)Emacs. | |
46 | * A Windows (XP/2k) command prompt with pyreadline_. |
|
47 | * A Windows (XP/2k) command prompt with pyreadline_. | |
47 | * A Windows (XP/2k) CygWin shell. Although some users have reported |
|
48 | * A Windows (XP/2k) CygWin shell. Although some users have reported | |
48 | problems; it is not clear whether there is an issue for everyone |
|
49 | problems; it is not clear whether there is an issue for everyone | |
49 | or only under specific configurations. If you have full color |
|
50 | or only under specific configurations. If you have full color | |
50 | support under cygwin, please post to the IPython mailing list so |
|
51 | support under cygwin, please post to the IPython mailing list so | |
51 | this issue can be resolved for all users. |
|
52 | this issue can be resolved for all users. | |
52 |
|
53 | |||
53 | .. _pyreadline: https://code.launchpad.net/pyreadline |
|
54 | .. _pyreadline: https://code.launchpad.net/pyreadline | |
54 |
|
55 | |||
55 | These have shown problems: |
|
56 | These have shown problems: | |
56 |
|
57 | |||
57 | * Windows command prompt in WinXP/2k logged into a Linux machine via |
|
58 | * Windows command prompt in WinXP/2k logged into a Linux machine via | |
58 | telnet or ssh. |
|
59 | telnet or ssh. | |
59 | * Windows native command prompt in WinXP/2k, without Gary Bishop's |
|
60 | * Windows native command prompt in WinXP/2k, without Gary Bishop's | |
60 | extensions. Once Gary's readline library is installed, the normal |
|
61 | extensions. Once Gary's readline library is installed, the normal | |
61 | WinXP/2k command prompt works perfectly. |
|
62 | WinXP/2k command prompt works perfectly. | |
62 |
|
63 | |||
63 | Currently the following color schemes are available: |
|
64 | Currently the following color schemes are available: | |
64 |
|
65 | |||
65 | * NoColor: uses no color escapes at all (all escapes are empty '' '' |
|
66 | * NoColor: uses no color escapes at all (all escapes are empty '' '' | |
66 | strings). This 'scheme' is thus fully safe to use in any terminal. |
|
67 | strings). This 'scheme' is thus fully safe to use in any terminal. | |
67 | * Linux: works well in Linux console type environments: dark |
|
68 | * Linux: works well in Linux console type environments: dark | |
68 | background with light fonts. It uses bright colors for |
|
69 | background with light fonts. It uses bright colors for | |
69 | information, so it is difficult to read if you have a light |
|
70 | information, so it is difficult to read if you have a light | |
70 | colored background. |
|
71 | colored background. | |
71 | * LightBG: the basic colors are similar to those in the Linux scheme |
|
72 | * LightBG: the basic colors are similar to those in the Linux scheme | |
72 | but darker. It is easy to read in terminals with light backgrounds. |
|
73 | but darker. It is easy to read in terminals with light backgrounds. | |
73 |
|
74 | |||
74 | IPython uses colors for two main groups of things: prompts and |
|
75 | IPython uses colors for two main groups of things: prompts and | |
75 | tracebacks which are directly printed to the terminal, and the object |
|
76 | tracebacks which are directly printed to the terminal, and the object | |
76 | introspection system which passes large sets of data through a pager. |
|
77 | introspection system which passes large sets of data through a pager. | |
77 |
|
78 | |||
78 | Input/Output prompts and exception tracebacks |
|
79 | Input/Output prompts and exception tracebacks | |
79 | ============================================= |
|
80 | ============================================= | |
80 |
|
81 | |||
81 | You can test whether the colored prompts and tracebacks work on your |
|
82 | You can test whether the colored prompts and tracebacks work on your | |
82 | system interactively by typing '%colors Linux' at the prompt (use |
|
83 | system interactively by typing '%colors Linux' at the prompt (use | |
83 | '%colors LightBG' if your terminal has a light background). If the input |
|
84 | '%colors LightBG' if your terminal has a light background). If the input | |
84 | prompt shows garbage like:: |
|
85 | prompt shows garbage like:: | |
85 |
|
86 | |||
86 | [0;32mIn [[1;32m1[0;32m]: [0;00m |
|
87 | [0;32mIn [[1;32m1[0;32m]: [0;00m | |
87 |
|
88 | |||
88 | instead of (in color) something like:: |
|
89 | instead of (in color) something like:: | |
89 |
|
90 | |||
90 | In [1]: |
|
91 | In [1]: | |
91 |
|
92 | |||
92 | this means that your terminal doesn't properly handle color escape |
|
93 | this means that your terminal doesn't properly handle color escape | |
93 | sequences. You can go to a 'no color' mode by typing '%colors NoColor'. |
|
94 | sequences. You can go to a 'no color' mode by typing '%colors NoColor'. | |
94 |
|
95 | |||
95 | You can try using a different terminal emulator program (Emacs users, |
|
96 | You can try using a different terminal emulator program (Emacs users, | |
96 | see below). To permanently set your color preferences, edit the file |
|
97 | see below). To permanently set your color preferences, edit the file | |
97 |
$ |
|
98 | $IPYTHON_DIR/ipythonrc and set the colors option to the desired value. | |
98 |
|
99 | |||
99 |
|
100 | |||
100 | Object details (types, docstrings, source code, etc.) |
|
101 | Object details (types, docstrings, source code, etc.) | |
101 | ===================================================== |
|
102 | ===================================================== | |
102 |
|
103 | |||
103 | IPython has a set of special functions for studying the objects you are working |
|
104 | IPython has a set of special functions for studying the objects you are working | |
104 | with, discussed in detail :ref:`here <dynamic_object_info>`. But this system |
|
105 | with, discussed in detail :ref:`here <dynamic_object_info>`. But this system | |
105 | relies on passing information which is longer than your screen through a data |
|
106 | relies on passing information which is longer than your screen through a data | |
106 | pager, such as the common Unix less and more programs. In order to be able to |
|
107 | pager, such as the common Unix less and more programs. In order to be able to | |
107 | see this information in color, your pager needs to be properly configured. I |
|
108 | see this information in color, your pager needs to be properly configured. I | |
108 | strongly recommend using less instead of more, as it seems that more simply can |
|
109 | strongly recommend using less instead of more, as it seems that more simply can | |
109 | not understand colored text correctly. |
|
110 | not understand colored text correctly. | |
110 |
|
111 | |||
111 | In order to configure less as your default pager, do the following: |
|
112 | In order to configure less as your default pager, do the following: | |
112 |
|
113 | |||
113 | 1. Set the environment PAGER variable to less. |
|
114 | 1. Set the environment PAGER variable to less. | |
114 | 2. Set the environment LESS variable to -r (plus any other options |
|
115 | 2. Set the environment LESS variable to -r (plus any other options | |
115 | you always want to pass to less by default). This tells less to |
|
116 | you always want to pass to less by default). This tells less to | |
116 | properly interpret control sequences, which is how color |
|
117 | properly interpret control sequences, which is how color | |
117 | information is given to your terminal. |
|
118 | information is given to your terminal. | |
118 |
|
119 | |||
119 | For the bash shell, add to your ~/.bashrc file the lines:: |
|
120 | For the bash shell, add to your ~/.bashrc file the lines:: | |
120 |
|
121 | |||
121 | export PAGER=less |
|
122 | export PAGER=less | |
122 | export LESS=-r |
|
123 | export LESS=-r | |
123 |
|
124 | |||
124 | For the csh or tcsh shells, add to your ~/.cshrc file the lines:: |
|
125 | For the csh or tcsh shells, add to your ~/.cshrc file the lines:: | |
125 |
|
126 | |||
126 | setenv PAGER less |
|
127 | setenv PAGER less | |
127 | setenv LESS -r |
|
128 | setenv LESS -r | |
128 |
|
129 | |||
129 | There is similar syntax for other Unix shells, look at your system |
|
130 | There is similar syntax for other Unix shells, look at your system | |
130 | documentation for details. |
|
131 | documentation for details. | |
131 |
|
132 | |||
132 | If you are on a system which lacks proper data pagers (such as Windows), |
|
133 | If you are on a system which lacks proper data pagers (such as Windows), | |
133 | IPython will use a very limited builtin pager. |
|
134 | IPython will use a very limited builtin pager. | |
134 |
|
135 | |||
135 | .. _Prompts: |
|
136 | .. _Prompts: | |
136 |
|
137 | |||
137 | Fine-tuning your prompt |
|
138 | Fine-tuning your prompt | |
138 | ======================= |
|
139 | ======================= | |
139 |
|
140 | |||
140 | IPython's prompts can be customized using a syntax similar to that of |
|
141 | IPython's prompts can be customized using a syntax similar to that of | |
141 | the bash shell. Many of bash's escapes are supported, as well as a few |
|
142 | the bash shell. Many of bash's escapes are supported, as well as a few | |
142 | additional ones. We list them below:: |
|
143 | additional ones. We list them below:: | |
143 |
|
144 | |||
144 | \# |
|
145 | \# | |
145 | the prompt/history count number. This escape is automatically |
|
146 | the prompt/history count number. This escape is automatically | |
146 | wrapped in the coloring codes for the currently active color scheme. |
|
147 | wrapped in the coloring codes for the currently active color scheme. | |
147 | \N |
|
148 | \N | |
148 | the 'naked' prompt/history count number: this is just the number |
|
149 | the 'naked' prompt/history count number: this is just the number | |
149 | itself, without any coloring applied to it. This lets you produce |
|
150 | itself, without any coloring applied to it. This lets you produce | |
150 | numbered prompts with your own colors. |
|
151 | numbered prompts with your own colors. | |
151 | \D |
|
152 | \D | |
152 | the prompt/history count, with the actual digits replaced by dots. |
|
153 | the prompt/history count, with the actual digits replaced by dots. | |
153 | Used mainly in continuation prompts (prompt_in2) |
|
154 | Used mainly in continuation prompts (prompt_in2) | |
154 | \w |
|
155 | \w | |
155 | the current working directory |
|
156 | the current working directory | |
156 | \W |
|
157 | \W | |
157 | the basename of current working directory |
|
158 | the basename of current working directory | |
158 | \Xn |
|
159 | \Xn | |
159 | where $n=0\ldots5.$ The current working directory, with $HOME |
|
160 | where $n=0\ldots5.$ The current working directory, with $HOME | |
160 | replaced by ~, and filtered out to contain only $n$ path elements |
|
161 | replaced by ~, and filtered out to contain only $n$ path elements | |
161 | \Yn |
|
162 | \Yn | |
162 | Similar to \Xn, but with the $n+1$ element included if it is ~ (this |
|
163 | Similar to \Xn, but with the $n+1$ element included if it is ~ (this | |
163 | is similar to the behavior of the %cn escapes in tcsh) |
|
164 | is similar to the behavior of the %cn escapes in tcsh) | |
164 | \u |
|
165 | \u | |
165 | the username of the current user |
|
166 | the username of the current user | |
166 | \$ |
|
167 | \$ | |
167 | if the effective UID is 0, a #, otherwise a $ |
|
168 | if the effective UID is 0, a #, otherwise a $ | |
168 | \h |
|
169 | \h | |
169 | the hostname up to the first '.' |
|
170 | the hostname up to the first '.' | |
170 | \H |
|
171 | \H | |
171 | the hostname |
|
172 | the hostname | |
172 | \n |
|
173 | \n | |
173 | a newline |
|
174 | a newline | |
174 | \r |
|
175 | \r | |
175 | a carriage return |
|
176 | a carriage return | |
176 | \v |
|
177 | \v | |
177 | IPython version string |
|
178 | IPython version string | |
178 |
|
179 | |||
179 | In addition to these, ANSI color escapes can be insterted into the |
|
180 | In addition to these, ANSI color escapes can be insterted into the | |
180 | prompts, as \C_ColorName. The list of valid color names is: Black, Blue, |
|
181 | prompts, as \C_ColorName. The list of valid color names is: Black, Blue, | |
181 | Brown, Cyan, DarkGray, Green, LightBlue, LightCyan, LightGray, |
|
182 | Brown, Cyan, DarkGray, Green, LightBlue, LightCyan, LightGray, | |
182 | LightGreen, LightPurple, LightRed, NoColor, Normal, Purple, Red, White, |
|
183 | LightGreen, LightPurple, LightRed, NoColor, Normal, Purple, Red, White, | |
183 | Yellow. |
|
184 | Yellow. | |
184 |
|
185 | |||
185 | Finally, IPython supports the evaluation of arbitrary expressions in |
|
186 | Finally, IPython supports the evaluation of arbitrary expressions in | |
186 | your prompt string. The prompt strings are evaluated through the syntax |
|
187 | your prompt string. The prompt strings are evaluated through the syntax | |
187 | of PEP 215, but basically you can use $x.y to expand the value of x.y, |
|
188 | of PEP 215, but basically you can use $x.y to expand the value of x.y, | |
188 | and for more complicated expressions you can use braces: ${foo()+x} will |
|
189 | and for more complicated expressions you can use braces: ${foo()+x} will | |
189 | call function foo and add to it the value of x, before putting the |
|
190 | call function foo and add to it the value of x, before putting the | |
190 | result into your prompt. For example, using |
|
191 | result into your prompt. For example, using | |
191 | prompt_in1 '${commands.getoutput("uptime")}\nIn [\#]: ' |
|
192 | prompt_in1 '${commands.getoutput("uptime")}\nIn [\#]: ' | |
192 | will print the result of the uptime command on each prompt (assuming the |
|
193 | will print the result of the uptime command on each prompt (assuming the | |
193 | commands module has been imported in your ipythonrc file). |
|
194 | commands module has been imported in your ipythonrc file). | |
194 |
|
195 | |||
195 |
|
196 | |||
196 | Prompt examples |
|
197 | Prompt examples | |
197 |
|
198 | |||
198 | The following options in an ipythonrc file will give you IPython's |
|
199 | The following options in an ipythonrc file will give you IPython's | |
199 | default prompts:: |
|
200 | default prompts:: | |
200 |
|
201 | |||
201 | prompt_in1 'In [\#]:' |
|
202 | prompt_in1 'In [\#]:' | |
202 | prompt_in2 ' .\D.:' |
|
203 | prompt_in2 ' .\D.:' | |
203 | prompt_out 'Out[\#]:' |
|
204 | prompt_out 'Out[\#]:' | |
204 |
|
205 | |||
205 | which look like this:: |
|
206 | which look like this:: | |
206 |
|
207 | |||
207 | In [1]: 1+2 |
|
208 | In [1]: 1+2 | |
208 | Out[1]: 3 |
|
209 | Out[1]: 3 | |
209 |
|
210 | |||
210 | In [2]: for i in (1,2,3): |
|
211 | In [2]: for i in (1,2,3): | |
211 | ...: print i, |
|
212 | ...: print i, | |
212 | ...: |
|
213 | ...: | |
213 | 1 2 3 |
|
214 | 1 2 3 | |
214 |
|
215 | |||
215 | These will give you a very colorful prompt with path information:: |
|
216 | These will give you a very colorful prompt with path information:: | |
216 |
|
217 | |||
217 | #prompt_in1 '\C_Red\u\C_Blue[\C_Cyan\Y1\C_Blue]\C_LightGreen\#>' |
|
218 | #prompt_in1 '\C_Red\u\C_Blue[\C_Cyan\Y1\C_Blue]\C_LightGreen\#>' | |
218 | prompt_in2 ' ..\D>' |
|
219 | prompt_in2 ' ..\D>' | |
219 | prompt_out '<\#>' |
|
220 | prompt_out '<\#>' | |
220 |
|
221 | |||
221 | which look like this:: |
|
222 | which look like this:: | |
222 |
|
223 | |||
223 | fperez[~/ipython]1> 1+2 |
|
224 | fperez[~/ipython]1> 1+2 | |
224 | <1> 3 |
|
225 | <1> 3 | |
225 | fperez[~/ipython]2> for i in (1,2,3): |
|
226 | fperez[~/ipython]2> for i in (1,2,3): | |
226 | ...> print i, |
|
227 | ...> print i, | |
227 | ...> |
|
228 | ...> | |
228 | 1 2 3 |
|
229 | 1 2 3 | |
229 |
|
230 | |||
230 |
|
231 |
@@ -1,329 +1,342 b'' | |||||
1 | .. _config_overview: |
|
1 | .. _config_overview: | |
2 |
|
2 | |||
3 | ============================================ |
|
3 | ============================================ | |
4 | Overview of the IPython configuration system |
|
4 | Overview of the IPython configuration system | |
5 | ============================================ |
|
5 | ============================================ | |
6 |
|
6 | |||
7 | This section describes the IPython configuration system. Starting with version |
|
7 | This section describes the IPython configuration system. Starting with version | |
8 | 0.11, IPython has a completely new configuration system that is quite |
|
8 | 0.11, IPython has a completely new configuration system that is quite | |
9 | different from the older :file:`ipythonrc` or :file:`ipy_user_conf.py` |
|
9 | different from the older :file:`ipythonrc` or :file:`ipy_user_conf.py` | |
10 | approaches. The new configuration system was designed from scratch to address |
|
10 | approaches. The new configuration system was designed from scratch to address | |
11 | the particular configuration needs of IPython. While there are many |
|
11 | the particular configuration needs of IPython. While there are many | |
12 | other excellent configuration systems out there, we found that none of them |
|
12 | other excellent configuration systems out there, we found that none of them | |
13 | met our requirements. |
|
13 | met our requirements. | |
14 |
|
14 | |||
15 | .. warning:: |
|
15 | .. warning:: | |
16 |
|
16 | |||
17 | If you are upgrading to version 0.11 of IPython, you will need to migrate |
|
17 | If you are upgrading to version 0.11 of IPython, you will need to migrate | |
18 | your old :file:`ipythonrc` or :file:`ipy_user_conf.py` configuration files |
|
18 | your old :file:`ipythonrc` or :file:`ipy_user_conf.py` configuration files | |
19 | to the new system. Read on for information on how to do this. |
|
19 | to the new system. Read on for information on how to do this. | |
20 |
|
20 | |||
21 | The discussion that follows is focused on teaching user's how to configure |
|
21 | The discussion that follows is focused on teaching user's how to configure | |
22 | IPython to their liking. Developer's who want to know more about how they |
|
22 | IPython to their liking. Developer's who want to know more about how they | |
23 | can enable their objects to take advantage of the configuration system |
|
23 | can enable their objects to take advantage of the configuration system | |
24 | should consult our :ref:`developer guide <developer_guide>` |
|
24 | should consult our :ref:`developer guide <developer_guide>` | |
25 |
|
25 | |||
26 | The main concepts |
|
26 | The main concepts | |
27 | ================= |
|
27 | ================= | |
28 |
|
28 | |||
29 | There are a number of abstractions that the IPython configuration system uses. |
|
29 | There are a number of abstractions that the IPython configuration system uses. | |
30 | Each of these abstractions is represented by a Python class. |
|
30 | Each of these abstractions is represented by a Python class. | |
31 |
|
31 | |||
32 | Configuration object: :class:`~IPython.config.loader.Config` |
|
32 | Configuration object: :class:`~IPython.config.loader.Config` | |
33 | A configuration object is a simple dictionary-like class that holds |
|
33 | A configuration object is a simple dictionary-like class that holds | |
34 | configuration attributes and sub-configuration objects. These classes |
|
34 | configuration attributes and sub-configuration objects. These classes | |
35 | support dotted attribute style access (``Foo.bar``) in addition to the |
|
35 | support dotted attribute style access (``Foo.bar``) in addition to the | |
36 | regular dictionary style access (``Foo['bar']``). Configuration objects |
|
36 | regular dictionary style access (``Foo['bar']``). Configuration objects | |
37 | are smart. They know how to merge themselves with other configuration |
|
37 | are smart. They know how to merge themselves with other configuration | |
38 | objects and they automatically create sub-configuration objects. |
|
38 | objects and they automatically create sub-configuration objects. | |
39 |
|
39 | |||
40 | Application: :class:`~IPython.core.application.Application` |
|
40 | Application: :class:`~IPython.core.application.Application` | |
41 | An application is a process that does a specific job. The most obvious |
|
41 | An application is a process that does a specific job. The most obvious | |
42 | application is the :command:`ipython` command line program. Each |
|
42 | application is the :command:`ipython` command line program. Each | |
43 | application reads a *single* configuration file and command line options |
|
43 | application reads a *single* configuration file and command line options | |
44 | and then produces a master configuration object for the application. This |
|
44 | and then produces a master configuration object for the application. This | |
45 | configuration object is then passed to the configurable objects that the |
|
45 | configuration object is then passed to the configurable objects that the | |
46 | application creates. These configurable objects implement the actual logic |
|
46 | application creates. These configurable objects implement the actual logic | |
47 | of the application and know how to configure themselves given the |
|
47 | of the application and know how to configure themselves given the | |
48 | configuration object. |
|
48 | configuration object. | |
49 |
|
49 | |||
50 | Component: :class:`~IPython.config.configurable.Configurable` |
|
50 | Component: :class:`~IPython.config.configurable.Configurable` | |
51 | A configurable is a regular Python class that serves as a base class for |
|
51 | A configurable is a regular Python class that serves as a base class for | |
52 | all main classes in an application. The |
|
52 | all main classes in an application. The | |
53 | :class:`~IPython.config.configurable.Configurable` base class is |
|
53 | :class:`~IPython.config.configurable.Configurable` base class is | |
54 | lightweight and only does one things. |
|
54 | lightweight and only does one things. | |
55 |
|
55 | |||
56 | This :class:`~IPython.config.configurable.Configurable` is a subclass |
|
56 | This :class:`~IPython.config.configurable.Configurable` is a subclass | |
57 | of :class:`~IPython.utils.traitlets.HasTraits` that knows how to configure |
|
57 | of :class:`~IPython.utils.traitlets.HasTraits` that knows how to configure | |
58 | itself. Class level traits with the metadata ``config=True`` become |
|
58 | itself. Class level traits with the metadata ``config=True`` become | |
59 | values that can be configured from the command line and configuration |
|
59 | values that can be configured from the command line and configuration | |
60 | files. |
|
60 | files. | |
61 |
|
61 | |||
62 | Developers create :class:`~IPython.config.configurable.Configurable` |
|
62 | Developers create :class:`~IPython.config.configurable.Configurable` | |
63 | subclasses that implement all of the logic in the application. Each of |
|
63 | subclasses that implement all of the logic in the application. Each of | |
64 | these subclasses has its own configuration information that controls how |
|
64 | these subclasses has its own configuration information that controls how | |
65 | instances are created. |
|
65 | instances are created. | |
66 |
|
66 | |||
67 | Having described these main concepts, we can now state the main idea in our |
|
67 | Having described these main concepts, we can now state the main idea in our | |
68 | configuration system: *"configuration" allows the default values of class |
|
68 | configuration system: *"configuration" allows the default values of class | |
69 | attributes to be controlled on a class by class basis*. Thus all instances of |
|
69 | attributes to be controlled on a class by class basis*. Thus all instances of | |
70 | a given class are configured in the same way. Furthermore, if two instances |
|
70 | a given class are configured in the same way. Furthermore, if two instances | |
71 | need to be configured differently, they need to be instances of two different |
|
71 | need to be configured differently, they need to be instances of two different | |
72 | classes. While this model may seem a bit restrictive, we have found that it |
|
72 | classes. While this model may seem a bit restrictive, we have found that it | |
73 | expresses most things that need to be configured extremely well. However, it |
|
73 | expresses most things that need to be configured extremely well. However, it | |
74 | is possible to create two instances of the same class that have different |
|
74 | is possible to create two instances of the same class that have different | |
75 | trait values. This is done by overriding the configuration. |
|
75 | trait values. This is done by overriding the configuration. | |
76 |
|
76 | |||
77 | Now, we show what our configuration objects and files look like. |
|
77 | Now, we show what our configuration objects and files look like. | |
78 |
|
78 | |||
79 | Configuration objects and files |
|
79 | Configuration objects and files | |
80 | =============================== |
|
80 | =============================== | |
81 |
|
81 | |||
82 | A configuration file is simply a pure Python file that sets the attributes |
|
82 | A configuration file is simply a pure Python file that sets the attributes | |
83 | of a global, pre-created configuration object. This configuration object is a |
|
83 | of a global, pre-created configuration object. This configuration object is a | |
84 | :class:`~IPython.config.loader.Config` instance. While in a configuration |
|
84 | :class:`~IPython.config.loader.Config` instance. While in a configuration | |
85 | file, to get a reference to this object, simply call the :func:`get_config` |
|
85 | file, to get a reference to this object, simply call the :func:`get_config` | |
86 | function. We inject this function into the global namespace that the |
|
86 | function. We inject this function into the global namespace that the | |
87 | configuration file is executed in. |
|
87 | configuration file is executed in. | |
88 |
|
88 | |||
89 | Here is an example of a super simple configuration file that does nothing:: |
|
89 | Here is an example of a super simple configuration file that does nothing:: | |
90 |
|
90 | |||
91 | c = get_config() |
|
91 | c = get_config() | |
92 |
|
92 | |||
93 | Once you get a reference to the configuration object, you simply set |
|
93 | Once you get a reference to the configuration object, you simply set | |
94 | attributes on it. All you have to know is: |
|
94 | attributes on it. All you have to know is: | |
95 |
|
95 | |||
96 | * The name of each attribute. |
|
96 | * The name of each attribute. | |
97 | * The type of each attribute. |
|
97 | * The type of each attribute. | |
98 |
|
98 | |||
99 | The answers to these two questions are provided by the various |
|
99 | The answers to these two questions are provided by the various | |
100 | :class:`~IPython.config.configurable.Configurable` subclasses that an |
|
100 | :class:`~IPython.config.configurable.Configurable` subclasses that an | |
101 | application uses. Let's look at how this would work for a simple component |
|
101 | application uses. Let's look at how this would work for a simple component | |
102 | subclass:: |
|
102 | subclass:: | |
103 |
|
103 | |||
104 | # Sample component that can be configured. |
|
104 | # Sample component that can be configured. | |
105 | from IPython.config.configurable import Configurable |
|
105 | from IPython.config.configurable import Configurable | |
106 | from IPython.utils.traitlets import Int, Float, Str, Bool |
|
106 | from IPython.utils.traitlets import Int, Float, Str, Bool | |
107 |
|
107 | |||
108 | class MyClass(Configurable): |
|
108 | class MyClass(Configurable): | |
109 | name = Str('defaultname', config=True) |
|
109 | name = Str('defaultname', config=True) | |
110 | ranking = Int(0, config=True) |
|
110 | ranking = Int(0, config=True) | |
111 | value = Float(99.0) |
|
111 | value = Float(99.0) | |
112 | # The rest of the class implementation would go here.. |
|
112 | # The rest of the class implementation would go here.. | |
113 |
|
113 | |||
114 | In this example, we see that :class:`MyClass` has three attributes, two |
|
114 | In this example, we see that :class:`MyClass` has three attributes, two | |
115 | of whom (``name``, ``ranking``) can be configured. All of the attributes |
|
115 | of whom (``name``, ``ranking``) can be configured. All of the attributes | |
116 | are given types and default values. If a :class:`MyClass` is instantiated, |
|
116 | are given types and default values. If a :class:`MyClass` is instantiated, | |
117 | but not configured, these default values will be used. But let's see how |
|
117 | but not configured, these default values will be used. But let's see how | |
118 | to configure this class in a configuration file:: |
|
118 | to configure this class in a configuration file:: | |
119 |
|
119 | |||
120 | # Sample config file |
|
120 | # Sample config file | |
121 | c = get_config() |
|
121 | c = get_config() | |
122 |
|
122 | |||
123 | c.MyClass.name = 'coolname' |
|
123 | c.MyClass.name = 'coolname' | |
124 | c.MyClass.ranking = 10 |
|
124 | c.MyClass.ranking = 10 | |
125 |
|
125 | |||
126 | After this configuration file is loaded, the values set in it will override |
|
126 | After this configuration file is loaded, the values set in it will override | |
127 | the class defaults anytime a :class:`MyClass` is created. Furthermore, |
|
127 | the class defaults anytime a :class:`MyClass` is created. Furthermore, | |
128 | these attributes will be type checked and validated anytime they are set. |
|
128 | these attributes will be type checked and validated anytime they are set. | |
129 | This type checking is handled by the :mod:`IPython.utils.traitlets` module, |
|
129 | This type checking is handled by the :mod:`IPython.utils.traitlets` module, | |
130 | which provides the :class:`Str`, :class:`Int` and :class:`Float` types. In |
|
130 | which provides the :class:`Str`, :class:`Int` and :class:`Float` types. In | |
131 | addition to these traitlets, the :mod:`IPython.utils.traitlets` provides |
|
131 | addition to these traitlets, the :mod:`IPython.utils.traitlets` provides | |
132 | traitlets for a number of other types. |
|
132 | traitlets for a number of other types. | |
133 |
|
133 | |||
134 | .. note:: |
|
134 | .. note:: | |
135 |
|
135 | |||
136 | Underneath the hood, the :class:`Configurable` base class is a subclass of |
|
136 | Underneath the hood, the :class:`Configurable` base class is a subclass of | |
137 | :class:`IPython.utils.traitlets.HasTraits`. The |
|
137 | :class:`IPython.utils.traitlets.HasTraits`. The | |
138 | :mod:`IPython.utils.traitlets` module is a lightweight version of |
|
138 | :mod:`IPython.utils.traitlets` module is a lightweight version of | |
139 | :mod:`enthought.traits`. Our implementation is a pure Python subset |
|
139 | :mod:`enthought.traits`. Our implementation is a pure Python subset | |
140 | (mostly API compatible) of :mod:`enthought.traits` that does not have any |
|
140 | (mostly API compatible) of :mod:`enthought.traits` that does not have any | |
141 | of the automatic GUI generation capabilities. Our plan is to achieve 100% |
|
141 | of the automatic GUI generation capabilities. Our plan is to achieve 100% | |
142 | API compatibility to enable the actual :mod:`enthought.traits` to |
|
142 | API compatibility to enable the actual :mod:`enthought.traits` to | |
143 | eventually be used instead. Currently, we cannot use |
|
143 | eventually be used instead. Currently, we cannot use | |
144 | :mod:`enthought.traits` as we are committed to the core of IPython being |
|
144 | :mod:`enthought.traits` as we are committed to the core of IPython being | |
145 | pure Python. |
|
145 | pure Python. | |
146 |
|
146 | |||
147 | It should be very clear at this point what the naming convention is for |
|
147 | It should be very clear at this point what the naming convention is for | |
148 | configuration attributes:: |
|
148 | configuration attributes:: | |
149 |
|
149 | |||
150 | c.ClassName.attribute_name = attribute_value |
|
150 | c.ClassName.attribute_name = attribute_value | |
151 |
|
151 | |||
152 | Here, ``ClassName`` is the name of the class whose configuration attribute you |
|
152 | Here, ``ClassName`` is the name of the class whose configuration attribute you | |
153 | want to set, ``attribute_name`` is the name of the attribute you want to set |
|
153 | want to set, ``attribute_name`` is the name of the attribute you want to set | |
154 | and ``attribute_value`` the the value you want it to have. The ``ClassName`` |
|
154 | and ``attribute_value`` the the value you want it to have. The ``ClassName`` | |
155 | attribute of ``c`` is not the actual class, but instead is another |
|
155 | attribute of ``c`` is not the actual class, but instead is another | |
156 | :class:`~IPython.config.loader.Config` instance. |
|
156 | :class:`~IPython.config.loader.Config` instance. | |
157 |
|
157 | |||
158 | .. note:: |
|
158 | .. note:: | |
159 |
|
159 | |||
160 | The careful reader may wonder how the ``ClassName`` (``MyClass`` in |
|
160 | The careful reader may wonder how the ``ClassName`` (``MyClass`` in | |
161 | the above example) attribute of the configuration object ``c`` gets |
|
161 | the above example) attribute of the configuration object ``c`` gets | |
162 | created. These attributes are created on the fly by the |
|
162 | created. These attributes are created on the fly by the | |
163 | :class:`~IPython.config.loader.Config` instance, using a simple naming |
|
163 | :class:`~IPython.config.loader.Config` instance, using a simple naming | |
164 | convention. Any attribute of a :class:`~IPython.config.loader.Config` |
|
164 | convention. Any attribute of a :class:`~IPython.config.loader.Config` | |
165 | instance whose name begins with an uppercase character is assumed to be a |
|
165 | instance whose name begins with an uppercase character is assumed to be a | |
166 | sub-configuration and a new empty :class:`~IPython.config.loader.Config` |
|
166 | sub-configuration and a new empty :class:`~IPython.config.loader.Config` | |
167 | instance is dynamically created for that attribute. This allows deeply |
|
167 | instance is dynamically created for that attribute. This allows deeply | |
168 | hierarchical information created easily (``c.Foo.Bar.value``) on the fly. |
|
168 | hierarchical information created easily (``c.Foo.Bar.value``) on the fly. | |
169 |
|
169 | |||
170 | Configuration files inheritance |
|
170 | Configuration files inheritance | |
171 | =============================== |
|
171 | =============================== | |
172 |
|
172 | |||
173 | Let's say you want to have different configuration files for various purposes. |
|
173 | Let's say you want to have different configuration files for various purposes. | |
174 | Our configuration system makes it easy for one configuration file to inherit |
|
174 | Our configuration system makes it easy for one configuration file to inherit | |
175 | the information in another configuration file. The :func:`load_subconfig` |
|
175 | the information in another configuration file. The :func:`load_subconfig` | |
176 | command can be used in a configuration file for this purpose. Here is a simple |
|
176 | command can be used in a configuration file for this purpose. Here is a simple | |
177 | example that loads all of the values from the file :file:`base_config.py`:: |
|
177 | example that loads all of the values from the file :file:`base_config.py`:: | |
178 |
|
178 | |||
179 | # base_config.py |
|
179 | # base_config.py | |
180 | c = get_config() |
|
180 | c = get_config() | |
181 | c.MyClass.name = 'coolname' |
|
181 | c.MyClass.name = 'coolname' | |
182 | c.MyClass.ranking = 100 |
|
182 | c.MyClass.ranking = 100 | |
183 |
|
183 | |||
184 | into the configuration file :file:`main_config.py`:: |
|
184 | into the configuration file :file:`main_config.py`:: | |
185 |
|
185 | |||
186 | # main_config.py |
|
186 | # main_config.py | |
187 | c = get_config() |
|
187 | c = get_config() | |
188 |
|
188 | |||
189 | # Load everything from base_config.py |
|
189 | # Load everything from base_config.py | |
190 | load_subconfig('base_config.py') |
|
190 | load_subconfig('base_config.py') | |
191 |
|
191 | |||
192 | # Now override one of the values |
|
192 | # Now override one of the values | |
193 | c.MyClass.name = 'bettername' |
|
193 | c.MyClass.name = 'bettername' | |
194 |
|
194 | |||
195 | In a situation like this the :func:`load_subconfig` makes sure that the |
|
195 | In a situation like this the :func:`load_subconfig` makes sure that the | |
196 | search path for sub-configuration files is inherited from that of the parent. |
|
196 | search path for sub-configuration files is inherited from that of the parent. | |
197 | Thus, you can typically put the two in the same directory and everything will |
|
197 | Thus, you can typically put the two in the same directory and everything will | |
198 | just work. |
|
198 | just work. | |
199 |
|
199 | |||
200 | Class based configuration inheritance |
|
200 | Class based configuration inheritance | |
201 | ===================================== |
|
201 | ===================================== | |
202 |
|
202 | |||
203 | There is another aspect of configuration where inheritance comes into play. |
|
203 | There is another aspect of configuration where inheritance comes into play. | |
204 | Sometimes, your classes will have an inheritance hierarchy that you want |
|
204 | Sometimes, your classes will have an inheritance hierarchy that you want | |
205 | to be reflected in the configuration system. Here is a simple example:: |
|
205 | to be reflected in the configuration system. Here is a simple example:: | |
206 |
|
206 | |||
207 | from IPython.config.configurable import Configurable |
|
207 | from IPython.config.configurable import Configurable | |
208 | from IPython.utils.traitlets import Int, Float, Str, Bool |
|
208 | from IPython.utils.traitlets import Int, Float, Str, Bool | |
209 |
|
209 | |||
210 | class Foo(Configurable): |
|
210 | class Foo(Configurable): | |
211 | name = Str('fooname', config=True) |
|
211 | name = Str('fooname', config=True) | |
212 | value = Float(100.0, config=True) |
|
212 | value = Float(100.0, config=True) | |
213 |
|
213 | |||
214 | class Bar(Foo): |
|
214 | class Bar(Foo): | |
215 | name = Str('barname', config=True) |
|
215 | name = Str('barname', config=True) | |
216 | othervalue = Int(0, config=True) |
|
216 | othervalue = Int(0, config=True) | |
217 |
|
217 | |||
218 | Now, we can create a configuration file to configure instances of :class:`Foo` |
|
218 | Now, we can create a configuration file to configure instances of :class:`Foo` | |
219 | and :class:`Bar`:: |
|
219 | and :class:`Bar`:: | |
220 |
|
220 | |||
221 | # config file |
|
221 | # config file | |
222 | c = get_config() |
|
222 | c = get_config() | |
223 |
|
223 | |||
224 | c.Foo.name = 'bestname' |
|
224 | c.Foo.name = 'bestname' | |
225 | c.Bar.othervalue = 10 |
|
225 | c.Bar.othervalue = 10 | |
226 |
|
226 | |||
227 | This class hierarchy and configuration file accomplishes the following: |
|
227 | This class hierarchy and configuration file accomplishes the following: | |
228 |
|
228 | |||
229 | * The default value for :attr:`Foo.name` and :attr:`Bar.name` will be |
|
229 | * The default value for :attr:`Foo.name` and :attr:`Bar.name` will be | |
230 | 'bestname'. Because :class:`Bar` is a :class:`Foo` subclass it also |
|
230 | 'bestname'. Because :class:`Bar` is a :class:`Foo` subclass it also | |
231 | picks up the configuration information for :class:`Foo`. |
|
231 | picks up the configuration information for :class:`Foo`. | |
232 | * The default value for :attr:`Foo.value` and :attr:`Bar.value` will be |
|
232 | * The default value for :attr:`Foo.value` and :attr:`Bar.value` will be | |
233 | ``100.0``, which is the value specified as the class default. |
|
233 | ``100.0``, which is the value specified as the class default. | |
234 | * The default value for :attr:`Bar.othervalue` will be 10 as set in the |
|
234 | * The default value for :attr:`Bar.othervalue` will be 10 as set in the | |
235 | configuration file. Because :class:`Foo` is the parent of :class:`Bar` |
|
235 | configuration file. Because :class:`Foo` is the parent of :class:`Bar` | |
236 | it doesn't know anything about the :attr:`othervalue` attribute. |
|
236 | it doesn't know anything about the :attr:`othervalue` attribute. | |
237 |
|
237 | |||
|
238 | ||||
|
239 | .. _ipython_dir: | |||
|
240 | ||||
238 | Configuration file location |
|
241 | Configuration file location | |
239 | =========================== |
|
242 | =========================== | |
240 |
|
243 | |||
241 | So where should you put your configuration files? By default, all IPython |
|
244 | So where should you put your configuration files? By default, all IPython | |
242 | applications look in the so called "IPython directory". The location of |
|
245 | applications look in the so called "IPython directory". The location of | |
243 | this directory is determined by the following algorithm: |
|
246 | this directory is determined by the following algorithm: | |
244 |
|
247 | |||
245 | * If the ``--ipython-dir`` command line flag is given, its value is used. |
|
248 | * If the ``--ipython-dir`` command line flag is given, its value is used. | |
246 |
|
249 | |||
247 | * If not, the value returned by :func:`IPython.utils.path.get_ipython_dir` |
|
250 | * If not, the value returned by :func:`IPython.utils.path.get_ipython_dir` | |
248 | is used. This function will first look at the :envvar:`IPYTHON_DIR` |
|
251 | is used. This function will first look at the :envvar:`IPYTHON_DIR` | |
249 |
environment variable and then default to |
|
252 | environment variable and then default to a platform-specific default. | |
250 | :file:`$HOME/.ipython`. |
|
253 | ||
|
254 | On posix systems (Linux, Unix, etc.), IPython respects the ``$XDG_CONFIG_HOME`` | |||
|
255 | part of the `XDG Base Directory`_ specification. If ``$XDG_CONFIG_HOME`` is | |||
|
256 | defined and exists ( ``XDG_CONFIG_HOME`` has a default interpretation of | |||
|
257 | :file:`$HOME/.config`), then IPython's config directory will be located in | |||
|
258 | :file:`$XDG_CONFIG_HOME/ipython`. If users still have an IPython directory | |||
|
259 | in :file:`$HOME/.ipython`, then that will be used. in preference to the | |||
|
260 | system default. | |||
251 |
|
261 | |||
252 | For most users, the default value will simply be something like |
|
262 | For most users, the default value will simply be something like | |
253 | :file:`$HOME/.ipython`. |
|
263 | :file:`$HOME/.config/ipython` on Linux, or :file:`$HOME/.ipython` | |
|
264 | elsewhere. | |||
254 |
|
265 | |||
255 | Once the location of the IPython directory has been determined, you need to |
|
266 | Once the location of the IPython directory has been determined, you need to | |
256 | know what filename to use for the configuration file. The basic idea is that |
|
267 | know what filename to use for the configuration file. The basic idea is that | |
257 | each application has its own default configuration filename. The default named |
|
268 | each application has its own default configuration filename. The default named | |
258 | used by the :command:`ipython` command line program is |
|
269 | used by the :command:`ipython` command line program is | |
259 | :file:`ipython_config.py`. This value can be overriden by the ``-config_file`` |
|
270 | :file:`ipython_config.py`. This value can be overriden by the ``-config_file`` | |
260 | command line flag. A sample :file:`ipython_config.py` file can be found |
|
271 | command line flag. A sample :file:`ipython_config.py` file can be found | |
261 | in :mod:`IPython.config.default.ipython_config.py`. Simple copy it to your |
|
272 | in :mod:`IPython.config.default.ipython_config.py`. Simple copy it to your | |
262 | IPython directory to begin using it. |
|
273 | IPython directory to begin using it. | |
263 |
|
274 | |||
264 | .. _Profiles: |
|
275 | .. _Profiles: | |
265 |
|
276 | |||
266 | Profiles |
|
277 | Profiles | |
267 | ======== |
|
278 | ======== | |
268 |
|
279 | |||
269 | A profile is simply a configuration file that follows a simple naming |
|
280 | A profile is simply a configuration file that follows a simple naming | |
270 | convention and can be loaded using a simplified syntax. The idea is |
|
281 | convention and can be loaded using a simplified syntax. The idea is | |
271 | that users often want to maintain a set of configuration files for different |
|
282 | that users often want to maintain a set of configuration files for different | |
272 | purposes: one for doing numerical computing with NumPy and SciPy and |
|
283 | purposes: one for doing numerical computing with NumPy and SciPy and | |
273 | another for doing symbolic computing with SymPy. Profiles make it easy |
|
284 | another for doing symbolic computing with SymPy. Profiles make it easy | |
274 | to keep a separate configuration file for each of these purposes. |
|
285 | to keep a separate configuration file for each of these purposes. | |
275 |
|
286 | |||
276 | Let's start by showing how a profile is used: |
|
287 | Let's start by showing how a profile is used: | |
277 |
|
288 | |||
278 | .. code-block:: bash |
|
289 | .. code-block:: bash | |
279 |
|
290 | |||
280 | $ ipython -p sympy |
|
291 | $ ipython -p sympy | |
281 |
|
292 | |||
282 | This tells the :command:`ipython` command line program to get its |
|
293 | This tells the :command:`ipython` command line program to get its | |
283 | configuration from the "sympy" profile. The search path for profiles is the |
|
294 | configuration from the "sympy" profile. The search path for profiles is the | |
284 | same as that of regular configuration files. The only difference is that |
|
295 | same as that of regular configuration files. The only difference is that | |
285 | profiles are named in a special way. In the case above, the "sympy" profile |
|
296 | profiles are named in a special way. In the case above, the "sympy" profile | |
286 | would need to have the name :file:`ipython_config_sympy.py`. |
|
297 | would need to have the name :file:`ipython_config_sympy.py`. | |
287 |
|
298 | |||
288 | The general pattern is this: simply add ``_profilename`` to the end of the |
|
299 | The general pattern is this: simply add ``_profilename`` to the end of the | |
289 | normal configuration file name. Then load the profile by adding ``-p |
|
300 | normal configuration file name. Then load the profile by adding ``-p | |
290 | profilename`` to your command line options. |
|
301 | profilename`` to your command line options. | |
291 |
|
302 | |||
292 | IPython ships with some sample profiles in :mod:`IPython.config.profile`. |
|
303 | IPython ships with some sample profiles in :mod:`IPython.config.profile`. | |
293 | Simply copy these to your IPython directory to begin using them. |
|
304 | Simply copy these to your IPython directory to begin using them. | |
294 |
|
305 | |||
295 | Design requirements |
|
306 | Design requirements | |
296 | =================== |
|
307 | =================== | |
297 |
|
308 | |||
298 | Here are the main requirements we wanted our configuration system to have: |
|
309 | Here are the main requirements we wanted our configuration system to have: | |
299 |
|
310 | |||
300 | * Support for hierarchical configuration information. |
|
311 | * Support for hierarchical configuration information. | |
301 |
|
312 | |||
302 | * Full integration with command line option parsers. Often, you want to read |
|
313 | * Full integration with command line option parsers. Often, you want to read | |
303 | a configuration file, but then override some of the values with command line |
|
314 | a configuration file, but then override some of the values with command line | |
304 | options. Our configuration system automates this process and allows each |
|
315 | options. Our configuration system automates this process and allows each | |
305 | command line option to be linked to a particular attribute in the |
|
316 | command line option to be linked to a particular attribute in the | |
306 | configuration hierarchy that it will override. |
|
317 | configuration hierarchy that it will override. | |
307 |
|
318 | |||
308 | * Configuration files that are themselves valid Python code. This accomplishes |
|
319 | * Configuration files that are themselves valid Python code. This accomplishes | |
309 | many things. First, it becomes possible to put logic in your configuration |
|
320 | many things. First, it becomes possible to put logic in your configuration | |
310 | files that sets attributes based on your operating system, network setup, |
|
321 | files that sets attributes based on your operating system, network setup, | |
311 | Python version, etc. Second, Python has a super simple syntax for accessing |
|
322 | Python version, etc. Second, Python has a super simple syntax for accessing | |
312 | hierarchical data structures, namely regular attribute access |
|
323 | hierarchical data structures, namely regular attribute access | |
313 | (``Foo.Bar.Bam.name``). Third, using Python makes it easy for users to |
|
324 | (``Foo.Bar.Bam.name``). Third, using Python makes it easy for users to | |
314 | import configuration attributes from one configuration file to another. |
|
325 | import configuration attributes from one configuration file to another. | |
315 | Forth, even though Python is dynamically typed, it does have types that can |
|
326 | Forth, even though Python is dynamically typed, it does have types that can | |
316 | be checked at runtime. Thus, a ``1`` in a config file is the integer '1', |
|
327 | be checked at runtime. Thus, a ``1`` in a config file is the integer '1', | |
317 | while a ``'1'`` is a string. |
|
328 | while a ``'1'`` is a string. | |
318 |
|
329 | |||
319 | * A fully automated method for getting the configuration information to the |
|
330 | * A fully automated method for getting the configuration information to the | |
320 | classes that need it at runtime. Writing code that walks a configuration |
|
331 | classes that need it at runtime. Writing code that walks a configuration | |
321 | hierarchy to extract a particular attribute is painful. When you have |
|
332 | hierarchy to extract a particular attribute is painful. When you have | |
322 | complex configuration information with hundreds of attributes, this makes |
|
333 | complex configuration information with hundreds of attributes, this makes | |
323 | you want to cry. |
|
334 | you want to cry. | |
324 |
|
335 | |||
325 | * Type checking and validation that doesn't require the entire configuration |
|
336 | * Type checking and validation that doesn't require the entire configuration | |
326 | hierarchy to be specified statically before runtime. Python is a very |
|
337 | hierarchy to be specified statically before runtime. Python is a very | |
327 | dynamic language and you don't always know everything that needs to be |
|
338 | dynamic language and you don't always know everything that needs to be | |
328 | configured when a program starts. |
|
339 | configured when a program starts. | |
329 |
|
340 | |||
|
341 | ||||
|
342 | .. _`XDG Base Directory`: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html |
@@ -1,167 +1,167 b'' | |||||
1 | .. _documenting-ipython: |
|
1 | .. _documenting-ipython: | |
2 |
|
2 | |||
3 | ===================== |
|
3 | ===================== | |
4 | Documenting IPython |
|
4 | Documenting IPython | |
5 | ===================== |
|
5 | ===================== | |
6 |
|
6 | |||
7 | When contributing code to IPython, you should strive for clarity and |
|
7 | When contributing code to IPython, you should strive for clarity and | |
8 | consistency, without falling prey to a style straitjacket. Basically, |
|
8 | consistency, without falling prey to a style straitjacket. Basically, | |
9 | 'document everything, try to be consistent, do what makes sense.' |
|
9 | 'document everything, try to be consistent, do what makes sense.' | |
10 |
|
10 | |||
11 | By and large we follow existing Python practices in major projects like Python |
|
11 | By and large we follow existing Python practices in major projects like Python | |
12 | itself or NumPy, this document provides some additional detail for IPython. |
|
12 | itself or NumPy, this document provides some additional detail for IPython. | |
13 |
|
13 | |||
14 |
|
14 | |||
15 | Standalone documentation |
|
15 | Standalone documentation | |
16 | ======================== |
|
16 | ======================== | |
17 |
|
17 | |||
18 | All standalone documentation should be written in plain text (``.txt``) files |
|
18 | All standalone documentation should be written in plain text (``.txt``) files | |
19 | using reStructuredText [reStructuredText]_ for markup and formatting. All such |
|
19 | using reStructuredText [reStructuredText]_ for markup and formatting. All such | |
20 | documentation should be placed in the directory :file:`docs/source` of the |
|
20 | documentation should be placed in the directory :file:`docs/source` of the | |
21 | IPython source tree. Or, when appropriate, a suitably named subdirectory |
|
21 | IPython source tree. Or, when appropriate, a suitably named subdirectory | |
22 | should be used. The documentation in this location will serve as the main |
|
22 | should be used. The documentation in this location will serve as the main | |
23 | source for IPython documentation. |
|
23 | source for IPython documentation. | |
24 |
|
24 | |||
25 | The actual HTML and PDF docs are built using the Sphinx [Sphinx]_ |
|
25 | The actual HTML and PDF docs are built using the Sphinx [Sphinx]_ | |
26 | documentation generation tool. Once you have Sphinx installed, you can build |
|
26 | documentation generation tool. Once you have Sphinx installed, you can build | |
27 | the html docs yourself by doing: |
|
27 | the html docs yourself by doing: | |
28 |
|
28 | |||
29 | .. code-block:: bash |
|
29 | .. code-block:: bash | |
30 |
|
30 | |||
31 | $ cd ipython-mybranch/docs |
|
31 | $ cd ipython-mybranch/docs | |
32 | $ make html |
|
32 | $ make html | |
33 |
|
33 | |||
34 | Our usage of Sphinx follows that of matplotlib [Matplotlib]_ closely. We are |
|
34 | Our usage of Sphinx follows that of matplotlib [Matplotlib]_ closely. We are | |
35 | using a number of Sphinx tools and extensions written by the matplotlib team |
|
35 | using a number of Sphinx tools and extensions written by the matplotlib team | |
36 | and will mostly follow their conventions, which are nicely spelled out in |
|
36 | and will mostly follow their conventions, which are nicely spelled out in | |
37 | their documentation guide [MatplotlibDocGuide]_. What follows is thus a |
|
37 | their documentation guide [MatplotlibDocGuide]_. What follows is thus a | |
38 | abridged version of the matplotlib documentation guide, taken with permission |
|
38 | abridged version of the matplotlib documentation guide, taken with permission | |
39 | from the matplotlib team. |
|
39 | from the matplotlib team. | |
40 |
|
40 | |||
41 | If you are reading this in a web browser, you can click on the "Show Source" |
|
41 | If you are reading this in a web browser, you can click on the "Show Source" | |
42 | link to see the original reStricturedText for the following examples. |
|
42 | link to see the original reStricturedText for the following examples. | |
43 |
|
43 | |||
44 | A bit of Python code:: |
|
44 | A bit of Python code:: | |
45 |
|
45 | |||
46 | for i in range(10): |
|
46 | for i in range(10): | |
47 | print i, |
|
47 | print i, | |
48 | print "A big number:",2**34 |
|
48 | print "A big number:",2**34 | |
49 |
|
49 | |||
50 | An interactive Python session:: |
|
50 | An interactive Python session:: | |
51 |
|
51 | |||
52 | >>> from IPython.utils.path import get_ipython_dir |
|
52 | >>> from IPython.utils.path import get_ipython_dir | |
53 | >>> get_ipython_dir() |
|
53 | >>> get_ipython_dir() | |
54 | '/home/fperez/.ipython' |
|
54 | '/home/fperez/.config/ipython' | |
55 |
|
55 | |||
56 | An IPython session: |
|
56 | An IPython session: | |
57 |
|
57 | |||
58 | .. code-block:: ipython |
|
58 | .. code-block:: ipython | |
59 |
|
59 | |||
60 | In [7]: import IPython |
|
60 | In [7]: import IPython | |
61 |
|
61 | |||
62 | In [8]: print "This IPython is version:",IPython.__version__ |
|
62 | In [8]: print "This IPython is version:",IPython.__version__ | |
63 | This IPython is version: 0.9.1 |
|
63 | This IPython is version: 0.9.1 | |
64 |
|
64 | |||
65 | In [9]: 2+4 |
|
65 | In [9]: 2+4 | |
66 | Out[9]: 6 |
|
66 | Out[9]: 6 | |
67 |
|
67 | |||
68 |
|
68 | |||
69 | A bit of shell code: |
|
69 | A bit of shell code: | |
70 |
|
70 | |||
71 | .. code-block:: bash |
|
71 | .. code-block:: bash | |
72 |
|
72 | |||
73 | cd /tmp |
|
73 | cd /tmp | |
74 | echo "My home directory is: $HOME" |
|
74 | echo "My home directory is: $HOME" | |
75 | ls |
|
75 | ls | |
76 |
|
76 | |||
77 | Docstring format |
|
77 | Docstring format | |
78 | ================ |
|
78 | ================ | |
79 |
|
79 | |||
80 | Good docstrings are very important. Unfortunately, Python itself only provides |
|
80 | Good docstrings are very important. Unfortunately, Python itself only provides | |
81 | a rather loose standard for docstrings [PEP257]_, and there is no universally |
|
81 | a rather loose standard for docstrings [PEP257]_, and there is no universally | |
82 | accepted convention for all the different parts of a complete docstring. |
|
82 | accepted convention for all the different parts of a complete docstring. | |
83 | However, the NumPy project has established a very reasonable standard, and has |
|
83 | However, the NumPy project has established a very reasonable standard, and has | |
84 | developed some tools to support the smooth inclusion of such docstrings in |
|
84 | developed some tools to support the smooth inclusion of such docstrings in | |
85 | Sphinx-generated manuals. Rather than inventing yet another pseudo-standard, |
|
85 | Sphinx-generated manuals. Rather than inventing yet another pseudo-standard, | |
86 | IPython will be henceforth documented using the NumPy conventions; we carry |
|
86 | IPython will be henceforth documented using the NumPy conventions; we carry | |
87 | copies of some of the NumPy support tools to remain self-contained, but share |
|
87 | copies of some of the NumPy support tools to remain self-contained, but share | |
88 | back upstream with NumPy any improvements or fixes we may make to the tools. |
|
88 | back upstream with NumPy any improvements or fixes we may make to the tools. | |
89 |
|
89 | |||
90 | The NumPy documentation guidelines [NumPyDocGuide]_ contain detailed |
|
90 | The NumPy documentation guidelines [NumPyDocGuide]_ contain detailed | |
91 | information on this standard, and for a quick overview, the NumPy example |
|
91 | information on this standard, and for a quick overview, the NumPy example | |
92 | docstring [NumPyExampleDocstring]_ is a useful read. |
|
92 | docstring [NumPyExampleDocstring]_ is a useful read. | |
93 |
|
93 | |||
94 |
|
94 | |||
95 | For user-facing APIs, we try to be fairly strict about following the above |
|
95 | For user-facing APIs, we try to be fairly strict about following the above | |
96 | standards (even though they mean more verbose and detailed docstrings). |
|
96 | standards (even though they mean more verbose and detailed docstrings). | |
97 | Wherever you can reasonably expect people to do introspection with:: |
|
97 | Wherever you can reasonably expect people to do introspection with:: | |
98 |
|
98 | |||
99 | In [1]: some_function? |
|
99 | In [1]: some_function? | |
100 |
|
100 | |||
101 | the docstring should follow the NumPy style and be fairly detailed. |
|
101 | the docstring should follow the NumPy style and be fairly detailed. | |
102 |
|
102 | |||
103 | For purely internal methods that are only likely to be read by others extending |
|
103 | For purely internal methods that are only likely to be read by others extending | |
104 | IPython itself we are a bit more relaxed, especially for small/short methods |
|
104 | IPython itself we are a bit more relaxed, especially for small/short methods | |
105 | and functions whose intent is reasonably obvious. We still expect docstrings |
|
105 | and functions whose intent is reasonably obvious. We still expect docstrings | |
106 | to be written, but they can be simpler. For very short functions with a |
|
106 | to be written, but they can be simpler. For very short functions with a | |
107 | single-line docstring you can use something like:: |
|
107 | single-line docstring you can use something like:: | |
108 |
|
108 | |||
109 | def add(a, b): |
|
109 | def add(a, b): | |
110 | """The sum of two numbers. |
|
110 | """The sum of two numbers. | |
111 | """ |
|
111 | """ | |
112 | code |
|
112 | code | |
113 |
|
113 | |||
114 | and for longer multiline strings:: |
|
114 | and for longer multiline strings:: | |
115 |
|
115 | |||
116 | def add(a, b): |
|
116 | def add(a, b): | |
117 | """The sum of two numbers. |
|
117 | """The sum of two numbers. | |
118 |
|
118 | |||
119 | Here is the rest of the docs. |
|
119 | Here is the rest of the docs. | |
120 | """ |
|
120 | """ | |
121 | code |
|
121 | code | |
122 |
|
122 | |||
123 |
|
123 | |||
124 | Here are two additional PEPs of interest regarding documentation of code. |
|
124 | Here are two additional PEPs of interest regarding documentation of code. | |
125 | While both of these were rejected, the ideas therein form much of the basis of |
|
125 | While both of these were rejected, the ideas therein form much of the basis of | |
126 | docutils (the machinery to process reStructuredText): |
|
126 | docutils (the machinery to process reStructuredText): | |
127 |
|
127 | |||
128 | * `Docstring Processing System Framework <http://www.python.org/peps/pep-0256.html>`_ |
|
128 | * `Docstring Processing System Framework <http://www.python.org/peps/pep-0256.html>`_ | |
129 | * `Docutils Design Specification <http://www.python.org/peps/pep-0258.html>`_ |
|
129 | * `Docutils Design Specification <http://www.python.org/peps/pep-0258.html>`_ | |
130 |
|
130 | |||
131 | .. note:: |
|
131 | .. note:: | |
132 |
|
132 | |||
133 | In the past IPython used epydoc so currently many docstrings still use |
|
133 | In the past IPython used epydoc so currently many docstrings still use | |
134 | epydoc conventions. We will update them as we go, but all new code should |
|
134 | epydoc conventions. We will update them as we go, but all new code should | |
135 | be documented using the NumPy standard. |
|
135 | be documented using the NumPy standard. | |
136 |
|
136 | |||
137 | Building and uploading |
|
137 | Building and uploading | |
138 | ====================== |
|
138 | ====================== | |
139 | The built docs are stored in a separate repository. Through some github magic, |
|
139 | The built docs are stored in a separate repository. Through some github magic, | |
140 | they're automatically exposed as a website. It works like this: |
|
140 | they're automatically exposed as a website. It works like this: | |
141 |
|
141 | |||
142 | * You will need to have sphinx and latex installed. In Ubuntu, install |
|
142 | * You will need to have sphinx and latex installed. In Ubuntu, install | |
143 | ``texlive-latex-recommended texlive-latex-extra texlive-fonts-recommended``. |
|
143 | ``texlive-latex-recommended texlive-latex-extra texlive-fonts-recommended``. | |
144 | Install the latest version of sphinx from PyPI (``pip install sphinx``). |
|
144 | Install the latest version of sphinx from PyPI (``pip install sphinx``). | |
145 | * Ensure that the development version of IPython is the first in your system |
|
145 | * Ensure that the development version of IPython is the first in your system | |
146 | path. You can either use a virtualenv, or modify your PYTHONPATH. |
|
146 | path. You can either use a virtualenv, or modify your PYTHONPATH. | |
147 | * Switch into the docs directory, and run ``make gh-pages``. This will build |
|
147 | * Switch into the docs directory, and run ``make gh-pages``. This will build | |
148 | your updated docs as html and pdf, then automatically check out the latest |
|
148 | your updated docs as html and pdf, then automatically check out the latest | |
149 | version of the docs repository, copy the built docs into it, and commit your |
|
149 | version of the docs repository, copy the built docs into it, and commit your | |
150 | changes. |
|
150 | changes. | |
151 | * Open the built docs in a web browser, and check that they're as expected. |
|
151 | * Open the built docs in a web browser, and check that they're as expected. | |
152 | * (When building the docs for a new tagged release, you will have to add its link to |
|
152 | * (When building the docs for a new tagged release, you will have to add its link to | |
153 | index.rst, then run ``python build_index.py`` to update index.html. Commit the |
|
153 | index.rst, then run ``python build_index.py`` to update index.html. Commit the | |
154 | change.) |
|
154 | change.) | |
155 | * Upload the docs with ``git push``. This only works if you have write access to |
|
155 | * Upload the docs with ``git push``. This only works if you have write access to | |
156 | the docs repository. |
|
156 | the docs repository. | |
157 | * If you are building a version that is not the current dev branch, nor a tagged release, |
|
157 | * If you are building a version that is not the current dev branch, nor a tagged release, | |
158 | then you must run gh-pages.py directly with ``python gh-pages.py <version>``, and *not* |
|
158 | then you must run gh-pages.py directly with ``python gh-pages.py <version>``, and *not* | |
159 | with ``make gh-pages``. |
|
159 | with ``make gh-pages``. | |
160 |
|
160 | |||
161 | .. [reStructuredText] reStructuredText. http://docutils.sourceforge.net/rst.html |
|
161 | .. [reStructuredText] reStructuredText. http://docutils.sourceforge.net/rst.html | |
162 | .. [Sphinx] Sphinx. http://sphinx.pocoo.org/ |
|
162 | .. [Sphinx] Sphinx. http://sphinx.pocoo.org/ | |
163 | .. [MatplotlibDocGuide] http://matplotlib.sourceforge.net/devel/documenting_mpl.html |
|
163 | .. [MatplotlibDocGuide] http://matplotlib.sourceforge.net/devel/documenting_mpl.html | |
164 | .. [PEP257] PEP 257. http://www.python.org/peps/pep-0257.html |
|
164 | .. [PEP257] PEP 257. http://www.python.org/peps/pep-0257.html | |
165 | .. [NumPyDocGuide] NumPy documentation guide. http://projects.scipy.org/numpy/wiki/CodingStyleGuidelines |
|
165 | .. [NumPyDocGuide] NumPy documentation guide. http://projects.scipy.org/numpy/wiki/CodingStyleGuidelines | |
166 | .. [NumPyExampleDocstring] NumPy example docstring. http://projects.scipy.org/numpy/browser/trunk/doc/EXAMPLE_DOCSTRING.txt |
|
166 | .. [NumPyExampleDocstring] NumPy example docstring. http://projects.scipy.org/numpy/browser/trunk/doc/EXAMPLE_DOCSTRING.txt | |
167 |
|
167 |
@@ -1,1577 +1,1578 b'' | |||||
1 | ================= |
|
1 | ================= | |
2 | IPython reference |
|
2 | IPython reference | |
3 | ================= |
|
3 | ================= | |
4 |
|
4 | |||
5 | .. warning:: |
|
5 | .. warning:: | |
6 |
|
6 | |||
7 | As of the 0.11 version of IPython, some of the features and APIs |
|
7 | As of the 0.11 version of IPython, some of the features and APIs | |
8 | described in this section have been deprecated or are broken. Our plan |
|
8 | described in this section have been deprecated or are broken. Our plan | |
9 | is to continue to support these features, but they need to be updated |
|
9 | is to continue to support these features, but they need to be updated | |
10 | to take advantage of recent API changes. Furthermore, this section |
|
10 | to take advantage of recent API changes. Furthermore, this section | |
11 | of the documentation need to be updated to reflect all of these changes. |
|
11 | of the documentation need to be updated to reflect all of these changes. | |
12 |
|
12 | |||
13 | .. _command_line_options: |
|
13 | .. _command_line_options: | |
14 |
|
14 | |||
15 | Command-line usage |
|
15 | Command-line usage | |
16 | ================== |
|
16 | ================== | |
17 |
|
17 | |||
18 | You start IPython with the command:: |
|
18 | You start IPython with the command:: | |
19 |
|
19 | |||
20 | $ ipython [options] files |
|
20 | $ ipython [options] files | |
21 |
|
21 | |||
22 | If invoked with no options, it executes all the files listed in sequence |
|
22 | If invoked with no options, it executes all the files listed in sequence | |
23 | and drops you into the interpreter while still acknowledging any options |
|
23 | and drops you into the interpreter while still acknowledging any options | |
24 | you may have set in your ipythonrc file. This behavior is different from |
|
24 | you may have set in your ipythonrc file. This behavior is different from | |
25 | standard Python, which when called as python -i will only execute one |
|
25 | standard Python, which when called as python -i will only execute one | |
26 | file and ignore your configuration setup. |
|
26 | file and ignore your configuration setup. | |
27 |
|
27 | |||
28 | Please note that some of the configuration options are not available at |
|
28 | Please note that some of the configuration options are not available at | |
29 | the command line, simply because they are not practical here. Look into |
|
29 | the command line, simply because they are not practical here. Look into | |
30 | your ipythonrc configuration file for details on those. This file |
|
30 | your ipythonrc configuration file for details on those. This file is typically | |
31 |
|
|
31 | installed in the IPYTHON_DIR directory. For Linux | |
32 | $HOME resolves to C:\\Documents and Settings\\YourUserName in most |
|
32 | users, this will be $HOME/.config/ipython, and for other users it will be | |
33 | instances. In the rest of this text, we will refer to this directory as |
|
33 | $HOME/.ipython. For Windows users, $HOME resolves to C:\\Documents and | |
34 | IPYTHON_DIR. |
|
34 | Settings\\YourUserName in most instances. | |
|
35 | ||||
35 |
|
36 | |||
36 |
|
37 | |||
37 |
|
38 | |||
38 | Special Threading Options |
|
39 | Special Threading Options | |
39 | ------------------------- |
|
40 | ------------------------- | |
40 |
|
41 | |||
41 | Previously IPython had command line options for controlling GUI event loop |
|
42 | Previously IPython had command line options for controlling GUI event loop | |
42 | integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython |
|
43 | integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython | |
43 | version 0.11, these have been deprecated. Please see the new ``%gui`` |
|
44 | version 0.11, these have been deprecated. Please see the new ``%gui`` | |
44 | magic command or :ref:`this section <gui_support>` for details on the new |
|
45 | magic command or :ref:`this section <gui_support>` for details on the new | |
45 | interface. |
|
46 | interface. | |
46 |
|
47 | |||
47 | Regular Options |
|
48 | Regular Options | |
48 | --------------- |
|
49 | --------------- | |
49 |
|
50 | |||
50 | After the above threading options have been given, regular options can |
|
51 | After the above threading options have been given, regular options can | |
51 | follow in any order. All options can be abbreviated to their shortest |
|
52 | follow in any order. All options can be abbreviated to their shortest | |
52 | non-ambiguous form and are case-sensitive. One or two dashes can be |
|
53 | non-ambiguous form and are case-sensitive. One or two dashes can be | |
53 | used. Some options have an alternate short form, indicated after a ``|``. |
|
54 | used. Some options have an alternate short form, indicated after a ``|``. | |
54 |
|
55 | |||
55 | Most options can also be set from your ipythonrc configuration file. See |
|
56 | Most options can also be set from your ipythonrc configuration file. See | |
56 | the provided example for more details on what the options do. Options |
|
57 | the provided example for more details on what the options do. Options | |
57 | given at the command line override the values set in the ipythonrc file. |
|
58 | given at the command line override the values set in the ipythonrc file. | |
58 |
|
59 | |||
59 | All options with a [no] prepended can be specified in negated form |
|
60 | All options with a [no] prepended can be specified in negated form | |
60 | (-nooption instead of -option) to turn the feature off. |
|
61 | (-nooption instead of -option) to turn the feature off. | |
61 |
|
62 | |||
62 | -help print a help message and exit. |
|
63 | -help print a help message and exit. | |
63 |
|
64 | |||
64 | -pylab |
|
65 | -pylab | |
65 | Deprecated. See :ref:`Matplotlib support <matplotlib_support>` |
|
66 | Deprecated. See :ref:`Matplotlib support <matplotlib_support>` | |
66 | for more details. |
|
67 | for more details. | |
67 |
|
68 | |||
68 | -autocall <val> |
|
69 | -autocall <val> | |
69 | Make IPython automatically call any callable object even if you |
|
70 | Make IPython automatically call any callable object even if you | |
70 | didn't type explicit parentheses. For example, 'str 43' becomes |
|
71 | didn't type explicit parentheses. For example, 'str 43' becomes | |
71 | 'str(43)' automatically. The value can be '0' to disable the feature, |
|
72 | 'str(43)' automatically. The value can be '0' to disable the feature, | |
72 | '1' for smart autocall, where it is not applied if there are no more |
|
73 | '1' for smart autocall, where it is not applied if there are no more | |
73 | arguments on the line, and '2' for full autocall, where all callable |
|
74 | arguments on the line, and '2' for full autocall, where all callable | |
74 | objects are automatically called (even if no arguments are |
|
75 | objects are automatically called (even if no arguments are | |
75 | present). The default is '1'. |
|
76 | present). The default is '1'. | |
76 |
|
77 | |||
77 | -[no]autoindent |
|
78 | -[no]autoindent | |
78 | Turn automatic indentation on/off. |
|
79 | Turn automatic indentation on/off. | |
79 |
|
80 | |||
80 | -[no]automagic |
|
81 | -[no]automagic | |
81 | make magic commands automatic (without needing their first character |
|
82 | make magic commands automatic (without needing their first character | |
82 | to be %). Type %magic at the IPython prompt for more information. |
|
83 | to be %). Type %magic at the IPython prompt for more information. | |
83 |
|
84 | |||
84 | -[no]autoedit_syntax |
|
85 | -[no]autoedit_syntax | |
85 | When a syntax error occurs after editing a file, automatically |
|
86 | When a syntax error occurs after editing a file, automatically | |
86 | open the file to the trouble causing line for convenient |
|
87 | open the file to the trouble causing line for convenient | |
87 | fixing. |
|
88 | fixing. | |
88 |
|
89 | |||
89 | -[no]banner Print the initial information banner (default on). |
|
90 | -[no]banner Print the initial information banner (default on). | |
90 |
|
91 | |||
91 | -c <command> |
|
92 | -c <command> | |
92 | execute the given command string. This is similar to the -c |
|
93 | execute the given command string. This is similar to the -c | |
93 | option in the normal Python interpreter. |
|
94 | option in the normal Python interpreter. | |
94 |
|
95 | |||
95 | -cache_size, cs <n> |
|
96 | -cache_size, cs <n> | |
96 | size of the output cache (maximum number of entries to hold in |
|
97 | size of the output cache (maximum number of entries to hold in | |
97 | memory). The default is 1000, you can change it permanently in your |
|
98 | memory). The default is 1000, you can change it permanently in your | |
98 | config file. Setting it to 0 completely disables the caching system, |
|
99 | config file. Setting it to 0 completely disables the caching system, | |
99 | and the minimum value accepted is 20 (if you provide a value less than |
|
100 | and the minimum value accepted is 20 (if you provide a value less than | |
100 | 20, it is reset to 0 and a warning is issued) This limit is defined |
|
101 | 20, it is reset to 0 and a warning is issued) This limit is defined | |
101 | because otherwise you'll spend more time re-flushing a too small cache |
|
102 | because otherwise you'll spend more time re-flushing a too small cache | |
102 | than working. |
|
103 | than working. | |
103 |
|
104 | |||
104 | -classic, cl |
|
105 | -classic, cl | |
105 | Gives IPython a similar feel to the classic Python |
|
106 | Gives IPython a similar feel to the classic Python | |
106 | prompt. |
|
107 | prompt. | |
107 |
|
108 | |||
108 | -colors <scheme> |
|
109 | -colors <scheme> | |
109 | Color scheme for prompts and exception reporting. Currently |
|
110 | Color scheme for prompts and exception reporting. Currently | |
110 | implemented: NoColor, Linux and LightBG. |
|
111 | implemented: NoColor, Linux and LightBG. | |
111 |
|
112 | |||
112 | -[no]color_info |
|
113 | -[no]color_info | |
113 | IPython can display information about objects via a set of functions, |
|
114 | IPython can display information about objects via a set of functions, | |
114 | and optionally can use colors for this, syntax highlighting source |
|
115 | and optionally can use colors for this, syntax highlighting source | |
115 | code and various other elements. However, because this information is |
|
116 | code and various other elements. However, because this information is | |
116 | passed through a pager (like 'less') and many pagers get confused with |
|
117 | passed through a pager (like 'less') and many pagers get confused with | |
117 | color codes, this option is off by default. You can test it and turn |
|
118 | color codes, this option is off by default. You can test it and turn | |
118 | it on permanently in your ipythonrc file if it works for you. As a |
|
119 | it on permanently in your ipythonrc file if it works for you. As a | |
119 | reference, the 'less' pager supplied with Mandrake 8.2 works ok, but |
|
120 | reference, the 'less' pager supplied with Mandrake 8.2 works ok, but | |
120 | that in RedHat 7.2 doesn't. |
|
121 | that in RedHat 7.2 doesn't. | |
121 |
|
122 | |||
122 | Test it and turn it on permanently if it works with your |
|
123 | Test it and turn it on permanently if it works with your | |
123 | system. The magic function %color_info allows you to toggle this |
|
124 | system. The magic function %color_info allows you to toggle this | |
124 | interactively for testing. |
|
125 | interactively for testing. | |
125 |
|
126 | |||
126 | -[no]debug |
|
127 | -[no]debug | |
127 | Show information about the loading process. Very useful to pin down |
|
128 | Show information about the loading process. Very useful to pin down | |
128 | problems with your configuration files or to get details about |
|
129 | problems with your configuration files or to get details about | |
129 | session restores. |
|
130 | session restores. | |
130 |
|
131 | |||
131 | -[no]deep_reload: |
|
132 | -[no]deep_reload: | |
132 | IPython can use the deep_reload module which reloads changes in |
|
133 | IPython can use the deep_reload module which reloads changes in | |
133 | modules recursively (it replaces the reload() function, so you don't |
|
134 | modules recursively (it replaces the reload() function, so you don't | |
134 | need to change anything to use it). deep_reload() forces a full |
|
135 | need to change anything to use it). deep_reload() forces a full | |
135 | reload of modules whose code may have changed, which the default |
|
136 | reload of modules whose code may have changed, which the default | |
136 | reload() function does not. |
|
137 | reload() function does not. | |
137 |
|
138 | |||
138 | When deep_reload is off, IPython will use the normal reload(), |
|
139 | When deep_reload is off, IPython will use the normal reload(), | |
139 | but deep_reload will still be available as dreload(). This |
|
140 | but deep_reload will still be available as dreload(). This | |
140 | feature is off by default [which means that you have both |
|
141 | feature is off by default [which means that you have both | |
141 | normal reload() and dreload()]. |
|
142 | normal reload() and dreload()]. | |
142 |
|
143 | |||
143 | -editor <name> |
|
144 | -editor <name> | |
144 | Which editor to use with the %edit command. By default, |
|
145 | Which editor to use with the %edit command. By default, | |
145 | IPython will honor your EDITOR environment variable (if not |
|
146 | IPython will honor your EDITOR environment variable (if not | |
146 | set, vi is the Unix default and notepad the Windows one). |
|
147 | set, vi is the Unix default and notepad the Windows one). | |
147 | Since this editor is invoked on the fly by IPython and is |
|
148 | Since this editor is invoked on the fly by IPython and is | |
148 | meant for editing small code snippets, you may want to use a |
|
149 | meant for editing small code snippets, you may want to use a | |
149 | small, lightweight editor here (in case your default EDITOR is |
|
150 | small, lightweight editor here (in case your default EDITOR is | |
150 | something like Emacs). |
|
151 | something like Emacs). | |
151 |
|
152 | |||
152 | -ipythondir <name> |
|
153 | -ipythondir <name> | |
153 | name of your IPython configuration directory IPYTHON_DIR. This |
|
154 | name of your IPython configuration directory IPYTHON_DIR. This | |
154 | can also be specified through the environment variable |
|
155 | can also be specified through the environment variable | |
155 | IPYTHON_DIR. |
|
156 | IPYTHON_DIR. | |
156 |
|
157 | |||
157 | -log, l |
|
158 | -log, l | |
158 | generate a log file of all input. The file is named |
|
159 | generate a log file of all input. The file is named | |
159 | ipython_log.py in your current directory (which prevents logs |
|
160 | ipython_log.py in your current directory (which prevents logs | |
160 | from multiple IPython sessions from trampling each other). You |
|
161 | from multiple IPython sessions from trampling each other). You | |
161 | can use this to later restore a session by loading your |
|
162 | can use this to later restore a session by loading your | |
162 | logfile as a file to be executed with option -logplay (see |
|
163 | logfile as a file to be executed with option -logplay (see | |
163 | below). |
|
164 | below). | |
164 |
|
165 | |||
165 | -logfile, lf <name> specify the name of your logfile. |
|
166 | -logfile, lf <name> specify the name of your logfile. | |
166 |
|
167 | |||
167 | -logplay, lp <name> |
|
168 | -logplay, lp <name> | |
168 |
|
169 | |||
169 | you can replay a previous log. For restoring a session as close as |
|
170 | you can replay a previous log. For restoring a session as close as | |
170 | possible to the state you left it in, use this option (don't just run |
|
171 | possible to the state you left it in, use this option (don't just run | |
171 | the logfile). With -logplay, IPython will try to reconstruct the |
|
172 | the logfile). With -logplay, IPython will try to reconstruct the | |
172 | previous working environment in full, not just execute the commands in |
|
173 | previous working environment in full, not just execute the commands in | |
173 | the logfile. |
|
174 | the logfile. | |
174 |
|
175 | |||
175 | When a session is restored, logging is automatically turned on |
|
176 | When a session is restored, logging is automatically turned on | |
176 | again with the name of the logfile it was invoked with (it is |
|
177 | again with the name of the logfile it was invoked with (it is | |
177 | read from the log header). So once you've turned logging on for |
|
178 | read from the log header). So once you've turned logging on for | |
178 | a session, you can quit IPython and reload it as many times as |
|
179 | a session, you can quit IPython and reload it as many times as | |
179 | you want and it will continue to log its history and restore |
|
180 | you want and it will continue to log its history and restore | |
180 | from the beginning every time. |
|
181 | from the beginning every time. | |
181 |
|
182 | |||
182 | Caveats: there are limitations in this option. The history |
|
183 | Caveats: there are limitations in this option. The history | |
183 | variables _i*,_* and _dh don't get restored properly. In the |
|
184 | variables _i*,_* and _dh don't get restored properly. In the | |
184 | future we will try to implement full session saving by writing |
|
185 | future we will try to implement full session saving by writing | |
185 | and retrieving a 'snapshot' of the memory state of IPython. But |
|
186 | and retrieving a 'snapshot' of the memory state of IPython. But | |
186 | our first attempts failed because of inherent limitations of |
|
187 | our first attempts failed because of inherent limitations of | |
187 | Python's Pickle module, so this may have to wait. |
|
188 | Python's Pickle module, so this may have to wait. | |
188 |
|
189 | |||
189 | -[no]messages |
|
190 | -[no]messages | |
190 | Print messages which IPython collects about its startup |
|
191 | Print messages which IPython collects about its startup | |
191 | process (default on). |
|
192 | process (default on). | |
192 |
|
193 | |||
193 | -[no]pdb |
|
194 | -[no]pdb | |
194 | Automatically call the pdb debugger after every uncaught |
|
195 | Automatically call the pdb debugger after every uncaught | |
195 | exception. If you are used to debugging using pdb, this puts |
|
196 | exception. If you are used to debugging using pdb, this puts | |
196 | you automatically inside of it after any call (either in |
|
197 | you automatically inside of it after any call (either in | |
197 | IPython or in code called by it) which triggers an exception |
|
198 | IPython or in code called by it) which triggers an exception | |
198 | which goes uncaught. |
|
199 | which goes uncaught. | |
199 |
|
200 | |||
200 | -pydb |
|
201 | -pydb | |
201 | Makes IPython use the third party "pydb" package as debugger, |
|
202 | Makes IPython use the third party "pydb" package as debugger, | |
202 | instead of pdb. Requires that pydb is installed. |
|
203 | instead of pdb. Requires that pydb is installed. | |
203 |
|
204 | |||
204 | -[no]pprint |
|
205 | -[no]pprint | |
205 | ipython can optionally use the pprint (pretty printer) module |
|
206 | ipython can optionally use the pprint (pretty printer) module | |
206 | for displaying results. pprint tends to give a nicer display |
|
207 | for displaying results. pprint tends to give a nicer display | |
207 | of nested data structures. If you like it, you can turn it on |
|
208 | of nested data structures. If you like it, you can turn it on | |
208 | permanently in your config file (default off). |
|
209 | permanently in your config file (default off). | |
209 |
|
210 | |||
210 | -profile, p <name> |
|
211 | -profile, p <name> | |
211 |
|
212 | |||
212 | assume that your config file is ipythonrc-<name> or |
|
213 | assume that your config file is ipythonrc-<name> or | |
213 | ipy_profile_<name>.py (looks in current dir first, then in |
|
214 | ipy_profile_<name>.py (looks in current dir first, then in | |
214 | IPYTHON_DIR). This is a quick way to keep and load multiple |
|
215 | IPYTHON_DIR). This is a quick way to keep and load multiple | |
215 | config files for different tasks, especially if you use the |
|
216 | config files for different tasks, especially if you use the | |
216 | include option of config files. You can keep a basic |
|
217 | include option of config files. You can keep a basic | |
217 | IPYTHON_DIR/ipythonrc file and then have other 'profiles' which |
|
218 | IPYTHON_DIR/ipythonrc file and then have other 'profiles' which | |
218 | include this one and load extra things for particular |
|
219 | include this one and load extra things for particular | |
219 | tasks. For example: |
|
220 | tasks. For example: | |
220 |
|
221 | |||
221 |
1. $ |
|
222 | 1. $IPYTHON_DIR/ipythonrc : load basic things you always want. | |
222 |
2. $ |
|
223 | 2. $IPYTHON_DIR/ipythonrc-math : load (1) and basic math-related modules. | |
223 |
3. $ |
|
224 | 3. $IPYTHON_DIR/ipythonrc-numeric : load (1) and Numeric and plotting modules. | |
224 |
|
225 | |||
225 | Since it is possible to create an endless loop by having |
|
226 | Since it is possible to create an endless loop by having | |
226 | circular file inclusions, IPython will stop if it reaches 15 |
|
227 | circular file inclusions, IPython will stop if it reaches 15 | |
227 | recursive inclusions. |
|
228 | recursive inclusions. | |
228 |
|
229 | |||
229 | -prompt_in1, pi1 <string> |
|
230 | -prompt_in1, pi1 <string> | |
230 |
|
231 | |||
231 | Specify the string used for input prompts. Note that if you are using |
|
232 | Specify the string used for input prompts. Note that if you are using | |
232 | numbered prompts, the number is represented with a '\#' in the |
|
233 | numbered prompts, the number is represented with a '\#' in the | |
233 | string. Don't forget to quote strings with spaces embedded in |
|
234 | string. Don't forget to quote strings with spaces embedded in | |
234 | them. Default: 'In [\#]:'. The :ref:`prompts section <prompts>` |
|
235 | them. Default: 'In [\#]:'. The :ref:`prompts section <prompts>` | |
235 | discusses in detail all the available escapes to customize your |
|
236 | discusses in detail all the available escapes to customize your | |
236 | prompts. |
|
237 | prompts. | |
237 |
|
238 | |||
238 | -prompt_in2, pi2 <string> |
|
239 | -prompt_in2, pi2 <string> | |
239 | Similar to the previous option, but used for the continuation |
|
240 | Similar to the previous option, but used for the continuation | |
240 | prompts. The special sequence '\D' is similar to '\#', but |
|
241 | prompts. The special sequence '\D' is similar to '\#', but | |
241 | with all digits replaced dots (so you can have your |
|
242 | with all digits replaced dots (so you can have your | |
242 | continuation prompt aligned with your input prompt). Default: |
|
243 | continuation prompt aligned with your input prompt). Default: | |
243 | ' .\D.:' (note three spaces at the start for alignment with |
|
244 | ' .\D.:' (note three spaces at the start for alignment with | |
244 | 'In [\#]'). |
|
245 | 'In [\#]'). | |
245 |
|
246 | |||
246 | -prompt_out,po <string> |
|
247 | -prompt_out,po <string> | |
247 | String used for output prompts, also uses numbers like |
|
248 | String used for output prompts, also uses numbers like | |
248 | prompt_in1. Default: 'Out[\#]:' |
|
249 | prompt_in1. Default: 'Out[\#]:' | |
249 |
|
250 | |||
250 | -quick start in bare bones mode (no config file loaded). |
|
251 | -quick start in bare bones mode (no config file loaded). | |
251 |
|
252 | |||
252 | -rcfile <name> |
|
253 | -rcfile <name> | |
253 | name of your IPython resource configuration file. Normally |
|
254 | name of your IPython resource configuration file. Normally | |
254 | IPython loads ipythonrc (from current directory) or |
|
255 | IPython loads ipythonrc (from current directory) or | |
255 | IPYTHON_DIR/ipythonrc. |
|
256 | IPYTHON_DIR/ipythonrc. | |
256 |
|
257 | |||
257 | If the loading of your config file fails, IPython starts with |
|
258 | If the loading of your config file fails, IPython starts with | |
258 | a bare bones configuration (no modules loaded at all). |
|
259 | a bare bones configuration (no modules loaded at all). | |
259 |
|
260 | |||
260 | -[no]readline |
|
261 | -[no]readline | |
261 | use the readline library, which is needed to support name |
|
262 | use the readline library, which is needed to support name | |
262 | completion and command history, among other things. It is |
|
263 | completion and command history, among other things. It is | |
263 | enabled by default, but may cause problems for users of |
|
264 | enabled by default, but may cause problems for users of | |
264 | X/Emacs in Python comint or shell buffers. |
|
265 | X/Emacs in Python comint or shell buffers. | |
265 |
|
266 | |||
266 | Note that X/Emacs 'eterm' buffers (opened with M-x term) support |
|
267 | Note that X/Emacs 'eterm' buffers (opened with M-x term) support | |
267 | IPython's readline and syntax coloring fine, only 'emacs' (M-x |
|
268 | IPython's readline and syntax coloring fine, only 'emacs' (M-x | |
268 | shell and C-c !) buffers do not. |
|
269 | shell and C-c !) buffers do not. | |
269 |
|
270 | |||
270 | -screen_length, sl <n> |
|
271 | -screen_length, sl <n> | |
271 | number of lines of your screen. This is used to control |
|
272 | number of lines of your screen. This is used to control | |
272 | printing of very long strings. Strings longer than this number |
|
273 | printing of very long strings. Strings longer than this number | |
273 | of lines will be sent through a pager instead of directly |
|
274 | of lines will be sent through a pager instead of directly | |
274 | printed. |
|
275 | printed. | |
275 |
|
276 | |||
276 | The default value for this is 0, which means IPython will |
|
277 | The default value for this is 0, which means IPython will | |
277 | auto-detect your screen size every time it needs to print certain |
|
278 | auto-detect your screen size every time it needs to print certain | |
278 | potentially long strings (this doesn't change the behavior of the |
|
279 | potentially long strings (this doesn't change the behavior of the | |
279 | 'print' keyword, it's only triggered internally). If for some |
|
280 | 'print' keyword, it's only triggered internally). If for some | |
280 | reason this isn't working well (it needs curses support), specify |
|
281 | reason this isn't working well (it needs curses support), specify | |
281 | it yourself. Otherwise don't change the default. |
|
282 | it yourself. Otherwise don't change the default. | |
282 |
|
283 | |||
283 | -separate_in, si <string> |
|
284 | -separate_in, si <string> | |
284 |
|
285 | |||
285 | separator before input prompts. |
|
286 | separator before input prompts. | |
286 | Default: '\n' |
|
287 | Default: '\n' | |
287 |
|
288 | |||
288 | -separate_out, so <string> |
|
289 | -separate_out, so <string> | |
289 | separator before output prompts. |
|
290 | separator before output prompts. | |
290 | Default: nothing. |
|
291 | Default: nothing. | |
291 |
|
292 | |||
292 | -separate_out2, so2 |
|
293 | -separate_out2, so2 | |
293 | separator after output prompts. |
|
294 | separator after output prompts. | |
294 | Default: nothing. |
|
295 | Default: nothing. | |
295 | For these three options, use the value 0 to specify no separator. |
|
296 | For these three options, use the value 0 to specify no separator. | |
296 |
|
297 | |||
297 | -nosep |
|
298 | -nosep | |
298 | shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 |
|
299 | shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 | |
299 | 0'. Simply removes all input/output separators. |
|
300 | 0'. Simply removes all input/output separators. | |
300 |
|
301 | |||
301 | -upgrade |
|
302 | -upgrade | |
302 | allows you to upgrade your IPYTHON_DIR configuration when you |
|
303 | allows you to upgrade your IPYTHON_DIR configuration when you | |
303 | install a new version of IPython. Since new versions may |
|
304 | install a new version of IPython. Since new versions may | |
304 | include new command line options or example files, this copies |
|
305 | include new command line options or example files, this copies | |
305 | updated ipythonrc-type files. However, it backs up (with a |
|
306 | updated ipythonrc-type files. However, it backs up (with a | |
306 | .old extension) all files which it overwrites so that you can |
|
307 | .old extension) all files which it overwrites so that you can | |
307 | merge back any customizations you might have in your personal |
|
308 | merge back any customizations you might have in your personal | |
308 | files. Note that you should probably use %upgrade instead, |
|
309 | files. Note that you should probably use %upgrade instead, | |
309 | it's a safer alternative. |
|
310 | it's a safer alternative. | |
310 |
|
311 | |||
311 |
|
312 | |||
312 | -Version print version information and exit. |
|
313 | -Version print version information and exit. | |
313 |
|
314 | |||
314 | -wxversion <string> |
|
315 | -wxversion <string> | |
315 | Deprecated. |
|
316 | Deprecated. | |
316 |
|
317 | |||
317 | -xmode <modename> |
|
318 | -xmode <modename> | |
318 |
|
319 | |||
319 | Mode for exception reporting. |
|
320 | Mode for exception reporting. | |
320 |
|
321 | |||
321 | Valid modes: Plain, Context and Verbose. |
|
322 | Valid modes: Plain, Context and Verbose. | |
322 |
|
323 | |||
323 | * Plain: similar to python's normal traceback printing. |
|
324 | * Plain: similar to python's normal traceback printing. | |
324 | * Context: prints 5 lines of context source code around each |
|
325 | * Context: prints 5 lines of context source code around each | |
325 | line in the traceback. |
|
326 | line in the traceback. | |
326 | * Verbose: similar to Context, but additionally prints the |
|
327 | * Verbose: similar to Context, but additionally prints the | |
327 | variables currently visible where the exception happened |
|
328 | variables currently visible where the exception happened | |
328 | (shortening their strings if too long). This can potentially be |
|
329 | (shortening their strings if too long). This can potentially be | |
329 | very slow, if you happen to have a huge data structure whose |
|
330 | very slow, if you happen to have a huge data structure whose | |
330 | string representation is complex to compute. Your computer may |
|
331 | string representation is complex to compute. Your computer may | |
331 | appear to freeze for a while with cpu usage at 100%. If this |
|
332 | appear to freeze for a while with cpu usage at 100%. If this | |
332 | occurs, you can cancel the traceback with Ctrl-C (maybe hitting it |
|
333 | occurs, you can cancel the traceback with Ctrl-C (maybe hitting it | |
333 | more than once). |
|
334 | more than once). | |
334 |
|
335 | |||
335 | Interactive use |
|
336 | Interactive use | |
336 | =============== |
|
337 | =============== | |
337 |
|
338 | |||
338 | Warning: IPython relies on the existence of a global variable called |
|
339 | Warning: IPython relies on the existence of a global variable called | |
339 | _ip which controls the shell itself. If you redefine _ip to anything, |
|
340 | _ip which controls the shell itself. If you redefine _ip to anything, | |
340 | bizarre behavior will quickly occur. |
|
341 | bizarre behavior will quickly occur. | |
341 |
|
342 | |||
342 | Other than the above warning, IPython is meant to work as a drop-in |
|
343 | Other than the above warning, IPython is meant to work as a drop-in | |
343 | replacement for the standard interactive interpreter. As such, any code |
|
344 | replacement for the standard interactive interpreter. As such, any code | |
344 | which is valid python should execute normally under IPython (cases where |
|
345 | which is valid python should execute normally under IPython (cases where | |
345 | this is not true should be reported as bugs). It does, however, offer |
|
346 | this is not true should be reported as bugs). It does, however, offer | |
346 | many features which are not available at a standard python prompt. What |
|
347 | many features which are not available at a standard python prompt. What | |
347 | follows is a list of these. |
|
348 | follows is a list of these. | |
348 |
|
349 | |||
349 |
|
350 | |||
350 | Caution for Windows users |
|
351 | Caution for Windows users | |
351 | ------------------------- |
|
352 | ------------------------- | |
352 |
|
353 | |||
353 | Windows, unfortunately, uses the '\' character as a path |
|
354 | Windows, unfortunately, uses the '\' character as a path | |
354 | separator. This is a terrible choice, because '\' also represents the |
|
355 | separator. This is a terrible choice, because '\' also represents the | |
355 | escape character in most modern programming languages, including |
|
356 | escape character in most modern programming languages, including | |
356 | Python. For this reason, using '/' character is recommended if you |
|
357 | Python. For this reason, using '/' character is recommended if you | |
357 | have problems with ``\``. However, in Windows commands '/' flags |
|
358 | have problems with ``\``. However, in Windows commands '/' flags | |
358 | options, so you can not use it for the root directory. This means that |
|
359 | options, so you can not use it for the root directory. This means that | |
359 | paths beginning at the root must be typed in a contrived manner like: |
|
360 | paths beginning at the root must be typed in a contrived manner like: | |
360 | ``%copy \opt/foo/bar.txt \tmp`` |
|
361 | ``%copy \opt/foo/bar.txt \tmp`` | |
361 |
|
362 | |||
362 | .. _magic: |
|
363 | .. _magic: | |
363 |
|
364 | |||
364 | Magic command system |
|
365 | Magic command system | |
365 | -------------------- |
|
366 | -------------------- | |
366 |
|
367 | |||
367 | IPython will treat any line whose first character is a % as a special |
|
368 | IPython will treat any line whose first character is a % as a special | |
368 | call to a 'magic' function. These allow you to control the behavior of |
|
369 | call to a 'magic' function. These allow you to control the behavior of | |
369 | IPython itself, plus a lot of system-type features. They are all |
|
370 | IPython itself, plus a lot of system-type features. They are all | |
370 | prefixed with a % character, but parameters are given without |
|
371 | prefixed with a % character, but parameters are given without | |
371 | parentheses or quotes. |
|
372 | parentheses or quotes. | |
372 |
|
373 | |||
373 | Example: typing '%cd mydir' (without the quotes) changes you working |
|
374 | Example: typing '%cd mydir' (without the quotes) changes you working | |
374 | directory to 'mydir', if it exists. |
|
375 | directory to 'mydir', if it exists. | |
375 |
|
376 | |||
376 | If you have 'automagic' enabled (in your ipythonrc file, via the command |
|
377 | If you have 'automagic' enabled (in your ipythonrc file, via the command | |
377 | line option -automagic or with the %automagic function), you don't need |
|
378 | line option -automagic or with the %automagic function), you don't need | |
378 | to type in the % explicitly. IPython will scan its internal list of |
|
379 | to type in the % explicitly. IPython will scan its internal list of | |
379 | magic functions and call one if it exists. With automagic on you can |
|
380 | magic functions and call one if it exists. With automagic on you can | |
380 | then just type 'cd mydir' to go to directory 'mydir'. The automagic |
|
381 | then just type 'cd mydir' to go to directory 'mydir'. The automagic | |
381 | system has the lowest possible precedence in name searches, so defining |
|
382 | system has the lowest possible precedence in name searches, so defining | |
382 | an identifier with the same name as an existing magic function will |
|
383 | an identifier with the same name as an existing magic function will | |
383 | shadow it for automagic use. You can still access the shadowed magic |
|
384 | shadow it for automagic use. You can still access the shadowed magic | |
384 | function by explicitly using the % character at the beginning of the line. |
|
385 | function by explicitly using the % character at the beginning of the line. | |
385 |
|
386 | |||
386 | An example (with automagic on) should clarify all this:: |
|
387 | An example (with automagic on) should clarify all this:: | |
387 |
|
388 | |||
388 | In [1]: cd ipython # %cd is called by automagic |
|
389 | In [1]: cd ipython # %cd is called by automagic | |
389 |
|
390 | |||
390 | /home/fperez/ipython |
|
391 | /home/fperez/ipython | |
391 |
|
392 | |||
392 | In [2]: cd=1 # now cd is just a variable |
|
393 | In [2]: cd=1 # now cd is just a variable | |
393 |
|
394 | |||
394 | In [3]: cd .. # and doesn't work as a function anymore |
|
395 | In [3]: cd .. # and doesn't work as a function anymore | |
395 |
|
396 | |||
396 | ------------------------------ |
|
397 | ------------------------------ | |
397 |
|
398 | |||
398 | File "<console>", line 1 |
|
399 | File "<console>", line 1 | |
399 |
|
400 | |||
400 | cd .. |
|
401 | cd .. | |
401 |
|
402 | |||
402 | ^ |
|
403 | ^ | |
403 |
|
404 | |||
404 | SyntaxError: invalid syntax |
|
405 | SyntaxError: invalid syntax | |
405 |
|
406 | |||
406 | In [4]: %cd .. # but %cd always works |
|
407 | In [4]: %cd .. # but %cd always works | |
407 |
|
408 | |||
408 | /home/fperez |
|
409 | /home/fperez | |
409 |
|
410 | |||
410 | In [5]: del cd # if you remove the cd variable |
|
411 | In [5]: del cd # if you remove the cd variable | |
411 |
|
412 | |||
412 | In [6]: cd ipython # automagic can work again |
|
413 | In [6]: cd ipython # automagic can work again | |
413 |
|
414 | |||
414 | /home/fperez/ipython |
|
415 | /home/fperez/ipython | |
415 |
|
416 | |||
416 | You can define your own magic functions to extend the system. The |
|
417 | You can define your own magic functions to extend the system. The | |
417 | following example defines a new magic command, %impall:: |
|
418 | following example defines a new magic command, %impall:: | |
418 |
|
419 | |||
419 | import IPython.ipapi |
|
420 | import IPython.ipapi | |
420 |
|
421 | |||
421 | ip = IPython.ipapi.get() |
|
422 | ip = IPython.ipapi.get() | |
422 |
|
423 | |||
423 | def doimp(self, arg): |
|
424 | def doimp(self, arg): | |
424 |
|
425 | |||
425 | ip = self.api |
|
426 | ip = self.api | |
426 |
|
427 | |||
427 | ip.ex("import %s; reload(%s); from %s import *" % ( |
|
428 | ip.ex("import %s; reload(%s); from %s import *" % ( | |
428 |
|
429 | |||
429 | arg,arg,arg) |
|
430 | arg,arg,arg) | |
430 |
|
431 | |||
431 | ) |
|
432 | ) | |
432 |
|
433 | |||
433 | ip.expose_magic('impall', doimp) |
|
434 | ip.expose_magic('impall', doimp) | |
434 |
|
435 | |||
435 | You can also define your own aliased names for magic functions. In your |
|
436 | You can also define your own aliased names for magic functions. In your | |
436 | ipythonrc file, placing a line like:: |
|
437 | ipythonrc file, placing a line like:: | |
437 |
|
438 | |||
438 | execute __IP.magic_cl = __IP.magic_clear |
|
439 | execute __IP.magic_cl = __IP.magic_clear | |
439 |
|
440 | |||
440 | will define %cl as a new name for %clear. |
|
441 | will define %cl as a new name for %clear. | |
441 |
|
442 | |||
442 | Type %magic for more information, including a list of all available |
|
443 | Type %magic for more information, including a list of all available | |
443 | magic functions at any time and their docstrings. You can also type |
|
444 | magic functions at any time and their docstrings. You can also type | |
444 | %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for |
|
445 | %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for | |
445 | information on the '?' system) to get information about any particular |
|
446 | information on the '?' system) to get information about any particular | |
446 | magic function you are interested in. |
|
447 | magic function you are interested in. | |
447 |
|
448 | |||
448 | The API documentation for the :mod:`IPython.Magic` module contains the full |
|
449 | The API documentation for the :mod:`IPython.Magic` module contains the full | |
449 | docstrings of all currently available magic commands. |
|
450 | docstrings of all currently available magic commands. | |
450 |
|
451 | |||
451 |
|
452 | |||
452 | Access to the standard Python help |
|
453 | Access to the standard Python help | |
453 | ---------------------------------- |
|
454 | ---------------------------------- | |
454 |
|
455 | |||
455 | As of Python 2.1, a help system is available with access to object docstrings |
|
456 | As of Python 2.1, a help system is available with access to object docstrings | |
456 | and the Python manuals. Simply type 'help' (no quotes) to access it. You can |
|
457 | and the Python manuals. Simply type 'help' (no quotes) to access it. You can | |
457 | also type help(object) to obtain information about a given object, and |
|
458 | also type help(object) to obtain information about a given object, and | |
458 | help('keyword') for information on a keyword. As noted :ref:`here |
|
459 | help('keyword') for information on a keyword. As noted :ref:`here | |
459 | <accessing_help>`, you need to properly configure your environment variable |
|
460 | <accessing_help>`, you need to properly configure your environment variable | |
460 | PYTHONDOCS for this feature to work correctly. |
|
461 | PYTHONDOCS for this feature to work correctly. | |
461 |
|
462 | |||
462 | .. _dynamic_object_info: |
|
463 | .. _dynamic_object_info: | |
463 |
|
464 | |||
464 | Dynamic object information |
|
465 | Dynamic object information | |
465 | -------------------------- |
|
466 | -------------------------- | |
466 |
|
467 | |||
467 | Typing ?word or word? prints detailed information about an object. If |
|
468 | Typing ?word or word? prints detailed information about an object. If | |
468 | certain strings in the object are too long (docstrings, code, etc.) they |
|
469 | certain strings in the object are too long (docstrings, code, etc.) they | |
469 | get snipped in the center for brevity. This system gives access variable |
|
470 | get snipped in the center for brevity. This system gives access variable | |
470 | types and values, full source code for any object (if available), |
|
471 | types and values, full source code for any object (if available), | |
471 | function prototypes and other useful information. |
|
472 | function prototypes and other useful information. | |
472 |
|
473 | |||
473 | Typing ??word or word?? gives access to the full information without |
|
474 | Typing ??word or word?? gives access to the full information without | |
474 | snipping long strings. Long strings are sent to the screen through the |
|
475 | snipping long strings. Long strings are sent to the screen through the | |
475 | less pager if longer than the screen and printed otherwise. On systems |
|
476 | less pager if longer than the screen and printed otherwise. On systems | |
476 | lacking the less command, IPython uses a very basic internal pager. |
|
477 | lacking the less command, IPython uses a very basic internal pager. | |
477 |
|
478 | |||
478 | The following magic functions are particularly useful for gathering |
|
479 | The following magic functions are particularly useful for gathering | |
479 | information about your working environment. You can get more details by |
|
480 | information about your working environment. You can get more details by | |
480 | typing %magic or querying them individually (use %function_name? with or |
|
481 | typing %magic or querying them individually (use %function_name? with or | |
481 | without the %), this is just a summary: |
|
482 | without the %), this is just a summary: | |
482 |
|
483 | |||
483 | * **%pdoc <object>**: Print (or run through a pager if too long) the |
|
484 | * **%pdoc <object>**: Print (or run through a pager if too long) the | |
484 | docstring for an object. If the given object is a class, it will |
|
485 | docstring for an object. If the given object is a class, it will | |
485 | print both the class and the constructor docstrings. |
|
486 | print both the class and the constructor docstrings. | |
486 | * **%pdef <object>**: Print the definition header for any callable |
|
487 | * **%pdef <object>**: Print the definition header for any callable | |
487 | object. If the object is a class, print the constructor information. |
|
488 | object. If the object is a class, print the constructor information. | |
488 | * **%psource <object>**: Print (or run through a pager if too long) |
|
489 | * **%psource <object>**: Print (or run through a pager if too long) | |
489 | the source code for an object. |
|
490 | the source code for an object. | |
490 | * **%pfile <object>**: Show the entire source file where an object was |
|
491 | * **%pfile <object>**: Show the entire source file where an object was | |
491 | defined via a pager, opening it at the line where the object |
|
492 | defined via a pager, opening it at the line where the object | |
492 | definition begins. |
|
493 | definition begins. | |
493 | * **%who/%whos**: These functions give information about identifiers |
|
494 | * **%who/%whos**: These functions give information about identifiers | |
494 | you have defined interactively (not things you loaded or defined |
|
495 | you have defined interactively (not things you loaded or defined | |
495 | in your configuration files). %who just prints a list of |
|
496 | in your configuration files). %who just prints a list of | |
496 | identifiers and %whos prints a table with some basic details about |
|
497 | identifiers and %whos prints a table with some basic details about | |
497 | each identifier. |
|
498 | each identifier. | |
498 |
|
499 | |||
499 | Note that the dynamic object information functions (?/??, %pdoc, %pfile, |
|
500 | Note that the dynamic object information functions (?/??, %pdoc, %pfile, | |
500 | %pdef, %psource) give you access to documentation even on things which |
|
501 | %pdef, %psource) give you access to documentation even on things which | |
501 | are not really defined as separate identifiers. Try for example typing |
|
502 | are not really defined as separate identifiers. Try for example typing | |
502 | {}.get? or after doing import os, type os.path.abspath??. |
|
503 | {}.get? or after doing import os, type os.path.abspath??. | |
503 |
|
504 | |||
504 |
|
505 | |||
505 | .. _readline: |
|
506 | .. _readline: | |
506 |
|
507 | |||
507 | Readline-based features |
|
508 | Readline-based features | |
508 | ----------------------- |
|
509 | ----------------------- | |
509 |
|
510 | |||
510 | These features require the GNU readline library, so they won't work if |
|
511 | These features require the GNU readline library, so they won't work if | |
511 | your Python installation lacks readline support. We will first describe |
|
512 | your Python installation lacks readline support. We will first describe | |
512 | the default behavior IPython uses, and then how to change it to suit |
|
513 | the default behavior IPython uses, and then how to change it to suit | |
513 | your preferences. |
|
514 | your preferences. | |
514 |
|
515 | |||
515 |
|
516 | |||
516 | Command line completion |
|
517 | Command line completion | |
517 | +++++++++++++++++++++++ |
|
518 | +++++++++++++++++++++++ | |
518 |
|
519 | |||
519 | At any time, hitting TAB will complete any available python commands or |
|
520 | At any time, hitting TAB will complete any available python commands or | |
520 | variable names, and show you a list of the possible completions if |
|
521 | variable names, and show you a list of the possible completions if | |
521 | there's no unambiguous one. It will also complete filenames in the |
|
522 | there's no unambiguous one. It will also complete filenames in the | |
522 | current directory if no python names match what you've typed so far. |
|
523 | current directory if no python names match what you've typed so far. | |
523 |
|
524 | |||
524 |
|
525 | |||
525 | Search command history |
|
526 | Search command history | |
526 | ++++++++++++++++++++++ |
|
527 | ++++++++++++++++++++++ | |
527 |
|
528 | |||
528 | IPython provides two ways for searching through previous input and thus |
|
529 | IPython provides two ways for searching through previous input and thus | |
529 | reduce the need for repetitive typing: |
|
530 | reduce the need for repetitive typing: | |
530 |
|
531 | |||
531 | 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n |
|
532 | 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n | |
532 | (next,down) to search through only the history items that match |
|
533 | (next,down) to search through only the history items that match | |
533 | what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank |
|
534 | what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank | |
534 | prompt, they just behave like normal arrow keys. |
|
535 | prompt, they just behave like normal arrow keys. | |
535 | 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system |
|
536 | 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system | |
536 | searches your history for lines that contain what you've typed so |
|
537 | searches your history for lines that contain what you've typed so | |
537 | far, completing as much as it can. |
|
538 | far, completing as much as it can. | |
538 |
|
539 | |||
539 |
|
540 | |||
540 | Persistent command history across sessions |
|
541 | Persistent command history across sessions | |
541 | ++++++++++++++++++++++++++++++++++++++++++ |
|
542 | ++++++++++++++++++++++++++++++++++++++++++ | |
542 |
|
543 | |||
543 | IPython will save your input history when it leaves and reload it next |
|
544 | IPython will save your input history when it leaves and reload it next | |
544 | time you restart it. By default, the history file is named |
|
545 | time you restart it. By default, the history file is named | |
545 | $IPYTHON_DIR/history, but if you've loaded a named profile, |
|
546 | $IPYTHON_DIR/history, but if you've loaded a named profile, | |
546 | '-PROFILE_NAME' is appended to the name. This allows you to keep |
|
547 | '-PROFILE_NAME' is appended to the name. This allows you to keep | |
547 | separate histories related to various tasks: commands related to |
|
548 | separate histories related to various tasks: commands related to | |
548 | numerical work will not be clobbered by a system shell history, for |
|
549 | numerical work will not be clobbered by a system shell history, for | |
549 | example. |
|
550 | example. | |
550 |
|
551 | |||
551 |
|
552 | |||
552 | Autoindent |
|
553 | Autoindent | |
553 | ++++++++++ |
|
554 | ++++++++++ | |
554 |
|
555 | |||
555 | IPython can recognize lines ending in ':' and indent the next line, |
|
556 | IPython can recognize lines ending in ':' and indent the next line, | |
556 | while also un-indenting automatically after 'raise' or 'return'. |
|
557 | while also un-indenting automatically after 'raise' or 'return'. | |
557 |
|
558 | |||
558 | This feature uses the readline library, so it will honor your ~/.inputrc |
|
559 | This feature uses the readline library, so it will honor your ~/.inputrc | |
559 | configuration (or whatever file your INPUTRC variable points to). Adding |
|
560 | configuration (or whatever file your INPUTRC variable points to). Adding | |
560 | the following lines to your .inputrc file can make indenting/unindenting |
|
561 | the following lines to your .inputrc file can make indenting/unindenting | |
561 | more convenient (M-i indents, M-u unindents):: |
|
562 | more convenient (M-i indents, M-u unindents):: | |
562 |
|
563 | |||
563 | $if Python |
|
564 | $if Python | |
564 | "\M-i": " " |
|
565 | "\M-i": " " | |
565 | "\M-u": "\d\d\d\d" |
|
566 | "\M-u": "\d\d\d\d" | |
566 | $endif |
|
567 | $endif | |
567 |
|
568 | |||
568 | Note that there are 4 spaces between the quote marks after "M-i" above. |
|
569 | Note that there are 4 spaces between the quote marks after "M-i" above. | |
569 |
|
570 | |||
570 | Warning: this feature is ON by default, but it can cause problems with |
|
571 | Warning: this feature is ON by default, but it can cause problems with | |
571 | the pasting of multi-line indented code (the pasted code gets |
|
572 | the pasting of multi-line indented code (the pasted code gets | |
572 | re-indented on each line). A magic function %autoindent allows you to |
|
573 | re-indented on each line). A magic function %autoindent allows you to | |
573 | toggle it on/off at runtime. You can also disable it permanently on in |
|
574 | toggle it on/off at runtime. You can also disable it permanently on in | |
574 | your ipythonrc file (set autoindent 0). |
|
575 | your ipythonrc file (set autoindent 0). | |
575 |
|
576 | |||
576 |
|
577 | |||
577 | Customizing readline behavior |
|
578 | Customizing readline behavior | |
578 | +++++++++++++++++++++++++++++ |
|
579 | +++++++++++++++++++++++++++++ | |
579 |
|
580 | |||
580 | All these features are based on the GNU readline library, which has an |
|
581 | All these features are based on the GNU readline library, which has an | |
581 | extremely customizable interface. Normally, readline is configured via a |
|
582 | extremely customizable interface. Normally, readline is configured via a | |
582 | file which defines the behavior of the library; the details of the |
|
583 | file which defines the behavior of the library; the details of the | |
583 | syntax for this can be found in the readline documentation available |
|
584 | syntax for this can be found in the readline documentation available | |
584 | with your system or on the Internet. IPython doesn't read this file (if |
|
585 | with your system or on the Internet. IPython doesn't read this file (if | |
585 | it exists) directly, but it does support passing to readline valid |
|
586 | it exists) directly, but it does support passing to readline valid | |
586 | options via a simple interface. In brief, you can customize readline by |
|
587 | options via a simple interface. In brief, you can customize readline by | |
587 | setting the following options in your ipythonrc configuration file (note |
|
588 | setting the following options in your ipythonrc configuration file (note | |
588 | that these options can not be specified at the command line): |
|
589 | that these options can not be specified at the command line): | |
589 |
|
590 | |||
590 | * **readline_parse_and_bind**: this option can appear as many times as |
|
591 | * **readline_parse_and_bind**: this option can appear as many times as | |
591 | you want, each time defining a string to be executed via a |
|
592 | you want, each time defining a string to be executed via a | |
592 | readline.parse_and_bind() command. The syntax for valid commands |
|
593 | readline.parse_and_bind() command. The syntax for valid commands | |
593 | of this kind can be found by reading the documentation for the GNU |
|
594 | of this kind can be found by reading the documentation for the GNU | |
594 | readline library, as these commands are of the kind which readline |
|
595 | readline library, as these commands are of the kind which readline | |
595 | accepts in its configuration file. |
|
596 | accepts in its configuration file. | |
596 | * **readline_remove_delims**: a string of characters to be removed |
|
597 | * **readline_remove_delims**: a string of characters to be removed | |
597 | from the default word-delimiters list used by readline, so that |
|
598 | from the default word-delimiters list used by readline, so that | |
598 | completions may be performed on strings which contain them. Do not |
|
599 | completions may be performed on strings which contain them. Do not | |
599 | change the default value unless you know what you're doing. |
|
600 | change the default value unless you know what you're doing. | |
600 | * **readline_omit__names**: when tab-completion is enabled, hitting |
|
601 | * **readline_omit__names**: when tab-completion is enabled, hitting | |
601 | <tab> after a '.' in a name will complete all attributes of an |
|
602 | <tab> after a '.' in a name will complete all attributes of an | |
602 | object, including all the special methods whose names include |
|
603 | object, including all the special methods whose names include | |
603 | double underscores (like __getitem__ or __class__). If you'd |
|
604 | double underscores (like __getitem__ or __class__). If you'd | |
604 | rather not see these names by default, you can set this option to |
|
605 | rather not see these names by default, you can set this option to | |
605 | 1. Note that even when this option is set, you can still see those |
|
606 | 1. Note that even when this option is set, you can still see those | |
606 | names by explicitly typing a _ after the period and hitting <tab>: |
|
607 | names by explicitly typing a _ after the period and hitting <tab>: | |
607 | 'name._<tab>' will always complete attribute names starting with '_'. |
|
608 | 'name._<tab>' will always complete attribute names starting with '_'. | |
608 |
|
609 | |||
609 | This option is off by default so that new users see all |
|
610 | This option is off by default so that new users see all | |
610 | attributes of any objects they are dealing with. |
|
611 | attributes of any objects they are dealing with. | |
611 |
|
612 | |||
612 | You will find the default values along with a corresponding detailed |
|
613 | You will find the default values along with a corresponding detailed | |
613 | explanation in your ipythonrc file. |
|
614 | explanation in your ipythonrc file. | |
614 |
|
615 | |||
615 |
|
616 | |||
616 | Session logging and restoring |
|
617 | Session logging and restoring | |
617 | ----------------------------- |
|
618 | ----------------------------- | |
618 |
|
619 | |||
619 | You can log all input from a session either by starting IPython with the |
|
620 | You can log all input from a session either by starting IPython with the | |
620 | command line switches -log or -logfile (see :ref:`here <command_line_options>`) |
|
621 | command line switches -log or -logfile (see :ref:`here <command_line_options>`) | |
621 | or by activating the logging at any moment with the magic function %logstart. |
|
622 | or by activating the logging at any moment with the magic function %logstart. | |
622 |
|
623 | |||
623 | Log files can later be reloaded with the -logplay option and IPython |
|
624 | Log files can later be reloaded with the -logplay option and IPython | |
624 | will attempt to 'replay' the log by executing all the lines in it, thus |
|
625 | will attempt to 'replay' the log by executing all the lines in it, thus | |
625 | restoring the state of a previous session. This feature is not quite |
|
626 | restoring the state of a previous session. This feature is not quite | |
626 | perfect, but can still be useful in many cases. |
|
627 | perfect, but can still be useful in many cases. | |
627 |
|
628 | |||
628 | The log files can also be used as a way to have a permanent record of |
|
629 | The log files can also be used as a way to have a permanent record of | |
629 | any code you wrote while experimenting. Log files are regular text files |
|
630 | any code you wrote while experimenting. Log files are regular text files | |
630 | which you can later open in your favorite text editor to extract code or |
|
631 | which you can later open in your favorite text editor to extract code or | |
631 | to 'clean them up' before using them to replay a session. |
|
632 | to 'clean them up' before using them to replay a session. | |
632 |
|
633 | |||
633 | The %logstart function for activating logging in mid-session is used as |
|
634 | The %logstart function for activating logging in mid-session is used as | |
634 | follows: |
|
635 | follows: | |
635 |
|
636 | |||
636 | %logstart [log_name [log_mode]] |
|
637 | %logstart [log_name [log_mode]] | |
637 |
|
638 | |||
638 | If no name is given, it defaults to a file named 'log' in your |
|
639 | If no name is given, it defaults to a file named 'log' in your | |
639 | IPYTHON_DIR directory, in 'rotate' mode (see below). |
|
640 | IPYTHON_DIR directory, in 'rotate' mode (see below). | |
640 |
|
641 | |||
641 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
642 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
642 | history up to that point and then continues logging. |
|
643 | history up to that point and then continues logging. | |
643 |
|
644 | |||
644 | %logstart takes a second optional parameter: logging mode. This can be |
|
645 | %logstart takes a second optional parameter: logging mode. This can be | |
645 | one of (note that the modes are given unquoted): |
|
646 | one of (note that the modes are given unquoted): | |
646 |
|
647 | |||
647 | * [over:] overwrite existing log_name. |
|
648 | * [over:] overwrite existing log_name. | |
648 | * [backup:] rename (if exists) to log_name~ and start log_name. |
|
649 | * [backup:] rename (if exists) to log_name~ and start log_name. | |
649 | * [append:] well, that says it. |
|
650 | * [append:] well, that says it. | |
650 | * [rotate:] create rotating logs log_name.1~, log_name.2~, etc. |
|
651 | * [rotate:] create rotating logs log_name.1~, log_name.2~, etc. | |
651 |
|
652 | |||
652 | The %logoff and %logon functions allow you to temporarily stop and |
|
653 | The %logoff and %logon functions allow you to temporarily stop and | |
653 | resume logging to a file which had previously been started with |
|
654 | resume logging to a file which had previously been started with | |
654 | %logstart. They will fail (with an explanation) if you try to use them |
|
655 | %logstart. They will fail (with an explanation) if you try to use them | |
655 | before logging has been started. |
|
656 | before logging has been started. | |
656 |
|
657 | |||
657 | .. _system_shell_access: |
|
658 | .. _system_shell_access: | |
658 |
|
659 | |||
659 | System shell access |
|
660 | System shell access | |
660 | ------------------- |
|
661 | ------------------- | |
661 |
|
662 | |||
662 | Any input line beginning with a ! character is passed verbatim (minus |
|
663 | Any input line beginning with a ! character is passed verbatim (minus | |
663 | the !, of course) to the underlying operating system. For example, |
|
664 | the !, of course) to the underlying operating system. For example, | |
664 | typing !ls will run 'ls' in the current directory. |
|
665 | typing !ls will run 'ls' in the current directory. | |
665 |
|
666 | |||
666 | Manual capture of command output |
|
667 | Manual capture of command output | |
667 | -------------------------------- |
|
668 | -------------------------------- | |
668 |
|
669 | |||
669 | If the input line begins with two exclamation marks, !!, the command is |
|
670 | If the input line begins with two exclamation marks, !!, the command is | |
670 | executed but its output is captured and returned as a python list, split |
|
671 | executed but its output is captured and returned as a python list, split | |
671 | on newlines. Any output sent by the subprocess to standard error is |
|
672 | on newlines. Any output sent by the subprocess to standard error is | |
672 | printed separately, so that the resulting list only captures standard |
|
673 | printed separately, so that the resulting list only captures standard | |
673 | output. The !! syntax is a shorthand for the %sx magic command. |
|
674 | output. The !! syntax is a shorthand for the %sx magic command. | |
674 |
|
675 | |||
675 | Finally, the %sc magic (short for 'shell capture') is similar to %sx, |
|
676 | Finally, the %sc magic (short for 'shell capture') is similar to %sx, | |
676 | but allowing more fine-grained control of the capture details, and |
|
677 | but allowing more fine-grained control of the capture details, and | |
677 | storing the result directly into a named variable. The direct use of |
|
678 | storing the result directly into a named variable. The direct use of | |
678 | %sc is now deprecated, and you should ise the ``var = !cmd`` syntax |
|
679 | %sc is now deprecated, and you should ise the ``var = !cmd`` syntax | |
679 | instead. |
|
680 | instead. | |
680 |
|
681 | |||
681 | IPython also allows you to expand the value of python variables when |
|
682 | IPython also allows you to expand the value of python variables when | |
682 | making system calls. Any python variable or expression which you prepend |
|
683 | making system calls. Any python variable or expression which you prepend | |
683 | with $ will get expanded before the system call is made:: |
|
684 | with $ will get expanded before the system call is made:: | |
684 |
|
685 | |||
685 | In [1]: pyvar='Hello world' |
|
686 | In [1]: pyvar='Hello world' | |
686 | In [2]: !echo "A python variable: $pyvar" |
|
687 | In [2]: !echo "A python variable: $pyvar" | |
687 | A python variable: Hello world |
|
688 | A python variable: Hello world | |
688 |
|
689 | |||
689 | If you want the shell to actually see a literal $, you need to type it |
|
690 | If you want the shell to actually see a literal $, you need to type it | |
690 | twice:: |
|
691 | twice:: | |
691 |
|
692 | |||
692 | In [3]: !echo "A system variable: $$HOME" |
|
693 | In [3]: !echo "A system variable: $$HOME" | |
693 | A system variable: /home/fperez |
|
694 | A system variable: /home/fperez | |
694 |
|
695 | |||
695 | You can pass arbitrary expressions, though you'll need to delimit them |
|
696 | You can pass arbitrary expressions, though you'll need to delimit them | |
696 | with {} if there is ambiguity as to the extent of the expression:: |
|
697 | with {} if there is ambiguity as to the extent of the expression:: | |
697 |
|
698 | |||
698 | In [5]: x=10 |
|
699 | In [5]: x=10 | |
699 | In [6]: y=20 |
|
700 | In [6]: y=20 | |
700 | In [13]: !echo $x+y |
|
701 | In [13]: !echo $x+y | |
701 | 10+y |
|
702 | 10+y | |
702 | In [7]: !echo ${x+y} |
|
703 | In [7]: !echo ${x+y} | |
703 | 30 |
|
704 | 30 | |
704 |
|
705 | |||
705 | Even object attributes can be expanded:: |
|
706 | Even object attributes can be expanded:: | |
706 |
|
707 | |||
707 | In [12]: !echo $sys.argv |
|
708 | In [12]: !echo $sys.argv | |
708 | [/home/fperez/usr/bin/ipython] |
|
709 | [/home/fperez/usr/bin/ipython] | |
709 |
|
710 | |||
710 |
|
711 | |||
711 | System command aliases |
|
712 | System command aliases | |
712 | ---------------------- |
|
713 | ---------------------- | |
713 |
|
714 | |||
714 | The %alias magic function and the alias option in the ipythonrc |
|
715 | The %alias magic function and the alias option in the ipythonrc | |
715 | configuration file allow you to define magic functions which are in fact |
|
716 | configuration file allow you to define magic functions which are in fact | |
716 | system shell commands. These aliases can have parameters. |
|
717 | system shell commands. These aliases can have parameters. | |
717 |
|
718 | |||
718 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
719 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
719 |
|
720 | |||
720 | Then, typing '%alias_name params' will execute the system command 'cmd |
|
721 | Then, typing '%alias_name params' will execute the system command 'cmd | |
721 | params' (from your underlying operating system). |
|
722 | params' (from your underlying operating system). | |
722 |
|
723 | |||
723 | You can also define aliases with parameters using %s specifiers (one per |
|
724 | You can also define aliases with parameters using %s specifiers (one per | |
724 | parameter). The following example defines the %parts function as an |
|
725 | parameter). The following example defines the %parts function as an | |
725 | alias to the command 'echo first %s second %s' where each %s will be |
|
726 | alias to the command 'echo first %s second %s' where each %s will be | |
726 | replaced by a positional parameter to the call to %parts:: |
|
727 | replaced by a positional parameter to the call to %parts:: | |
727 |
|
728 | |||
728 | In [1]: alias parts echo first %s second %s |
|
729 | In [1]: alias parts echo first %s second %s | |
729 | In [2]: %parts A B |
|
730 | In [2]: %parts A B | |
730 | first A second B |
|
731 | first A second B | |
731 | In [3]: %parts A |
|
732 | In [3]: %parts A | |
732 | Incorrect number of arguments: 2 expected. |
|
733 | Incorrect number of arguments: 2 expected. | |
733 | parts is an alias to: 'echo first %s second %s' |
|
734 | parts is an alias to: 'echo first %s second %s' | |
734 |
|
735 | |||
735 | If called with no parameters, %alias prints the table of currently |
|
736 | If called with no parameters, %alias prints the table of currently | |
736 | defined aliases. |
|
737 | defined aliases. | |
737 |
|
738 | |||
738 | The %rehash/rehashx magics allow you to load your entire $PATH as |
|
739 | The %rehash/rehashx magics allow you to load your entire $PATH as | |
739 | ipython aliases. See their respective docstrings (or sec. 6.2 |
|
740 | ipython aliases. See their respective docstrings (or sec. 6.2 | |
740 | <#sec:magic> for further details). |
|
741 | <#sec:magic> for further details). | |
741 |
|
742 | |||
742 |
|
743 | |||
743 | .. _dreload: |
|
744 | .. _dreload: | |
744 |
|
745 | |||
745 | Recursive reload |
|
746 | Recursive reload | |
746 | ---------------- |
|
747 | ---------------- | |
747 |
|
748 | |||
748 | The dreload function does a recursive reload of a module: changes made |
|
749 | The dreload function does a recursive reload of a module: changes made | |
749 | to the module since you imported will actually be available without |
|
750 | to the module since you imported will actually be available without | |
750 | having to exit. |
|
751 | having to exit. | |
751 |
|
752 | |||
752 |
|
753 | |||
753 | Verbose and colored exception traceback printouts |
|
754 | Verbose and colored exception traceback printouts | |
754 | ------------------------------------------------- |
|
755 | ------------------------------------------------- | |
755 |
|
756 | |||
756 | IPython provides the option to see very detailed exception tracebacks, |
|
757 | IPython provides the option to see very detailed exception tracebacks, | |
757 | which can be especially useful when debugging large programs. You can |
|
758 | which can be especially useful when debugging large programs. You can | |
758 | run any Python file with the %run function to benefit from these |
|
759 | run any Python file with the %run function to benefit from these | |
759 | detailed tracebacks. Furthermore, both normal and verbose tracebacks can |
|
760 | detailed tracebacks. Furthermore, both normal and verbose tracebacks can | |
760 | be colored (if your terminal supports it) which makes them much easier |
|
761 | be colored (if your terminal supports it) which makes them much easier | |
761 | to parse visually. |
|
762 | to parse visually. | |
762 |
|
763 | |||
763 | See the magic xmode and colors functions for details (just type %magic). |
|
764 | See the magic xmode and colors functions for details (just type %magic). | |
764 |
|
765 | |||
765 | These features are basically a terminal version of Ka-Ping Yee's cgitb |
|
766 | These features are basically a terminal version of Ka-Ping Yee's cgitb | |
766 | module, now part of the standard Python library. |
|
767 | module, now part of the standard Python library. | |
767 |
|
768 | |||
768 |
|
769 | |||
769 | .. _input_caching: |
|
770 | .. _input_caching: | |
770 |
|
771 | |||
771 | Input caching system |
|
772 | Input caching system | |
772 | -------------------- |
|
773 | -------------------- | |
773 |
|
774 | |||
774 | IPython offers numbered prompts (In/Out) with input and output caching |
|
775 | IPython offers numbered prompts (In/Out) with input and output caching | |
775 | (also referred to as 'input history'). All input is saved and can be |
|
776 | (also referred to as 'input history'). All input is saved and can be | |
776 | retrieved as variables (besides the usual arrow key recall), in |
|
777 | retrieved as variables (besides the usual arrow key recall), in | |
777 | addition to the %rep magic command that brings a history entry |
|
778 | addition to the %rep magic command that brings a history entry | |
778 | up for editing on the next command line. |
|
779 | up for editing on the next command line. | |
779 |
|
780 | |||
780 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
781 | The following GLOBAL variables always exist (so don't overwrite them!): | |
781 | _i: stores previous input. _ii: next previous. _iii: next-next previous. |
|
782 | _i: stores previous input. _ii: next previous. _iii: next-next previous. | |
782 | _ih : a list of all input _ih[n] is the input from line n and this list |
|
783 | _ih : a list of all input _ih[n] is the input from line n and this list | |
783 | is aliased to the global variable In. If you overwrite In with a |
|
784 | is aliased to the global variable In. If you overwrite In with a | |
784 | variable of your own, you can remake the assignment to the internal list |
|
785 | variable of your own, you can remake the assignment to the internal list | |
785 | with a simple 'In=_ih'. |
|
786 | with a simple 'In=_ih'. | |
786 |
|
787 | |||
787 | Additionally, global variables named _i<n> are dynamically created (<n> |
|
788 | Additionally, global variables named _i<n> are dynamically created (<n> | |
788 | being the prompt counter), such that |
|
789 | being the prompt counter), such that | |
789 | _i<n> == _ih[<n>] == In[<n>]. |
|
790 | _i<n> == _ih[<n>] == In[<n>]. | |
790 |
|
791 | |||
791 | For example, what you typed at prompt 14 is available as _i14, _ih[14] |
|
792 | For example, what you typed at prompt 14 is available as _i14, _ih[14] | |
792 | and In[14]. |
|
793 | and In[14]. | |
793 |
|
794 | |||
794 | This allows you to easily cut and paste multi line interactive prompts |
|
795 | This allows you to easily cut and paste multi line interactive prompts | |
795 | by printing them out: they print like a clean string, without prompt |
|
796 | by printing them out: they print like a clean string, without prompt | |
796 | characters. You can also manipulate them like regular variables (they |
|
797 | characters. You can also manipulate them like regular variables (they | |
797 | are strings), modify or exec them (typing 'exec _i9' will re-execute the |
|
798 | are strings), modify or exec them (typing 'exec _i9' will re-execute the | |
798 | contents of input prompt 9, 'exec In[9:14]+In[18]' will re-execute lines |
|
799 | contents of input prompt 9, 'exec In[9:14]+In[18]' will re-execute lines | |
799 | 9 through 13 and line 18). |
|
800 | 9 through 13 and line 18). | |
800 |
|
801 | |||
801 | You can also re-execute multiple lines of input easily by using the |
|
802 | You can also re-execute multiple lines of input easily by using the | |
802 | magic %macro function (which automates the process and allows |
|
803 | magic %macro function (which automates the process and allows | |
803 | re-execution without having to type 'exec' every time). The macro system |
|
804 | re-execution without having to type 'exec' every time). The macro system | |
804 | also allows you to re-execute previous lines which include magic |
|
805 | also allows you to re-execute previous lines which include magic | |
805 | function calls (which require special processing). Type %macro? or see |
|
806 | function calls (which require special processing). Type %macro? or see | |
806 | sec. 6.2 <#sec:magic> for more details on the macro system. |
|
807 | sec. 6.2 <#sec:magic> for more details on the macro system. | |
807 |
|
808 | |||
808 | A history function %hist allows you to see any part of your input |
|
809 | A history function %hist allows you to see any part of your input | |
809 | history by printing a range of the _i variables. |
|
810 | history by printing a range of the _i variables. | |
810 |
|
811 | |||
811 | You can also search ('grep') through your history by typing |
|
812 | You can also search ('grep') through your history by typing | |
812 | '%hist -g somestring'. This also searches through the so called *shadow history*, |
|
813 | '%hist -g somestring'. This also searches through the so called *shadow history*, | |
813 | which remembers all the commands (apart from multiline code blocks) |
|
814 | which remembers all the commands (apart from multiline code blocks) | |
814 | you have ever entered. Handy for searching for svn/bzr URL's, IP adrresses |
|
815 | you have ever entered. Handy for searching for svn/bzr URL's, IP adrresses | |
815 | etc. You can bring shadow history entries listed by '%hist -g' up for editing |
|
816 | etc. You can bring shadow history entries listed by '%hist -g' up for editing | |
816 | (or re-execution by just pressing ENTER) with %rep command. Shadow history |
|
817 | (or re-execution by just pressing ENTER) with %rep command. Shadow history | |
817 | entries are not available as _iNUMBER variables, and they are identified by |
|
818 | entries are not available as _iNUMBER variables, and they are identified by | |
818 | the '0' prefix in %hist -g output. That is, history entry 12 is a normal |
|
819 | the '0' prefix in %hist -g output. That is, history entry 12 is a normal | |
819 | history entry, but 0231 is a shadow history entry. |
|
820 | history entry, but 0231 is a shadow history entry. | |
820 |
|
821 | |||
821 | Shadow history was added because the readline history is inherently very |
|
822 | Shadow history was added because the readline history is inherently very | |
822 | unsafe - if you have multiple IPython sessions open, the last session |
|
823 | unsafe - if you have multiple IPython sessions open, the last session | |
823 | to close will overwrite the history of previountly closed session. Likewise, |
|
824 | to close will overwrite the history of previountly closed session. Likewise, | |
824 | if a crash occurs, history is never saved, whereas shadow history entries |
|
825 | if a crash occurs, history is never saved, whereas shadow history entries | |
825 | are added after entering every command (so a command executed |
|
826 | are added after entering every command (so a command executed | |
826 | in another IPython session is immediately available in other IPython |
|
827 | in another IPython session is immediately available in other IPython | |
827 | sessions that are open). |
|
828 | sessions that are open). | |
828 |
|
829 | |||
829 | To conserve space, a command can exist in shadow history only once - it doesn't |
|
830 | To conserve space, a command can exist in shadow history only once - it doesn't | |
830 | make sense to store a common line like "cd .." a thousand times. The idea is |
|
831 | make sense to store a common line like "cd .." a thousand times. The idea is | |
831 | mainly to provide a reliable place where valuable, hard-to-remember commands can |
|
832 | mainly to provide a reliable place where valuable, hard-to-remember commands can | |
832 | always be retrieved, as opposed to providing an exact sequence of commands |
|
833 | always be retrieved, as opposed to providing an exact sequence of commands | |
833 | you have entered in actual order. |
|
834 | you have entered in actual order. | |
834 |
|
835 | |||
835 | Because shadow history has all the commands you have ever executed, |
|
836 | Because shadow history has all the commands you have ever executed, | |
836 | time taken by %hist -g will increase oven time. If it ever starts to take |
|
837 | time taken by %hist -g will increase oven time. If it ever starts to take | |
837 | too long (or it ends up containing sensitive information like passwords), |
|
838 | too long (or it ends up containing sensitive information like passwords), | |
838 | clear the shadow history by `%clear shadow_nuke`. |
|
839 | clear the shadow history by `%clear shadow_nuke`. | |
839 |
|
840 | |||
840 | Time taken to add entries to shadow history should be negligible, but |
|
841 | Time taken to add entries to shadow history should be negligible, but | |
841 | in any case, if you start noticing performance degradation after using |
|
842 | in any case, if you start noticing performance degradation after using | |
842 | IPython for a long time (or running a script that floods the shadow history!), |
|
843 | IPython for a long time (or running a script that floods the shadow history!), | |
843 | you can 'compress' the shadow history by executing |
|
844 | you can 'compress' the shadow history by executing | |
844 | `%clear shadow_compress`. In practice, this should never be necessary |
|
845 | `%clear shadow_compress`. In practice, this should never be necessary | |
845 | in normal use. |
|
846 | in normal use. | |
846 |
|
847 | |||
847 | .. _output_caching: |
|
848 | .. _output_caching: | |
848 |
|
849 | |||
849 | Output caching system |
|
850 | Output caching system | |
850 | --------------------- |
|
851 | --------------------- | |
851 |
|
852 | |||
852 | For output that is returned from actions, a system similar to the input |
|
853 | For output that is returned from actions, a system similar to the input | |
853 | cache exists but using _ instead of _i. Only actions that produce a |
|
854 | cache exists but using _ instead of _i. Only actions that produce a | |
854 | result (NOT assignments, for example) are cached. If you are familiar |
|
855 | result (NOT assignments, for example) are cached. If you are familiar | |
855 | with Mathematica, IPython's _ variables behave exactly like |
|
856 | with Mathematica, IPython's _ variables behave exactly like | |
856 | Mathematica's % variables. |
|
857 | Mathematica's % variables. | |
857 |
|
858 | |||
858 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
859 | The following GLOBAL variables always exist (so don't overwrite them!): | |
859 |
|
860 | |||
860 | * [_] (a single underscore) : stores previous output, like Python's |
|
861 | * [_] (a single underscore) : stores previous output, like Python's | |
861 | default interpreter. |
|
862 | default interpreter. | |
862 | * [__] (two underscores): next previous. |
|
863 | * [__] (two underscores): next previous. | |
863 | * [___] (three underscores): next-next previous. |
|
864 | * [___] (three underscores): next-next previous. | |
864 |
|
865 | |||
865 | Additionally, global variables named _<n> are dynamically created (<n> |
|
866 | Additionally, global variables named _<n> are dynamically created (<n> | |
866 | being the prompt counter), such that the result of output <n> is always |
|
867 | being the prompt counter), such that the result of output <n> is always | |
867 | available as _<n> (don't use the angle brackets, just the number, e.g. |
|
868 | available as _<n> (don't use the angle brackets, just the number, e.g. | |
868 | _21). |
|
869 | _21). | |
869 |
|
870 | |||
870 | These global variables are all stored in a global dictionary (not a |
|
871 | These global variables are all stored in a global dictionary (not a | |
871 | list, since it only has entries for lines which returned a result) |
|
872 | list, since it only has entries for lines which returned a result) | |
872 | available under the names _oh and Out (similar to _ih and In). So the |
|
873 | available under the names _oh and Out (similar to _ih and In). So the | |
873 | output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you |
|
874 | output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you | |
874 | accidentally overwrite the Out variable you can recover it by typing |
|
875 | accidentally overwrite the Out variable you can recover it by typing | |
875 | 'Out=_oh' at the prompt. |
|
876 | 'Out=_oh' at the prompt. | |
876 |
|
877 | |||
877 | This system obviously can potentially put heavy memory demands on your |
|
878 | This system obviously can potentially put heavy memory demands on your | |
878 | system, since it prevents Python's garbage collector from removing any |
|
879 | system, since it prevents Python's garbage collector from removing any | |
879 | previously computed results. You can control how many results are kept |
|
880 | previously computed results. You can control how many results are kept | |
880 | in memory with the option (at the command line or in your ipythonrc |
|
881 | in memory with the option (at the command line or in your ipythonrc | |
881 | file) cache_size. If you set it to 0, the whole system is completely |
|
882 | file) cache_size. If you set it to 0, the whole system is completely | |
882 | disabled and the prompts revert to the classic '>>>' of normal Python. |
|
883 | disabled and the prompts revert to the classic '>>>' of normal Python. | |
883 |
|
884 | |||
884 |
|
885 | |||
885 | Directory history |
|
886 | Directory history | |
886 | ----------------- |
|
887 | ----------------- | |
887 |
|
888 | |||
888 | Your history of visited directories is kept in the global list _dh, and |
|
889 | Your history of visited directories is kept in the global list _dh, and | |
889 | the magic %cd command can be used to go to any entry in that list. The |
|
890 | the magic %cd command can be used to go to any entry in that list. The | |
890 | %dhist command allows you to view this history. Do ``cd -<TAB`` to |
|
891 | %dhist command allows you to view this history. Do ``cd -<TAB`` to | |
891 | conventiently view the directory history. |
|
892 | conventiently view the directory history. | |
892 |
|
893 | |||
893 |
|
894 | |||
894 | Automatic parentheses and quotes |
|
895 | Automatic parentheses and quotes | |
895 | -------------------------------- |
|
896 | -------------------------------- | |
896 |
|
897 | |||
897 | These features were adapted from Nathan Gray's LazyPython. They are |
|
898 | These features were adapted from Nathan Gray's LazyPython. They are | |
898 | meant to allow less typing for common situations. |
|
899 | meant to allow less typing for common situations. | |
899 |
|
900 | |||
900 |
|
901 | |||
901 | Automatic parentheses |
|
902 | Automatic parentheses | |
902 | --------------------- |
|
903 | --------------------- | |
903 |
|
904 | |||
904 | Callable objects (i.e. functions, methods, etc) can be invoked like this |
|
905 | Callable objects (i.e. functions, methods, etc) can be invoked like this | |
905 | (notice the commas between the arguments):: |
|
906 | (notice the commas between the arguments):: | |
906 |
|
907 | |||
907 | >>> callable_ob arg1, arg2, arg3 |
|
908 | >>> callable_ob arg1, arg2, arg3 | |
908 |
|
909 | |||
909 | and the input will be translated to this:: |
|
910 | and the input will be translated to this:: | |
910 |
|
911 | |||
911 | -> callable_ob(arg1, arg2, arg3) |
|
912 | -> callable_ob(arg1, arg2, arg3) | |
912 |
|
913 | |||
913 | You can force automatic parentheses by using '/' as the first character |
|
914 | You can force automatic parentheses by using '/' as the first character | |
914 | of a line. For example:: |
|
915 | of a line. For example:: | |
915 |
|
916 | |||
916 | >>> /globals # becomes 'globals()' |
|
917 | >>> /globals # becomes 'globals()' | |
917 |
|
918 | |||
918 | Note that the '/' MUST be the first character on the line! This won't work:: |
|
919 | Note that the '/' MUST be the first character on the line! This won't work:: | |
919 |
|
920 | |||
920 | >>> print /globals # syntax error |
|
921 | >>> print /globals # syntax error | |
921 |
|
922 | |||
922 | In most cases the automatic algorithm should work, so you should rarely |
|
923 | In most cases the automatic algorithm should work, so you should rarely | |
923 | need to explicitly invoke /. One notable exception is if you are trying |
|
924 | need to explicitly invoke /. One notable exception is if you are trying | |
924 | to call a function with a list of tuples as arguments (the parenthesis |
|
925 | to call a function with a list of tuples as arguments (the parenthesis | |
925 | will confuse IPython):: |
|
926 | will confuse IPython):: | |
926 |
|
927 | |||
927 | In [1]: zip (1,2,3),(4,5,6) # won't work |
|
928 | In [1]: zip (1,2,3),(4,5,6) # won't work | |
928 |
|
929 | |||
929 | but this will work:: |
|
930 | but this will work:: | |
930 |
|
931 | |||
931 | In [2]: /zip (1,2,3),(4,5,6) |
|
932 | In [2]: /zip (1,2,3),(4,5,6) | |
932 | ---> zip ((1,2,3),(4,5,6)) |
|
933 | ---> zip ((1,2,3),(4,5,6)) | |
933 | Out[2]= [(1, 4), (2, 5), (3, 6)] |
|
934 | Out[2]= [(1, 4), (2, 5), (3, 6)] | |
934 |
|
935 | |||
935 | IPython tells you that it has altered your command line by displaying |
|
936 | IPython tells you that it has altered your command line by displaying | |
936 | the new command line preceded by ->. e.g.:: |
|
937 | the new command line preceded by ->. e.g.:: | |
937 |
|
938 | |||
938 | In [18]: callable list |
|
939 | In [18]: callable list | |
939 | ----> callable (list) |
|
940 | ----> callable (list) | |
940 |
|
941 | |||
941 |
|
942 | |||
942 | Automatic quoting |
|
943 | Automatic quoting | |
943 | ----------------- |
|
944 | ----------------- | |
944 |
|
945 | |||
945 | You can force automatic quoting of a function's arguments by using ',' |
|
946 | You can force automatic quoting of a function's arguments by using ',' | |
946 | or ';' as the first character of a line. For example:: |
|
947 | or ';' as the first character of a line. For example:: | |
947 |
|
948 | |||
948 | >>> ,my_function /home/me # becomes my_function("/home/me") |
|
949 | >>> ,my_function /home/me # becomes my_function("/home/me") | |
949 |
|
950 | |||
950 | If you use ';' instead, the whole argument is quoted as a single string |
|
951 | If you use ';' instead, the whole argument is quoted as a single string | |
951 | (while ',' splits on whitespace):: |
|
952 | (while ',' splits on whitespace):: | |
952 |
|
953 | |||
953 | >>> ,my_function a b c # becomes my_function("a","b","c") |
|
954 | >>> ,my_function a b c # becomes my_function("a","b","c") | |
954 |
|
955 | |||
955 | >>> ;my_function a b c # becomes my_function("a b c") |
|
956 | >>> ;my_function a b c # becomes my_function("a b c") | |
956 |
|
957 | |||
957 | Note that the ',' or ';' MUST be the first character on the line! This |
|
958 | Note that the ',' or ';' MUST be the first character on the line! This | |
958 | won't work:: |
|
959 | won't work:: | |
959 |
|
960 | |||
960 | >>> x = ,my_function /home/me # syntax error |
|
961 | >>> x = ,my_function /home/me # syntax error | |
961 |
|
962 | |||
962 | IPython as your default Python environment |
|
963 | IPython as your default Python environment | |
963 | ========================================== |
|
964 | ========================================== | |
964 |
|
965 | |||
965 | Python honors the environment variable PYTHONSTARTUP and will execute at |
|
966 | Python honors the environment variable PYTHONSTARTUP and will execute at | |
966 | startup the file referenced by this variable. If you put at the end of |
|
967 | startup the file referenced by this variable. If you put at the end of | |
967 | this file the following two lines of code:: |
|
968 | this file the following two lines of code:: | |
968 |
|
969 | |||
969 | import IPython |
|
970 | import IPython | |
970 | IPython.Shell.IPShell().mainloop(sys_exit=1) |
|
971 | IPython.Shell.IPShell().mainloop(sys_exit=1) | |
971 |
|
972 | |||
972 | then IPython will be your working environment anytime you start Python. |
|
973 | then IPython will be your working environment anytime you start Python. | |
973 | The sys_exit=1 is needed to have IPython issue a call to sys.exit() when |
|
974 | The sys_exit=1 is needed to have IPython issue a call to sys.exit() when | |
974 | it finishes, otherwise you'll be back at the normal Python '>>>' |
|
975 | it finishes, otherwise you'll be back at the normal Python '>>>' | |
975 | prompt. |
|
976 | prompt. | |
976 |
|
977 | |||
977 | This is probably useful to developers who manage multiple Python |
|
978 | This is probably useful to developers who manage multiple Python | |
978 | versions and don't want to have correspondingly multiple IPython |
|
979 | versions and don't want to have correspondingly multiple IPython | |
979 | versions. Note that in this mode, there is no way to pass IPython any |
|
980 | versions. Note that in this mode, there is no way to pass IPython any | |
980 | command-line options, as those are trapped first by Python itself. |
|
981 | command-line options, as those are trapped first by Python itself. | |
981 |
|
982 | |||
982 | .. _Embedding: |
|
983 | .. _Embedding: | |
983 |
|
984 | |||
984 | Embedding IPython |
|
985 | Embedding IPython | |
985 | ================= |
|
986 | ================= | |
986 |
|
987 | |||
987 | It is possible to start an IPython instance inside your own Python |
|
988 | It is possible to start an IPython instance inside your own Python | |
988 | programs. This allows you to evaluate dynamically the state of your |
|
989 | programs. This allows you to evaluate dynamically the state of your | |
989 | code, operate with your variables, analyze them, etc. Note however that |
|
990 | code, operate with your variables, analyze them, etc. Note however that | |
990 | any changes you make to values while in the shell do not propagate back |
|
991 | any changes you make to values while in the shell do not propagate back | |
991 | to the running code, so it is safe to modify your values because you |
|
992 | to the running code, so it is safe to modify your values because you | |
992 | won't break your code in bizarre ways by doing so. |
|
993 | won't break your code in bizarre ways by doing so. | |
993 |
|
994 | |||
994 | This feature allows you to easily have a fully functional python |
|
995 | This feature allows you to easily have a fully functional python | |
995 | environment for doing object introspection anywhere in your code with a |
|
996 | environment for doing object introspection anywhere in your code with a | |
996 | simple function call. In some cases a simple print statement is enough, |
|
997 | simple function call. In some cases a simple print statement is enough, | |
997 | but if you need to do more detailed analysis of a code fragment this |
|
998 | but if you need to do more detailed analysis of a code fragment this | |
998 | feature can be very valuable. |
|
999 | feature can be very valuable. | |
999 |
|
1000 | |||
1000 | It can also be useful in scientific computing situations where it is |
|
1001 | It can also be useful in scientific computing situations where it is | |
1001 | common to need to do some automatic, computationally intensive part and |
|
1002 | common to need to do some automatic, computationally intensive part and | |
1002 | then stop to look at data, plots, etc. |
|
1003 | then stop to look at data, plots, etc. | |
1003 | Opening an IPython instance will give you full access to your data and |
|
1004 | Opening an IPython instance will give you full access to your data and | |
1004 | functions, and you can resume program execution once you are done with |
|
1005 | functions, and you can resume program execution once you are done with | |
1005 | the interactive part (perhaps to stop again later, as many times as |
|
1006 | the interactive part (perhaps to stop again later, as many times as | |
1006 | needed). |
|
1007 | needed). | |
1007 |
|
1008 | |||
1008 | The following code snippet is the bare minimum you need to include in |
|
1009 | The following code snippet is the bare minimum you need to include in | |
1009 | your Python programs for this to work (detailed examples follow later):: |
|
1010 | your Python programs for this to work (detailed examples follow later):: | |
1010 |
|
1011 | |||
1011 | from IPython.Shell import IPShellEmbed |
|
1012 | from IPython.Shell import IPShellEmbed | |
1012 |
|
1013 | |||
1013 | ipshell = IPShellEmbed() |
|
1014 | ipshell = IPShellEmbed() | |
1014 |
|
1015 | |||
1015 | ipshell() # this call anywhere in your program will start IPython |
|
1016 | ipshell() # this call anywhere in your program will start IPython | |
1016 |
|
1017 | |||
1017 | You can run embedded instances even in code which is itself being run at |
|
1018 | You can run embedded instances even in code which is itself being run at | |
1018 | the IPython interactive prompt with '%run <filename>'. Since it's easy |
|
1019 | the IPython interactive prompt with '%run <filename>'. Since it's easy | |
1019 | to get lost as to where you are (in your top-level IPython or in your |
|
1020 | to get lost as to where you are (in your top-level IPython or in your | |
1020 | embedded one), it's a good idea in such cases to set the in/out prompts |
|
1021 | embedded one), it's a good idea in such cases to set the in/out prompts | |
1021 | to something different for the embedded instances. The code examples |
|
1022 | to something different for the embedded instances. The code examples | |
1022 | below illustrate this. |
|
1023 | below illustrate this. | |
1023 |
|
1024 | |||
1024 | You can also have multiple IPython instances in your program and open |
|
1025 | You can also have multiple IPython instances in your program and open | |
1025 | them separately, for example with different options for data |
|
1026 | them separately, for example with different options for data | |
1026 | presentation. If you close and open the same instance multiple times, |
|
1027 | presentation. If you close and open the same instance multiple times, | |
1027 | its prompt counters simply continue from each execution to the next. |
|
1028 | its prompt counters simply continue from each execution to the next. | |
1028 |
|
1029 | |||
1029 | Please look at the docstrings in the Shell.py module for more details on |
|
1030 | Please look at the docstrings in the Shell.py module for more details on | |
1030 | the use of this system. |
|
1031 | the use of this system. | |
1031 |
|
1032 | |||
1032 | The following sample file illustrating how to use the embedding |
|
1033 | The following sample file illustrating how to use the embedding | |
1033 | functionality is provided in the examples directory as example-embed.py. |
|
1034 | functionality is provided in the examples directory as example-embed.py. | |
1034 | It should be fairly self-explanatory:: |
|
1035 | It should be fairly self-explanatory:: | |
1035 |
|
1036 | |||
1036 |
|
1037 | |||
1037 | #!/usr/bin/env python |
|
1038 | #!/usr/bin/env python | |
1038 |
|
1039 | |||
1039 | """An example of how to embed an IPython shell into a running program. |
|
1040 | """An example of how to embed an IPython shell into a running program. | |
1040 |
|
1041 | |||
1041 | Please see the documentation in the IPython.Shell module for more details. |
|
1042 | Please see the documentation in the IPython.Shell module for more details. | |
1042 |
|
1043 | |||
1043 | The accompanying file example-embed-short.py has quick code fragments for |
|
1044 | The accompanying file example-embed-short.py has quick code fragments for | |
1044 | embedding which you can cut and paste in your code once you understand how |
|
1045 | embedding which you can cut and paste in your code once you understand how | |
1045 | things work. |
|
1046 | things work. | |
1046 |
|
1047 | |||
1047 | The code in this file is deliberately extra-verbose, meant for learning.""" |
|
1048 | The code in this file is deliberately extra-verbose, meant for learning.""" | |
1048 |
|
1049 | |||
1049 | # The basics to get you going: |
|
1050 | # The basics to get you going: | |
1050 |
|
1051 | |||
1051 | # IPython sets the __IPYTHON__ variable so you can know if you have nested |
|
1052 | # IPython sets the __IPYTHON__ variable so you can know if you have nested | |
1052 | # copies running. |
|
1053 | # copies running. | |
1053 |
|
1054 | |||
1054 | # Try running this code both at the command line and from inside IPython (with |
|
1055 | # Try running this code both at the command line and from inside IPython (with | |
1055 | # %run example-embed.py) |
|
1056 | # %run example-embed.py) | |
1056 | try: |
|
1057 | try: | |
1057 | __IPYTHON__ |
|
1058 | __IPYTHON__ | |
1058 | except NameError: |
|
1059 | except NameError: | |
1059 | nested = 0 |
|
1060 | nested = 0 | |
1060 | args = [''] |
|
1061 | args = [''] | |
1061 | else: |
|
1062 | else: | |
1062 | print "Running nested copies of IPython." |
|
1063 | print "Running nested copies of IPython." | |
1063 | print "The prompts for the nested copy have been modified" |
|
1064 | print "The prompts for the nested copy have been modified" | |
1064 | nested = 1 |
|
1065 | nested = 1 | |
1065 | # what the embedded instance will see as sys.argv: |
|
1066 | # what the embedded instance will see as sys.argv: | |
1066 | args = ['-pi1','In <\\#>: ','-pi2',' .\\D.: ', |
|
1067 | args = ['-pi1','In <\\#>: ','-pi2',' .\\D.: ', | |
1067 | '-po','Out<\\#>: ','-nosep'] |
|
1068 | '-po','Out<\\#>: ','-nosep'] | |
1068 |
|
1069 | |||
1069 | # First import the embeddable shell class |
|
1070 | # First import the embeddable shell class | |
1070 | from IPython.Shell import IPShellEmbed |
|
1071 | from IPython.Shell import IPShellEmbed | |
1071 |
|
1072 | |||
1072 | # Now create an instance of the embeddable shell. The first argument is a |
|
1073 | # Now create an instance of the embeddable shell. The first argument is a | |
1073 | # string with options exactly as you would type them if you were starting |
|
1074 | # string with options exactly as you would type them if you were starting | |
1074 | # IPython at the system command line. Any parameters you want to define for |
|
1075 | # IPython at the system command line. Any parameters you want to define for | |
1075 | # configuration can thus be specified here. |
|
1076 | # configuration can thus be specified here. | |
1076 | ipshell = IPShellEmbed(args, |
|
1077 | ipshell = IPShellEmbed(args, | |
1077 | banner = 'Dropping into IPython', |
|
1078 | banner = 'Dropping into IPython', | |
1078 | exit_msg = 'Leaving Interpreter, back to program.') |
|
1079 | exit_msg = 'Leaving Interpreter, back to program.') | |
1079 |
|
1080 | |||
1080 | # Make a second instance, you can have as many as you want. |
|
1081 | # Make a second instance, you can have as many as you want. | |
1081 | if nested: |
|
1082 | if nested: | |
1082 | args[1] = 'In2<\\#>' |
|
1083 | args[1] = 'In2<\\#>' | |
1083 | else: |
|
1084 | else: | |
1084 | args = ['-pi1','In2<\\#>: ','-pi2',' .\\D.: ', |
|
1085 | args = ['-pi1','In2<\\#>: ','-pi2',' .\\D.: ', | |
1085 | '-po','Out<\\#>: ','-nosep'] |
|
1086 | '-po','Out<\\#>: ','-nosep'] | |
1086 | ipshell2 = IPShellEmbed(args,banner = 'Second IPython instance.') |
|
1087 | ipshell2 = IPShellEmbed(args,banner = 'Second IPython instance.') | |
1087 |
|
1088 | |||
1088 | print '\nHello. This is printed from the main controller program.\n' |
|
1089 | print '\nHello. This is printed from the main controller program.\n' | |
1089 |
|
1090 | |||
1090 | # You can then call ipshell() anywhere you need it (with an optional |
|
1091 | # You can then call ipshell() anywhere you need it (with an optional | |
1091 | # message): |
|
1092 | # message): | |
1092 | ipshell('***Called from top level. ' |
|
1093 | ipshell('***Called from top level. ' | |
1093 | 'Hit Ctrl-D to exit interpreter and continue program.\n' |
|
1094 | 'Hit Ctrl-D to exit interpreter and continue program.\n' | |
1094 | 'Note that if you use %kill_embedded, you can fully deactivate\n' |
|
1095 | 'Note that if you use %kill_embedded, you can fully deactivate\n' | |
1095 | 'This embedded instance so it will never turn on again') |
|
1096 | 'This embedded instance so it will never turn on again') | |
1096 |
|
1097 | |||
1097 | print '\nBack in caller program, moving along...\n' |
|
1098 | print '\nBack in caller program, moving along...\n' | |
1098 |
|
1099 | |||
1099 | #--------------------------------------------------------------------------- |
|
1100 | #--------------------------------------------------------------------------- | |
1100 | # More details: |
|
1101 | # More details: | |
1101 |
|
1102 | |||
1102 | # IPShellEmbed instances don't print the standard system banner and |
|
1103 | # IPShellEmbed instances don't print the standard system banner and | |
1103 | # messages. The IPython banner (which actually may contain initialization |
|
1104 | # messages. The IPython banner (which actually may contain initialization | |
1104 | # messages) is available as <instance>.IP.BANNER in case you want it. |
|
1105 | # messages) is available as <instance>.IP.BANNER in case you want it. | |
1105 |
|
1106 | |||
1106 | # IPShellEmbed instances print the following information everytime they |
|
1107 | # IPShellEmbed instances print the following information everytime they | |
1107 | # start: |
|
1108 | # start: | |
1108 |
|
1109 | |||
1109 | # - A global startup banner. |
|
1110 | # - A global startup banner. | |
1110 |
|
1111 | |||
1111 | # - A call-specific header string, which you can use to indicate where in the |
|
1112 | # - A call-specific header string, which you can use to indicate where in the | |
1112 | # execution flow the shell is starting. |
|
1113 | # execution flow the shell is starting. | |
1113 |
|
1114 | |||
1114 | # They also print an exit message every time they exit. |
|
1115 | # They also print an exit message every time they exit. | |
1115 |
|
1116 | |||
1116 | # Both the startup banner and the exit message default to None, and can be set |
|
1117 | # Both the startup banner and the exit message default to None, and can be set | |
1117 | # either at the instance constructor or at any other time with the |
|
1118 | # either at the instance constructor or at any other time with the | |
1118 | # set_banner() and set_exit_msg() methods. |
|
1119 | # set_banner() and set_exit_msg() methods. | |
1119 |
|
1120 | |||
1120 | # The shell instance can be also put in 'dummy' mode globally or on a per-call |
|
1121 | # The shell instance can be also put in 'dummy' mode globally or on a per-call | |
1121 | # basis. This gives you fine control for debugging without having to change |
|
1122 | # basis. This gives you fine control for debugging without having to change | |
1122 | # code all over the place. |
|
1123 | # code all over the place. | |
1123 |
|
1124 | |||
1124 | # The code below illustrates all this. |
|
1125 | # The code below illustrates all this. | |
1125 |
|
1126 | |||
1126 |
|
1127 | |||
1127 | # This is how the global banner and exit_msg can be reset at any point |
|
1128 | # This is how the global banner and exit_msg can be reset at any point | |
1128 | ipshell.set_banner('Entering interpreter - New Banner') |
|
1129 | ipshell.set_banner('Entering interpreter - New Banner') | |
1129 | ipshell.set_exit_msg('Leaving interpreter - New exit_msg') |
|
1130 | ipshell.set_exit_msg('Leaving interpreter - New exit_msg') | |
1130 |
|
1131 | |||
1131 | def foo(m): |
|
1132 | def foo(m): | |
1132 | s = 'spam' |
|
1133 | s = 'spam' | |
1133 | ipshell('***In foo(). Try @whos, or print s or m:') |
|
1134 | ipshell('***In foo(). Try @whos, or print s or m:') | |
1134 | print 'foo says m = ',m |
|
1135 | print 'foo says m = ',m | |
1135 |
|
1136 | |||
1136 | def bar(n): |
|
1137 | def bar(n): | |
1137 | s = 'eggs' |
|
1138 | s = 'eggs' | |
1138 | ipshell('***In bar(). Try @whos, or print s or n:') |
|
1139 | ipshell('***In bar(). Try @whos, or print s or n:') | |
1139 | print 'bar says n = ',n |
|
1140 | print 'bar says n = ',n | |
1140 |
|
1141 | |||
1141 | # Some calls to the above functions which will trigger IPython: |
|
1142 | # Some calls to the above functions which will trigger IPython: | |
1142 | print 'Main program calling foo("eggs")\n' |
|
1143 | print 'Main program calling foo("eggs")\n' | |
1143 | foo('eggs') |
|
1144 | foo('eggs') | |
1144 |
|
1145 | |||
1145 | # The shell can be put in 'dummy' mode where calls to it silently return. This |
|
1146 | # The shell can be put in 'dummy' mode where calls to it silently return. This | |
1146 | # allows you, for example, to globally turn off debugging for a program with a |
|
1147 | # allows you, for example, to globally turn off debugging for a program with a | |
1147 | # single call. |
|
1148 | # single call. | |
1148 | ipshell.set_dummy_mode(1) |
|
1149 | ipshell.set_dummy_mode(1) | |
1149 | print '\nTrying to call IPython which is now "dummy":' |
|
1150 | print '\nTrying to call IPython which is now "dummy":' | |
1150 | ipshell() |
|
1151 | ipshell() | |
1151 | print 'Nothing happened...' |
|
1152 | print 'Nothing happened...' | |
1152 | # The global 'dummy' mode can still be overridden for a single call |
|
1153 | # The global 'dummy' mode can still be overridden for a single call | |
1153 | print '\nOverriding dummy mode manually:' |
|
1154 | print '\nOverriding dummy mode manually:' | |
1154 | ipshell(dummy=0) |
|
1155 | ipshell(dummy=0) | |
1155 |
|
1156 | |||
1156 | # Reactivate the IPython shell |
|
1157 | # Reactivate the IPython shell | |
1157 | ipshell.set_dummy_mode(0) |
|
1158 | ipshell.set_dummy_mode(0) | |
1158 |
|
1159 | |||
1159 | print 'You can even have multiple embedded instances:' |
|
1160 | print 'You can even have multiple embedded instances:' | |
1160 | ipshell2() |
|
1161 | ipshell2() | |
1161 |
|
1162 | |||
1162 | print '\nMain program calling bar("spam")\n' |
|
1163 | print '\nMain program calling bar("spam")\n' | |
1163 | bar('spam') |
|
1164 | bar('spam') | |
1164 |
|
1165 | |||
1165 | print 'Main program finished. Bye!' |
|
1166 | print 'Main program finished. Bye!' | |
1166 |
|
1167 | |||
1167 | #********************** End of file <example-embed.py> *********************** |
|
1168 | #********************** End of file <example-embed.py> *********************** | |
1168 |
|
1169 | |||
1169 | Once you understand how the system functions, you can use the following |
|
1170 | Once you understand how the system functions, you can use the following | |
1170 | code fragments in your programs which are ready for cut and paste:: |
|
1171 | code fragments in your programs which are ready for cut and paste:: | |
1171 |
|
1172 | |||
1172 |
|
1173 | |||
1173 | """Quick code snippets for embedding IPython into other programs. |
|
1174 | """Quick code snippets for embedding IPython into other programs. | |
1174 |
|
1175 | |||
1175 | See example-embed.py for full details, this file has the bare minimum code for |
|
1176 | See example-embed.py for full details, this file has the bare minimum code for | |
1176 | cut and paste use once you understand how to use the system.""" |
|
1177 | cut and paste use once you understand how to use the system.""" | |
1177 |
|
1178 | |||
1178 | #--------------------------------------------------------------------------- |
|
1179 | #--------------------------------------------------------------------------- | |
1179 | # This code loads IPython but modifies a few things if it detects it's running |
|
1180 | # This code loads IPython but modifies a few things if it detects it's running | |
1180 | # embedded in another IPython session (helps avoid confusion) |
|
1181 | # embedded in another IPython session (helps avoid confusion) | |
1181 |
|
1182 | |||
1182 | try: |
|
1183 | try: | |
1183 | __IPYTHON__ |
|
1184 | __IPYTHON__ | |
1184 | except NameError: |
|
1185 | except NameError: | |
1185 | argv = [''] |
|
1186 | argv = [''] | |
1186 | banner = exit_msg = '' |
|
1187 | banner = exit_msg = '' | |
1187 | else: |
|
1188 | else: | |
1188 | # Command-line options for IPython (a list like sys.argv) |
|
1189 | # Command-line options for IPython (a list like sys.argv) | |
1189 | argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:'] |
|
1190 | argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:'] | |
1190 | banner = '*** Nested interpreter ***' |
|
1191 | banner = '*** Nested interpreter ***' | |
1191 | exit_msg = '*** Back in main IPython ***' |
|
1192 | exit_msg = '*** Back in main IPython ***' | |
1192 |
|
1193 | |||
1193 | # First import the embeddable shell class |
|
1194 | # First import the embeddable shell class | |
1194 | from IPython.Shell import IPShellEmbed |
|
1195 | from IPython.Shell import IPShellEmbed | |
1195 | # Now create the IPython shell instance. Put ipshell() anywhere in your code |
|
1196 | # Now create the IPython shell instance. Put ipshell() anywhere in your code | |
1196 | # where you want it to open. |
|
1197 | # where you want it to open. | |
1197 | ipshell = IPShellEmbed(argv,banner=banner,exit_msg=exit_msg) |
|
1198 | ipshell = IPShellEmbed(argv,banner=banner,exit_msg=exit_msg) | |
1198 |
|
1199 | |||
1199 | #--------------------------------------------------------------------------- |
|
1200 | #--------------------------------------------------------------------------- | |
1200 | # This code will load an embeddable IPython shell always with no changes for |
|
1201 | # This code will load an embeddable IPython shell always with no changes for | |
1201 | # nested embededings. |
|
1202 | # nested embededings. | |
1202 |
|
1203 | |||
1203 | from IPython.Shell import IPShellEmbed |
|
1204 | from IPython.Shell import IPShellEmbed | |
1204 | ipshell = IPShellEmbed() |
|
1205 | ipshell = IPShellEmbed() | |
1205 | # Now ipshell() will open IPython anywhere in the code. |
|
1206 | # Now ipshell() will open IPython anywhere in the code. | |
1206 |
|
1207 | |||
1207 | #--------------------------------------------------------------------------- |
|
1208 | #--------------------------------------------------------------------------- | |
1208 | # This code loads an embeddable shell only if NOT running inside |
|
1209 | # This code loads an embeddable shell only if NOT running inside | |
1209 | # IPython. Inside IPython, the embeddable shell variable ipshell is just a |
|
1210 | # IPython. Inside IPython, the embeddable shell variable ipshell is just a | |
1210 | # dummy function. |
|
1211 | # dummy function. | |
1211 |
|
1212 | |||
1212 | try: |
|
1213 | try: | |
1213 | __IPYTHON__ |
|
1214 | __IPYTHON__ | |
1214 | except NameError: |
|
1215 | except NameError: | |
1215 | from IPython.Shell import IPShellEmbed |
|
1216 | from IPython.Shell import IPShellEmbed | |
1216 | ipshell = IPShellEmbed() |
|
1217 | ipshell = IPShellEmbed() | |
1217 | # Now ipshell() will open IPython anywhere in the code |
|
1218 | # Now ipshell() will open IPython anywhere in the code | |
1218 | else: |
|
1219 | else: | |
1219 | # Define a dummy ipshell() so the same code doesn't crash inside an |
|
1220 | # Define a dummy ipshell() so the same code doesn't crash inside an | |
1220 | # interactive IPython |
|
1221 | # interactive IPython | |
1221 | def ipshell(): pass |
|
1222 | def ipshell(): pass | |
1222 |
|
1223 | |||
1223 | #******************* End of file <example-embed-short.py> ******************** |
|
1224 | #******************* End of file <example-embed-short.py> ******************** | |
1224 |
|
1225 | |||
1225 | Using the Python debugger (pdb) |
|
1226 | Using the Python debugger (pdb) | |
1226 | =============================== |
|
1227 | =============================== | |
1227 |
|
1228 | |||
1228 | Running entire programs via pdb |
|
1229 | Running entire programs via pdb | |
1229 | ------------------------------- |
|
1230 | ------------------------------- | |
1230 |
|
1231 | |||
1231 | pdb, the Python debugger, is a powerful interactive debugger which |
|
1232 | pdb, the Python debugger, is a powerful interactive debugger which | |
1232 | allows you to step through code, set breakpoints, watch variables, |
|
1233 | allows you to step through code, set breakpoints, watch variables, | |
1233 | etc. IPython makes it very easy to start any script under the control |
|
1234 | etc. IPython makes it very easy to start any script under the control | |
1234 | of pdb, regardless of whether you have wrapped it into a 'main()' |
|
1235 | of pdb, regardless of whether you have wrapped it into a 'main()' | |
1235 | function or not. For this, simply type '%run -d myscript' at an |
|
1236 | function or not. For this, simply type '%run -d myscript' at an | |
1236 | IPython prompt. See the %run command's documentation (via '%run?' or |
|
1237 | IPython prompt. See the %run command's documentation (via '%run?' or | |
1237 | in Sec. magic_ for more details, including how to control where pdb |
|
1238 | in Sec. magic_ for more details, including how to control where pdb | |
1238 | will stop execution first. |
|
1239 | will stop execution first. | |
1239 |
|
1240 | |||
1240 | For more information on the use of the pdb debugger, read the included |
|
1241 | For more information on the use of the pdb debugger, read the included | |
1241 | pdb.doc file (part of the standard Python distribution). On a stock |
|
1242 | pdb.doc file (part of the standard Python distribution). On a stock | |
1242 | Linux system it is located at /usr/lib/python2.3/pdb.doc, but the |
|
1243 | Linux system it is located at /usr/lib/python2.3/pdb.doc, but the | |
1243 | easiest way to read it is by using the help() function of the pdb module |
|
1244 | easiest way to read it is by using the help() function of the pdb module | |
1244 | as follows (in an IPython prompt): |
|
1245 | as follows (in an IPython prompt): | |
1245 |
|
1246 | |||
1246 | In [1]: import pdb |
|
1247 | In [1]: import pdb | |
1247 | In [2]: pdb.help() |
|
1248 | In [2]: pdb.help() | |
1248 |
|
1249 | |||
1249 | This will load the pdb.doc document in a file viewer for you automatically. |
|
1250 | This will load the pdb.doc document in a file viewer for you automatically. | |
1250 |
|
1251 | |||
1251 |
|
1252 | |||
1252 | Automatic invocation of pdb on exceptions |
|
1253 | Automatic invocation of pdb on exceptions | |
1253 | ----------------------------------------- |
|
1254 | ----------------------------------------- | |
1254 |
|
1255 | |||
1255 | IPython, if started with the -pdb option (or if the option is set in |
|
1256 | IPython, if started with the -pdb option (or if the option is set in | |
1256 | your rc file) can call the Python pdb debugger every time your code |
|
1257 | your rc file) can call the Python pdb debugger every time your code | |
1257 | triggers an uncaught exception. This feature |
|
1258 | triggers an uncaught exception. This feature | |
1258 | can also be toggled at any time with the %pdb magic command. This can be |
|
1259 | can also be toggled at any time with the %pdb magic command. This can be | |
1259 | extremely useful in order to find the origin of subtle bugs, because pdb |
|
1260 | extremely useful in order to find the origin of subtle bugs, because pdb | |
1260 | opens up at the point in your code which triggered the exception, and |
|
1261 | opens up at the point in your code which triggered the exception, and | |
1261 | while your program is at this point 'dead', all the data is still |
|
1262 | while your program is at this point 'dead', all the data is still | |
1262 | available and you can walk up and down the stack frame and understand |
|
1263 | available and you can walk up and down the stack frame and understand | |
1263 | the origin of the problem. |
|
1264 | the origin of the problem. | |
1264 |
|
1265 | |||
1265 | Furthermore, you can use these debugging facilities both with the |
|
1266 | Furthermore, you can use these debugging facilities both with the | |
1266 | embedded IPython mode and without IPython at all. For an embedded shell |
|
1267 | embedded IPython mode and without IPython at all. For an embedded shell | |
1267 | (see sec. Embedding_), simply call the constructor with |
|
1268 | (see sec. Embedding_), simply call the constructor with | |
1268 | '-pdb' in the argument string and automatically pdb will be called if an |
|
1269 | '-pdb' in the argument string and automatically pdb will be called if an | |
1269 | uncaught exception is triggered by your code. |
|
1270 | uncaught exception is triggered by your code. | |
1270 |
|
1271 | |||
1271 | For stand-alone use of the feature in your programs which do not use |
|
1272 | For stand-alone use of the feature in your programs which do not use | |
1272 | IPython at all, put the following lines toward the top of your 'main' |
|
1273 | IPython at all, put the following lines toward the top of your 'main' | |
1273 | routine:: |
|
1274 | routine:: | |
1274 |
|
1275 | |||
1275 | import sys |
|
1276 | import sys | |
1276 | from IPython.core import ultratb |
|
1277 | from IPython.core import ultratb | |
1277 | sys.excepthook = ultratb.FormattedTB(mode='Verbose', |
|
1278 | sys.excepthook = ultratb.FormattedTB(mode='Verbose', | |
1278 | color_scheme='Linux', call_pdb=1) |
|
1279 | color_scheme='Linux', call_pdb=1) | |
1279 |
|
1280 | |||
1280 | The mode keyword can be either 'Verbose' or 'Plain', giving either very |
|
1281 | The mode keyword can be either 'Verbose' or 'Plain', giving either very | |
1281 | detailed or normal tracebacks respectively. The color_scheme keyword can |
|
1282 | detailed or normal tracebacks respectively. The color_scheme keyword can | |
1282 | be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same |
|
1283 | be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same | |
1283 | options which can be set in IPython with -colors and -xmode. |
|
1284 | options which can be set in IPython with -colors and -xmode. | |
1284 |
|
1285 | |||
1285 | This will give any of your programs detailed, colored tracebacks with |
|
1286 | This will give any of your programs detailed, colored tracebacks with | |
1286 | automatic invocation of pdb. |
|
1287 | automatic invocation of pdb. | |
1287 |
|
1288 | |||
1288 |
|
1289 | |||
1289 | Extensions for syntax processing |
|
1290 | Extensions for syntax processing | |
1290 | ================================ |
|
1291 | ================================ | |
1291 |
|
1292 | |||
1292 | This isn't for the faint of heart, because the potential for breaking |
|
1293 | This isn't for the faint of heart, because the potential for breaking | |
1293 | things is quite high. But it can be a very powerful and useful feature. |
|
1294 | things is quite high. But it can be a very powerful and useful feature. | |
1294 | In a nutshell, you can redefine the way IPython processes the user input |
|
1295 | In a nutshell, you can redefine the way IPython processes the user input | |
1295 | line to accept new, special extensions to the syntax without needing to |
|
1296 | line to accept new, special extensions to the syntax without needing to | |
1296 | change any of IPython's own code. |
|
1297 | change any of IPython's own code. | |
1297 |
|
1298 | |||
1298 | In the IPython/extensions directory you will find some examples |
|
1299 | In the IPython/extensions directory you will find some examples | |
1299 | supplied, which we will briefly describe now. These can be used 'as is' |
|
1300 | supplied, which we will briefly describe now. These can be used 'as is' | |
1300 | (and both provide very useful functionality), or you can use them as a |
|
1301 | (and both provide very useful functionality), or you can use them as a | |
1301 | starting point for writing your own extensions. |
|
1302 | starting point for writing your own extensions. | |
1302 |
|
1303 | |||
1303 |
|
1304 | |||
1304 | Pasting of code starting with '>>> ' or '... ' |
|
1305 | Pasting of code starting with '>>> ' or '... ' | |
1305 | ---------------------------------------------- |
|
1306 | ---------------------------------------------- | |
1306 |
|
1307 | |||
1307 | In the python tutorial it is common to find code examples which have |
|
1308 | In the python tutorial it is common to find code examples which have | |
1308 | been taken from real python sessions. The problem with those is that all |
|
1309 | been taken from real python sessions. The problem with those is that all | |
1309 | the lines begin with either '>>> ' or '... ', which makes it impossible |
|
1310 | the lines begin with either '>>> ' or '... ', which makes it impossible | |
1310 | to paste them all at once. One must instead do a line by line manual |
|
1311 | to paste them all at once. One must instead do a line by line manual | |
1311 | copying, carefully removing the leading extraneous characters. |
|
1312 | copying, carefully removing the leading extraneous characters. | |
1312 |
|
1313 | |||
1313 | This extension identifies those starting characters and removes them |
|
1314 | This extension identifies those starting characters and removes them | |
1314 | from the input automatically, so that one can paste multi-line examples |
|
1315 | from the input automatically, so that one can paste multi-line examples | |
1315 | directly into IPython, saving a lot of time. Please look at the file |
|
1316 | directly into IPython, saving a lot of time. Please look at the file | |
1316 | InterpreterPasteInput.py in the IPython/extensions directory for details |
|
1317 | InterpreterPasteInput.py in the IPython/extensions directory for details | |
1317 | on how this is done. |
|
1318 | on how this is done. | |
1318 |
|
1319 | |||
1319 | IPython comes with a special profile enabling this feature, called |
|
1320 | IPython comes with a special profile enabling this feature, called | |
1320 | tutorial. Simply start IPython via 'ipython -p tutorial' and the feature |
|
1321 | tutorial. Simply start IPython via 'ipython -p tutorial' and the feature | |
1321 | will be available. In a normal IPython session you can activate the |
|
1322 | will be available. In a normal IPython session you can activate the | |
1322 | feature by importing the corresponding module with: |
|
1323 | feature by importing the corresponding module with: | |
1323 | In [1]: import IPython.extensions.InterpreterPasteInput |
|
1324 | In [1]: import IPython.extensions.InterpreterPasteInput | |
1324 |
|
1325 | |||
1325 | The following is a 'screenshot' of how things work when this extension |
|
1326 | The following is a 'screenshot' of how things work when this extension | |
1326 | is on, copying an example from the standard tutorial:: |
|
1327 | is on, copying an example from the standard tutorial:: | |
1327 |
|
1328 | |||
1328 | IPython profile: tutorial |
|
1329 | IPython profile: tutorial | |
1329 |
|
1330 | |||
1330 | *** Pasting of code with ">>>" or "..." has been enabled. |
|
1331 | *** Pasting of code with ">>>" or "..." has been enabled. | |
1331 |
|
1332 | |||
1332 | In [1]: >>> def fib2(n): # return Fibonacci series up to n |
|
1333 | In [1]: >>> def fib2(n): # return Fibonacci series up to n | |
1333 | ...: ... """Return a list containing the Fibonacci series up to |
|
1334 | ...: ... """Return a list containing the Fibonacci series up to | |
1334 | n.""" |
|
1335 | n.""" | |
1335 | ...: ... result = [] |
|
1336 | ...: ... result = [] | |
1336 | ...: ... a, b = 0, 1 |
|
1337 | ...: ... a, b = 0, 1 | |
1337 | ...: ... while b < n: |
|
1338 | ...: ... while b < n: | |
1338 | ...: ... result.append(b) # see below |
|
1339 | ...: ... result.append(b) # see below | |
1339 | ...: ... a, b = b, a+b |
|
1340 | ...: ... a, b = b, a+b | |
1340 | ...: ... return result |
|
1341 | ...: ... return result | |
1341 | ...: |
|
1342 | ...: | |
1342 |
|
1343 | |||
1343 | In [2]: fib2(10) |
|
1344 | In [2]: fib2(10) | |
1344 | Out[2]: [1, 1, 2, 3, 5, 8] |
|
1345 | Out[2]: [1, 1, 2, 3, 5, 8] | |
1345 |
|
1346 | |||
1346 | Note that as currently written, this extension does not recognize |
|
1347 | Note that as currently written, this extension does not recognize | |
1347 | IPython's prompts for pasting. Those are more complicated, since the |
|
1348 | IPython's prompts for pasting. Those are more complicated, since the | |
1348 | user can change them very easily, they involve numbers and can vary in |
|
1349 | user can change them very easily, they involve numbers and can vary in | |
1349 | length. One could however extract all the relevant information from the |
|
1350 | length. One could however extract all the relevant information from the | |
1350 | IPython instance and build an appropriate regular expression. This is |
|
1351 | IPython instance and build an appropriate regular expression. This is | |
1351 | left as an exercise for the reader. |
|
1352 | left as an exercise for the reader. | |
1352 |
|
1353 | |||
1353 |
|
1354 | |||
1354 | Input of physical quantities with units |
|
1355 | Input of physical quantities with units | |
1355 | --------------------------------------- |
|
1356 | --------------------------------------- | |
1356 |
|
1357 | |||
1357 | The module PhysicalQInput allows a simplified form of input for physical |
|
1358 | The module PhysicalQInput allows a simplified form of input for physical | |
1358 | quantities with units. This file is meant to be used in conjunction with |
|
1359 | quantities with units. This file is meant to be used in conjunction with | |
1359 | the PhysicalQInteractive module (in the same directory) and |
|
1360 | the PhysicalQInteractive module (in the same directory) and | |
1360 | Physics.PhysicalQuantities from Konrad Hinsen's ScientificPython |
|
1361 | Physics.PhysicalQuantities from Konrad Hinsen's ScientificPython | |
1361 | (http://dirac.cnrs-orleans.fr/ScientificPython/). |
|
1362 | (http://dirac.cnrs-orleans.fr/ScientificPython/). | |
1362 |
|
1363 | |||
1363 | The Physics.PhysicalQuantities module defines PhysicalQuantity objects, |
|
1364 | The Physics.PhysicalQuantities module defines PhysicalQuantity objects, | |
1364 | but these must be declared as instances of a class. For example, to |
|
1365 | but these must be declared as instances of a class. For example, to | |
1365 | define v as a velocity of 3 m/s, normally you would write:: |
|
1366 | define v as a velocity of 3 m/s, normally you would write:: | |
1366 |
|
1367 | |||
1367 | In [1]: v = PhysicalQuantity(3,'m/s') |
|
1368 | In [1]: v = PhysicalQuantity(3,'m/s') | |
1368 |
|
1369 | |||
1369 | Using the PhysicalQ_Input extension this can be input instead as: |
|
1370 | Using the PhysicalQ_Input extension this can be input instead as: | |
1370 | In [1]: v = 3 m/s |
|
1371 | In [1]: v = 3 m/s | |
1371 | which is much more convenient for interactive use (even though it is |
|
1372 | which is much more convenient for interactive use (even though it is | |
1372 | blatantly invalid Python syntax). |
|
1373 | blatantly invalid Python syntax). | |
1373 |
|
1374 | |||
1374 | The physics profile supplied with IPython (enabled via 'ipython -p |
|
1375 | The physics profile supplied with IPython (enabled via 'ipython -p | |
1375 | physics') uses these extensions, which you can also activate with: |
|
1376 | physics') uses these extensions, which you can also activate with: | |
1376 |
|
1377 | |||
1377 | from math import * # math MUST be imported BEFORE PhysicalQInteractive |
|
1378 | from math import * # math MUST be imported BEFORE PhysicalQInteractive | |
1378 | from IPython.extensions.PhysicalQInteractive import * |
|
1379 | from IPython.extensions.PhysicalQInteractive import * | |
1379 | import IPython.extensions.PhysicalQInput |
|
1380 | import IPython.extensions.PhysicalQInput | |
1380 |
|
1381 | |||
1381 | .. _gui_support: |
|
1382 | .. _gui_support: | |
1382 |
|
1383 | |||
1383 | GUI event loop support support |
|
1384 | GUI event loop support support | |
1384 | ============================== |
|
1385 | ============================== | |
1385 |
|
1386 | |||
1386 | .. versionadded:: 0.11 |
|
1387 | .. versionadded:: 0.11 | |
1387 | The ``%gui`` magic and :mod:`IPython.lib.inputhook`. |
|
1388 | The ``%gui`` magic and :mod:`IPython.lib.inputhook`. | |
1388 |
|
1389 | |||
1389 | IPython has excellent support for working interactively with Graphical User |
|
1390 | IPython has excellent support for working interactively with Graphical User | |
1390 | Interface (GUI) toolkits, such as wxPython, PyQt4, PyGTK and Tk. This is |
|
1391 | Interface (GUI) toolkits, such as wxPython, PyQt4, PyGTK and Tk. This is | |
1391 | implemented using Python's builtin ``PyOSInputHook`` hook. This implementation |
|
1392 | implemented using Python's builtin ``PyOSInputHook`` hook. This implementation | |
1392 | is extremely robust compared to our previous threaded based version. The |
|
1393 | is extremely robust compared to our previous threaded based version. The | |
1393 | advantages of this are: |
|
1394 | advantages of this are: | |
1394 |
|
1395 | |||
1395 | * GUIs can be enabled and disabled dynamically at runtime. |
|
1396 | * GUIs can be enabled and disabled dynamically at runtime. | |
1396 | * The active GUI can be switched dynamically at runtime. |
|
1397 | * The active GUI can be switched dynamically at runtime. | |
1397 | * In some cases, multiple GUIs can run simultaneously with no problems. |
|
1398 | * In some cases, multiple GUIs can run simultaneously with no problems. | |
1398 | * There is a developer API in :mod:`IPython.lib.inputhook` for customizing |
|
1399 | * There is a developer API in :mod:`IPython.lib.inputhook` for customizing | |
1399 | all of these things. |
|
1400 | all of these things. | |
1400 |
|
1401 | |||
1401 | For users, enabling GUI event loop integration is simple. You simple use the |
|
1402 | For users, enabling GUI event loop integration is simple. You simple use the | |
1402 | ``%gui`` magic as follows:: |
|
1403 | ``%gui`` magic as follows:: | |
1403 |
|
1404 | |||
1404 | %gui [-a] [GUINAME] |
|
1405 | %gui [-a] [GUINAME] | |
1405 |
|
1406 | |||
1406 | With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME`` |
|
1407 | With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME`` | |
1407 | arguments are ``wx``, ``qt4``, ``gtk`` and ``tk``. The ``-a`` option will |
|
1408 | arguments are ``wx``, ``qt4``, ``gtk`` and ``tk``. The ``-a`` option will | |
1408 | create and return a running application object for the selected GUI toolkit. |
|
1409 | create and return a running application object for the selected GUI toolkit. | |
1409 |
|
1410 | |||
1410 | Thus, to use wxPython interactively and create a running :class:`wx.App` |
|
1411 | Thus, to use wxPython interactively and create a running :class:`wx.App` | |
1411 | object, do:: |
|
1412 | object, do:: | |
1412 |
|
1413 | |||
1413 | %gui -a wx |
|
1414 | %gui -a wx | |
1414 |
|
1415 | |||
1415 | For information on IPython's Matplotlib integration (and the ``pylab`` mode) |
|
1416 | For information on IPython's Matplotlib integration (and the ``pylab`` mode) | |
1416 | see :ref:`this section <matplotlib_support>`. |
|
1417 | see :ref:`this section <matplotlib_support>`. | |
1417 |
|
1418 | |||
1418 | For developers that want to use IPython's GUI event loop integration in |
|
1419 | For developers that want to use IPython's GUI event loop integration in | |
1419 | the form of a library, these capabilities are exposed in library form |
|
1420 | the form of a library, these capabilities are exposed in library form | |
1420 | in the :mod:`IPython.lib.inputhook`. Interested developers should see the |
|
1421 | in the :mod:`IPython.lib.inputhook`. Interested developers should see the | |
1421 | module docstrings for more information, but there are a few points that |
|
1422 | module docstrings for more information, but there are a few points that | |
1422 | should be mentioned here. |
|
1423 | should be mentioned here. | |
1423 |
|
1424 | |||
1424 | First, the ``PyOSInputHook`` approach only works in command line settings |
|
1425 | First, the ``PyOSInputHook`` approach only works in command line settings | |
1425 | where readline is activated. |
|
1426 | where readline is activated. | |
1426 |
|
1427 | |||
1427 | Second, when using the ``PyOSInputHook`` approach, a GUI application should |
|
1428 | Second, when using the ``PyOSInputHook`` approach, a GUI application should | |
1428 | *not* start its event loop. Instead all of this is handled by the |
|
1429 | *not* start its event loop. Instead all of this is handled by the | |
1429 | ``PyOSInputHook``. This means that applications that are meant to be used both |
|
1430 | ``PyOSInputHook``. This means that applications that are meant to be used both | |
1430 | in IPython and as standalone apps need to have special code to detects how the |
|
1431 | in IPython and as standalone apps need to have special code to detects how the | |
1431 | application is being run. We highly recommend using IPython's |
|
1432 | application is being run. We highly recommend using IPython's | |
1432 | :func:`appstart_` functions for this. Here is a simple example that shows the |
|
1433 | :func:`appstart_` functions for this. Here is a simple example that shows the | |
1433 | recommended code that should be at the bottom of a wxPython using GUI |
|
1434 | recommended code that should be at the bottom of a wxPython using GUI | |
1434 | application:: |
|
1435 | application:: | |
1435 |
|
1436 | |||
1436 | try: |
|
1437 | try: | |
1437 | from IPython import appstart_wx |
|
1438 | from IPython import appstart_wx | |
1438 | appstart_wx(app) |
|
1439 | appstart_wx(app) | |
1439 | except ImportError: |
|
1440 | except ImportError: | |
1440 | app.MainLoop() |
|
1441 | app.MainLoop() | |
1441 |
|
1442 | |||
1442 | This pattern should be used instead of the simple ``app.MainLoop()`` code |
|
1443 | This pattern should be used instead of the simple ``app.MainLoop()`` code | |
1443 | that a standalone wxPython application would have. |
|
1444 | that a standalone wxPython application would have. | |
1444 |
|
1445 | |||
1445 | Third, unlike previous versions of IPython, we no longer "hijack" (replace |
|
1446 | Third, unlike previous versions of IPython, we no longer "hijack" (replace | |
1446 | them with no-ops) the event loops. This is done to allow applications that |
|
1447 | them with no-ops) the event loops. This is done to allow applications that | |
1447 | actually need to run the real event loops to do so. This is often needed to |
|
1448 | actually need to run the real event loops to do so. This is often needed to | |
1448 | process pending events at critical points. |
|
1449 | process pending events at critical points. | |
1449 |
|
1450 | |||
1450 | Finally, we also have a number of examples in our source directory |
|
1451 | Finally, we also have a number of examples in our source directory | |
1451 | :file:`docs/examples/lib` that demonstrate these capabilities. |
|
1452 | :file:`docs/examples/lib` that demonstrate these capabilities. | |
1452 |
|
1453 | |||
1453 | .. _matplotlib_support: |
|
1454 | .. _matplotlib_support: | |
1454 |
|
1455 | |||
1455 | Plotting with matplotlib |
|
1456 | Plotting with matplotlib | |
1456 | ======================== |
|
1457 | ======================== | |
1457 |
|
1458 | |||
1458 |
|
1459 | |||
1459 | `Matplotlib`_ provides high quality 2D and |
|
1460 | `Matplotlib`_ provides high quality 2D and | |
1460 | 3D plotting for Python. Matplotlib can produce plots on screen using a variety |
|
1461 | 3D plotting for Python. Matplotlib can produce plots on screen using a variety | |
1461 | of GUI toolkits, including Tk, PyGTK, PyQt4 and wxPython. It also provides a |
|
1462 | of GUI toolkits, including Tk, PyGTK, PyQt4 and wxPython. It also provides a | |
1462 | number of commands useful for scientific computing, all with a syntax |
|
1463 | number of commands useful for scientific computing, all with a syntax | |
1463 | compatible with that of the popular Matlab program. |
|
1464 | compatible with that of the popular Matlab program. | |
1464 |
|
1465 | |||
1465 | Many IPython users have come to rely on IPython's ``-pylab`` mode which |
|
1466 | Many IPython users have come to rely on IPython's ``-pylab`` mode which | |
1466 | automates the integration of Matplotlib with IPython. We are still in the |
|
1467 | automates the integration of Matplotlib with IPython. We are still in the | |
1467 | process of working with the Matplotlib developers to finalize the new pylab |
|
1468 | process of working with the Matplotlib developers to finalize the new pylab | |
1468 | API, but for now you can use Matplotlib interactively using the following |
|
1469 | API, but for now you can use Matplotlib interactively using the following | |
1469 | commands:: |
|
1470 | commands:: | |
1470 |
|
1471 | |||
1471 | %gui -a wx |
|
1472 | %gui -a wx | |
1472 | import matplotlib |
|
1473 | import matplotlib | |
1473 | matplotlib.use('wxagg') |
|
1474 | matplotlib.use('wxagg') | |
1474 | from matplotlib import pylab |
|
1475 | from matplotlib import pylab | |
1475 | pylab.interactive(True) |
|
1476 | pylab.interactive(True) | |
1476 |
|
1477 | |||
1477 | All of this will soon be automated as Matplotlib beings to include |
|
1478 | All of this will soon be automated as Matplotlib beings to include | |
1478 | new logic that uses our new GUI support. |
|
1479 | new logic that uses our new GUI support. | |
1479 |
|
1480 | |||
1480 | .. _interactive_demos: |
|
1481 | .. _interactive_demos: | |
1481 |
|
1482 | |||
1482 | Interactive demos with IPython |
|
1483 | Interactive demos with IPython | |
1483 | ============================== |
|
1484 | ============================== | |
1484 |
|
1485 | |||
1485 | IPython ships with a basic system for running scripts interactively in |
|
1486 | IPython ships with a basic system for running scripts interactively in | |
1486 | sections, useful when presenting code to audiences. A few tags embedded |
|
1487 | sections, useful when presenting code to audiences. A few tags embedded | |
1487 | in comments (so that the script remains valid Python code) divide a file |
|
1488 | in comments (so that the script remains valid Python code) divide a file | |
1488 | into separate blocks, and the demo can be run one block at a time, with |
|
1489 | into separate blocks, and the demo can be run one block at a time, with | |
1489 | IPython printing (with syntax highlighting) the block before executing |
|
1490 | IPython printing (with syntax highlighting) the block before executing | |
1490 | it, and returning to the interactive prompt after each block. The |
|
1491 | it, and returning to the interactive prompt after each block. The | |
1491 | interactive namespace is updated after each block is run with the |
|
1492 | interactive namespace is updated after each block is run with the | |
1492 | contents of the demo's namespace. |
|
1493 | contents of the demo's namespace. | |
1493 |
|
1494 | |||
1494 | This allows you to show a piece of code, run it and then execute |
|
1495 | This allows you to show a piece of code, run it and then execute | |
1495 | interactively commands based on the variables just created. Once you |
|
1496 | interactively commands based on the variables just created. Once you | |
1496 | want to continue, you simply execute the next block of the demo. The |
|
1497 | want to continue, you simply execute the next block of the demo. The | |
1497 | following listing shows the markup necessary for dividing a script into |
|
1498 | following listing shows the markup necessary for dividing a script into | |
1498 | sections for execution as a demo:: |
|
1499 | sections for execution as a demo:: | |
1499 |
|
1500 | |||
1500 |
|
1501 | |||
1501 | """A simple interactive demo to illustrate the use of IPython's Demo class. |
|
1502 | """A simple interactive demo to illustrate the use of IPython's Demo class. | |
1502 |
|
1503 | |||
1503 | Any python script can be run as a demo, but that does little more than showing |
|
1504 | Any python script can be run as a demo, but that does little more than showing | |
1504 | it on-screen, syntax-highlighted in one shot. If you add a little simple |
|
1505 | it on-screen, syntax-highlighted in one shot. If you add a little simple | |
1505 | markup, you can stop at specified intervals and return to the ipython prompt, |
|
1506 | markup, you can stop at specified intervals and return to the ipython prompt, | |
1506 | resuming execution later. |
|
1507 | resuming execution later. | |
1507 | """ |
|
1508 | """ | |
1508 |
|
1509 | |||
1509 | print 'Hello, welcome to an interactive IPython demo.' |
|
1510 | print 'Hello, welcome to an interactive IPython demo.' | |
1510 | print 'Executing this block should require confirmation before proceeding,' |
|
1511 | print 'Executing this block should require confirmation before proceeding,' | |
1511 | print 'unless auto_all has been set to true in the demo object' |
|
1512 | print 'unless auto_all has been set to true in the demo object' | |
1512 |
|
1513 | |||
1513 | # The mark below defines a block boundary, which is a point where IPython will |
|
1514 | # The mark below defines a block boundary, which is a point where IPython will | |
1514 | # stop execution and return to the interactive prompt. |
|
1515 | # stop execution and return to the interactive prompt. | |
1515 | # Note that in actual interactive execution, |
|
1516 | # Note that in actual interactive execution, | |
1516 | # <demo> --- stop --- |
|
1517 | # <demo> --- stop --- | |
1517 |
|
1518 | |||
1518 | x = 1 |
|
1519 | x = 1 | |
1519 | y = 2 |
|
1520 | y = 2 | |
1520 |
|
1521 | |||
1521 | # <demo> --- stop --- |
|
1522 | # <demo> --- stop --- | |
1522 |
|
1523 | |||
1523 | # the mark below makes this block as silent |
|
1524 | # the mark below makes this block as silent | |
1524 | # <demo> silent |
|
1525 | # <demo> silent | |
1525 |
|
1526 | |||
1526 | print 'This is a silent block, which gets executed but not printed.' |
|
1527 | print 'This is a silent block, which gets executed but not printed.' | |
1527 |
|
1528 | |||
1528 | # <demo> --- stop --- |
|
1529 | # <demo> --- stop --- | |
1529 | # <demo> auto |
|
1530 | # <demo> auto | |
1530 | print 'This is an automatic block.' |
|
1531 | print 'This is an automatic block.' | |
1531 | print 'It is executed without asking for confirmation, but printed.' |
|
1532 | print 'It is executed without asking for confirmation, but printed.' | |
1532 | z = x+y |
|
1533 | z = x+y | |
1533 |
|
1534 | |||
1534 | print 'z=',x |
|
1535 | print 'z=',x | |
1535 |
|
1536 | |||
1536 | # <demo> --- stop --- |
|
1537 | # <demo> --- stop --- | |
1537 | # This is just another normal block. |
|
1538 | # This is just another normal block. | |
1538 | print 'z is now:', z |
|
1539 | print 'z is now:', z | |
1539 |
|
1540 | |||
1540 | print 'bye!' |
|
1541 | print 'bye!' | |
1541 |
|
1542 | |||
1542 | In order to run a file as a demo, you must first make a Demo object out |
|
1543 | In order to run a file as a demo, you must first make a Demo object out | |
1543 | of it. If the file is named myscript.py, the following code will make a |
|
1544 | of it. If the file is named myscript.py, the following code will make a | |
1544 | demo:: |
|
1545 | demo:: | |
1545 |
|
1546 | |||
1546 | from IPython.demo import Demo |
|
1547 | from IPython.demo import Demo | |
1547 |
|
1548 | |||
1548 | mydemo = Demo('myscript.py') |
|
1549 | mydemo = Demo('myscript.py') | |
1549 |
|
1550 | |||
1550 | This creates the mydemo object, whose blocks you run one at a time by |
|
1551 | This creates the mydemo object, whose blocks you run one at a time by | |
1551 | simply calling the object with no arguments. If you have autocall active |
|
1552 | simply calling the object with no arguments. If you have autocall active | |
1552 | in IPython (the default), all you need to do is type:: |
|
1553 | in IPython (the default), all you need to do is type:: | |
1553 |
|
1554 | |||
1554 | mydemo |
|
1555 | mydemo | |
1555 |
|
1556 | |||
1556 | and IPython will call it, executing each block. Demo objects can be |
|
1557 | and IPython will call it, executing each block. Demo objects can be | |
1557 | restarted, you can move forward or back skipping blocks, re-execute the |
|
1558 | restarted, you can move forward or back skipping blocks, re-execute the | |
1558 | last block, etc. Simply use the Tab key on a demo object to see its |
|
1559 | last block, etc. Simply use the Tab key on a demo object to see its | |
1559 | methods, and call '?' on them to see their docstrings for more usage |
|
1560 | methods, and call '?' on them to see their docstrings for more usage | |
1560 | details. In addition, the demo module itself contains a comprehensive |
|
1561 | details. In addition, the demo module itself contains a comprehensive | |
1561 | docstring, which you can access via:: |
|
1562 | docstring, which you can access via:: | |
1562 |
|
1563 | |||
1563 | from IPython import demo |
|
1564 | from IPython import demo | |
1564 |
|
1565 | |||
1565 | demo? |
|
1566 | demo? | |
1566 |
|
1567 | |||
1567 | Limitations: It is important to note that these demos are limited to |
|
1568 | Limitations: It is important to note that these demos are limited to | |
1568 | fairly simple uses. In particular, you can not put division marks in |
|
1569 | fairly simple uses. In particular, you can not put division marks in | |
1569 | indented code (loops, if statements, function definitions, etc.) |
|
1570 | indented code (loops, if statements, function definitions, etc.) | |
1570 | Supporting something like this would basically require tracking the |
|
1571 | Supporting something like this would basically require tracking the | |
1571 | internal execution state of the Python interpreter, so only top-level |
|
1572 | internal execution state of the Python interpreter, so only top-level | |
1572 | divisions are allowed. If you want to be able to open an IPython |
|
1573 | divisions are allowed. If you want to be able to open an IPython | |
1573 | instance at an arbitrary point in a program, you can use IPython's |
|
1574 | instance at an arbitrary point in a program, you can use IPython's | |
1574 | embedding facilities, described in detail in Sec. 9 |
|
1575 | embedding facilities, described in detail in Sec. 9 | |
1575 |
|
1576 | |||
1576 | .. [Matplotlib] Matplotlib. http://matplotlib.sourceforge.net |
|
1577 | .. [Matplotlib] Matplotlib. http://matplotlib.sourceforge.net | |
1577 |
|
1578 |
@@ -1,293 +1,293 b'' | |||||
1 | .. _ipython_as_shell: |
|
1 | .. _ipython_as_shell: | |
2 |
|
2 | |||
3 | ========================= |
|
3 | ========================= | |
4 | IPython as a system shell |
|
4 | IPython as a system shell | |
5 | ========================= |
|
5 | ========================= | |
6 |
|
6 | |||
7 | .. warning:: |
|
7 | .. warning:: | |
8 |
|
8 | |||
9 | As of the 0.11 version of IPython, some of the features and APIs |
|
9 | As of the 0.11 version of IPython, some of the features and APIs | |
10 | described in this section have been deprecated or are broken. Our plan |
|
10 | described in this section have been deprecated or are broken. Our plan | |
11 | is to continue to support these features, but they need to be updated |
|
11 | is to continue to support these features, but they need to be updated | |
12 | to take advantage of recent API changes. Furthermore, this section |
|
12 | to take advantage of recent API changes. Furthermore, this section | |
13 | of the documentation need to be updated to reflect all of these changes. |
|
13 | of the documentation need to be updated to reflect all of these changes. | |
14 |
|
14 | |||
15 | Overview |
|
15 | Overview | |
16 | ======== |
|
16 | ======== | |
17 |
|
17 | |||
18 | The 'sh' profile optimizes IPython for system shell usage. Apart from |
|
18 | The 'sh' profile optimizes IPython for system shell usage. Apart from | |
19 | certain job control functionality that is present in unix (ctrl+z does |
|
19 | certain job control functionality that is present in unix (ctrl+z does | |
20 | "suspend"), the sh profile should provide you with most of the |
|
20 | "suspend"), the sh profile should provide you with most of the | |
21 | functionality you use daily in system shell, and more. Invoke IPython |
|
21 | functionality you use daily in system shell, and more. Invoke IPython | |
22 | in 'sh' profile by doing 'ipython -p sh', or (in win32) by launching |
|
22 | in 'sh' profile by doing 'ipython -p sh', or (in win32) by launching | |
23 | the "pysh" shortcut in start menu. |
|
23 | the "pysh" shortcut in start menu. | |
24 |
|
24 | |||
25 | If you want to use the features of sh profile as your defaults (which |
|
25 | If you want to use the features of sh profile as your defaults (which | |
26 | might be a good idea if you use other profiles a lot of the time but |
|
26 | might be a good idea if you use other profiles a lot of the time but | |
27 | still want the convenience of sh profile), add ``import ipy_profile_sh`` |
|
27 | still want the convenience of sh profile), add ``import ipy_profile_sh`` | |
28 |
to your |
|
28 | to your $IPYTHON_DIR/ipy_user_conf.py. | |
29 |
|
29 | |||
30 | The 'sh' profile is different from the default profile in that: |
|
30 | The 'sh' profile is different from the default profile in that: | |
31 |
|
31 | |||
32 | * Prompt shows the current directory |
|
32 | * Prompt shows the current directory | |
33 | * Spacing between prompts and input is more compact (no padding with |
|
33 | * Spacing between prompts and input is more compact (no padding with | |
34 | empty lines). The startup banner is more compact as well. |
|
34 | empty lines). The startup banner is more compact as well. | |
35 | * System commands are directly available (in alias table) without |
|
35 | * System commands are directly available (in alias table) without | |
36 | requesting %rehashx - however, if you install new programs along |
|
36 | requesting %rehashx - however, if you install new programs along | |
37 | your PATH, you might want to run %rehashx to update the persistent |
|
37 | your PATH, you might want to run %rehashx to update the persistent | |
38 | alias table |
|
38 | alias table | |
39 | * Macros are stored in raw format by default. That is, instead of |
|
39 | * Macros are stored in raw format by default. That is, instead of | |
40 | '_ip.system("cat foo"), the macro will contain text 'cat foo') |
|
40 | '_ip.system("cat foo"), the macro will contain text 'cat foo') | |
41 | * Autocall is in full mode |
|
41 | * Autocall is in full mode | |
42 | * Calling "up" does "cd .." |
|
42 | * Calling "up" does "cd .." | |
43 |
|
43 | |||
44 | The 'sh' profile is different from the now-obsolete (and unavailable) |
|
44 | The 'sh' profile is different from the now-obsolete (and unavailable) | |
45 | 'pysh' profile in that: |
|
45 | 'pysh' profile in that: | |
46 |
|
46 | |||
47 | * '$$var = command' and '$var = command' syntax is not supported |
|
47 | * '$$var = command' and '$var = command' syntax is not supported | |
48 | * anymore. Use 'var = !command' instead (incidentally, this is |
|
48 | * anymore. Use 'var = !command' instead (incidentally, this is | |
49 | * available in all IPython profiles). Note that !!command *will* |
|
49 | * available in all IPython profiles). Note that !!command *will* | |
50 | * work. |
|
50 | * work. | |
51 |
|
51 | |||
52 | Aliases |
|
52 | Aliases | |
53 | ======= |
|
53 | ======= | |
54 |
|
54 | |||
55 | All of your $PATH has been loaded as IPython aliases, so you should be |
|
55 | All of your $PATH has been loaded as IPython aliases, so you should be | |
56 | able to type any normal system command and have it executed. See |
|
56 | able to type any normal system command and have it executed. See | |
57 | %alias? and %unalias? for details on the alias facilities. See also |
|
57 | %alias? and %unalias? for details on the alias facilities. See also | |
58 | %rehashx? for details on the mechanism used to load $PATH. |
|
58 | %rehashx? for details on the mechanism used to load $PATH. | |
59 |
|
59 | |||
60 |
|
60 | |||
61 | Directory management |
|
61 | Directory management | |
62 | ==================== |
|
62 | ==================== | |
63 |
|
63 | |||
64 | Since each command passed by ipython to the underlying system is executed |
|
64 | Since each command passed by ipython to the underlying system is executed | |
65 | in a subshell which exits immediately, you can NOT use !cd to navigate |
|
65 | in a subshell which exits immediately, you can NOT use !cd to navigate | |
66 | the filesystem. |
|
66 | the filesystem. | |
67 |
|
67 | |||
68 | IPython provides its own builtin '%cd' magic command to move in the |
|
68 | IPython provides its own builtin '%cd' magic command to move in the | |
69 | filesystem (the % is not required with automagic on). It also maintains |
|
69 | filesystem (the % is not required with automagic on). It also maintains | |
70 | a list of visited directories (use %dhist to see it) and allows direct |
|
70 | a list of visited directories (use %dhist to see it) and allows direct | |
71 | switching to any of them. Type 'cd?' for more details. |
|
71 | switching to any of them. Type 'cd?' for more details. | |
72 |
|
72 | |||
73 | %pushd, %popd and %dirs are provided for directory stack handling. |
|
73 | %pushd, %popd and %dirs are provided for directory stack handling. | |
74 |
|
74 | |||
75 |
|
75 | |||
76 | Enabled extensions |
|
76 | Enabled extensions | |
77 | ================== |
|
77 | ================== | |
78 |
|
78 | |||
79 | Some extensions, listed below, are enabled as default in this profile. |
|
79 | Some extensions, listed below, are enabled as default in this profile. | |
80 |
|
80 | |||
81 | envpersist |
|
81 | envpersist | |
82 | ---------- |
|
82 | ---------- | |
83 |
|
83 | |||
84 | %env can be used to "remember" environment variable manipulations. Examples:: |
|
84 | %env can be used to "remember" environment variable manipulations. Examples:: | |
85 |
|
85 | |||
86 | %env - Show all environment variables |
|
86 | %env - Show all environment variables | |
87 | %env VISUAL=jed - set VISUAL to jed |
|
87 | %env VISUAL=jed - set VISUAL to jed | |
88 | %env PATH+=;/foo - append ;foo to PATH |
|
88 | %env PATH+=;/foo - append ;foo to PATH | |
89 | %env PATH+=;/bar - also append ;bar to PATH |
|
89 | %env PATH+=;/bar - also append ;bar to PATH | |
90 | %env PATH-=/wbin; - prepend /wbin; to PATH |
|
90 | %env PATH-=/wbin; - prepend /wbin; to PATH | |
91 | %env -d VISUAL - forget VISUAL persistent val |
|
91 | %env -d VISUAL - forget VISUAL persistent val | |
92 | %env -p - print all persistent env modifications |
|
92 | %env -p - print all persistent env modifications | |
93 |
|
93 | |||
94 | ipy_which |
|
94 | ipy_which | |
95 | --------- |
|
95 | --------- | |
96 |
|
96 | |||
97 | %which magic command. Like 'which' in unix, but knows about ipython aliases. |
|
97 | %which magic command. Like 'which' in unix, but knows about ipython aliases. | |
98 |
|
98 | |||
99 | Example:: |
|
99 | Example:: | |
100 |
|
100 | |||
101 | [C:/ipython]|14> %which st |
|
101 | [C:/ipython]|14> %which st | |
102 | st -> start . |
|
102 | st -> start . | |
103 | [C:/ipython]|15> %which d |
|
103 | [C:/ipython]|15> %which d | |
104 | d -> dir /w /og /on |
|
104 | d -> dir /w /og /on | |
105 | [C:/ipython]|16> %which cp |
|
105 | [C:/ipython]|16> %which cp | |
106 | cp -> cp |
|
106 | cp -> cp | |
107 | == c:\bin\cp.exe |
|
107 | == c:\bin\cp.exe | |
108 | c:\bin\cp.exe |
|
108 | c:\bin\cp.exe | |
109 |
|
109 | |||
110 | ipy_app_completers |
|
110 | ipy_app_completers | |
111 | ------------------ |
|
111 | ------------------ | |
112 |
|
112 | |||
113 | Custom tab completers for some apps like svn, hg, bzr, apt-get. Try 'apt-get install <TAB>' in debian/ubuntu. |
|
113 | Custom tab completers for some apps like svn, hg, bzr, apt-get. Try 'apt-get install <TAB>' in debian/ubuntu. | |
114 |
|
114 | |||
115 | ipy_rehashdir |
|
115 | ipy_rehashdir | |
116 | ------------- |
|
116 | ------------- | |
117 |
|
117 | |||
118 | Allows you to add system command aliases for commands that are not along your path. Let's say that you just installed Putty and want to be able to invoke it without adding it to path, you can create the alias for it with rehashdir:: |
|
118 | Allows you to add system command aliases for commands that are not along your path. Let's say that you just installed Putty and want to be able to invoke it without adding it to path, you can create the alias for it with rehashdir:: | |
119 |
|
119 | |||
120 | [~]|22> cd c:/opt/PuTTY/ |
|
120 | [~]|22> cd c:/opt/PuTTY/ | |
121 | [c:opt/PuTTY]|23> rehashdir . |
|
121 | [c:opt/PuTTY]|23> rehashdir . | |
122 | <23> ['pageant', 'plink', 'pscp', 'psftp', 'putty', 'puttygen', 'unins000'] |
|
122 | <23> ['pageant', 'plink', 'pscp', 'psftp', 'putty', 'puttygen', 'unins000'] | |
123 |
|
123 | |||
124 | Now, you can execute any of those commams directly:: |
|
124 | Now, you can execute any of those commams directly:: | |
125 |
|
125 | |||
126 | [c:opt/PuTTY]|24> cd |
|
126 | [c:opt/PuTTY]|24> cd | |
127 | [~]|25> putty |
|
127 | [~]|25> putty | |
128 |
|
128 | |||
129 | (the putty window opens). |
|
129 | (the putty window opens). | |
130 |
|
130 | |||
131 | If you want to store the alias so that it will always be available, do '%store putty'. If you want to %store all these aliases persistently, just do it in a for loop:: |
|
131 | If you want to store the alias so that it will always be available, do '%store putty'. If you want to %store all these aliases persistently, just do it in a for loop:: | |
132 |
|
132 | |||
133 | [~]|27> for a in _23: |
|
133 | [~]|27> for a in _23: | |
134 | |..> %store $a |
|
134 | |..> %store $a | |
135 | |..> |
|
135 | |..> | |
136 | |..> |
|
136 | |..> | |
137 | Alias stored: pageant (0, 'c:\\opt\\PuTTY\\pageant.exe') |
|
137 | Alias stored: pageant (0, 'c:\\opt\\PuTTY\\pageant.exe') | |
138 | Alias stored: plink (0, 'c:\\opt\\PuTTY\\plink.exe') |
|
138 | Alias stored: plink (0, 'c:\\opt\\PuTTY\\plink.exe') | |
139 | Alias stored: pscp (0, 'c:\\opt\\PuTTY\\pscp.exe') |
|
139 | Alias stored: pscp (0, 'c:\\opt\\PuTTY\\pscp.exe') | |
140 | Alias stored: psftp (0, 'c:\\opt\\PuTTY\\psftp.exe') |
|
140 | Alias stored: psftp (0, 'c:\\opt\\PuTTY\\psftp.exe') | |
141 | ... |
|
141 | ... | |
142 |
|
142 | |||
143 | mglob |
|
143 | mglob | |
144 | ----- |
|
144 | ----- | |
145 |
|
145 | |||
146 | Provide the magic function %mglob, which makes it easier (than the 'find' command) to collect (possibly recursive) file lists. Examples:: |
|
146 | Provide the magic function %mglob, which makes it easier (than the 'find' command) to collect (possibly recursive) file lists. Examples:: | |
147 |
|
147 | |||
148 | [c:/ipython]|9> mglob *.py |
|
148 | [c:/ipython]|9> mglob *.py | |
149 | [c:/ipython]|10> mglob *.py rec:*.txt |
|
149 | [c:/ipython]|10> mglob *.py rec:*.txt | |
150 | [c:/ipython]|19> workfiles = %mglob !.svn/ !.hg/ !*_Data/ !*.bak rec:. |
|
150 | [c:/ipython]|19> workfiles = %mglob !.svn/ !.hg/ !*_Data/ !*.bak rec:. | |
151 |
|
151 | |||
152 | Note that the first 2 calls will put the file list in result history (_, _9, _10), and the last one will assign it to 'workfiles'. |
|
152 | Note that the first 2 calls will put the file list in result history (_, _9, _10), and the last one will assign it to 'workfiles'. | |
153 |
|
153 | |||
154 |
|
154 | |||
155 | Prompt customization |
|
155 | Prompt customization | |
156 | ==================== |
|
156 | ==================== | |
157 |
|
157 | |||
158 | The sh profile uses the following prompt configurations:: |
|
158 | The sh profile uses the following prompt configurations:: | |
159 |
|
159 | |||
160 | o.prompt_in1= r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Green|\#>' |
|
160 | o.prompt_in1= r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Green|\#>' | |
161 | o.prompt_in2= r'\C_Green|\C_LightGreen\D\C_Green>' |
|
161 | o.prompt_in2= r'\C_Green|\C_LightGreen\D\C_Green>' | |
162 |
|
162 | |||
163 | You can change the prompt configuration to your liking by editing |
|
163 | You can change the prompt configuration to your liking by editing | |
164 | ipy_user_conf.py. |
|
164 | ipy_user_conf.py. | |
165 |
|
165 | |||
166 | String lists |
|
166 | String lists | |
167 | ============ |
|
167 | ============ | |
168 |
|
168 | |||
169 | String lists (IPython.utils.text.SList) are handy way to process output |
|
169 | String lists (IPython.utils.text.SList) are handy way to process output | |
170 | from system commands. They are produced by ``var = !cmd`` syntax. |
|
170 | from system commands. They are produced by ``var = !cmd`` syntax. | |
171 |
|
171 | |||
172 | First, we acquire the output of 'ls -l':: |
|
172 | First, we acquire the output of 'ls -l':: | |
173 |
|
173 | |||
174 | [Q:doc/examples]|2> lines = !ls -l |
|
174 | [Q:doc/examples]|2> lines = !ls -l | |
175 | == |
|
175 | == | |
176 | ['total 23', |
|
176 | ['total 23', | |
177 | '-rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py', |
|
177 | '-rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py', | |
178 | '-rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py', |
|
178 | '-rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py', | |
179 | '-rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py', |
|
179 | '-rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py', | |
180 | '-rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py', |
|
180 | '-rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py', | |
181 | '-rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py', |
|
181 | '-rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py', | |
182 | '-rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py', |
|
182 | '-rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py', | |
183 | '-rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc'] |
|
183 | '-rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc'] | |
184 |
|
184 | |||
185 | Now, let's take a look at the contents of 'lines' (the first number is |
|
185 | Now, let's take a look at the contents of 'lines' (the first number is | |
186 | the list element number):: |
|
186 | the list element number):: | |
187 |
|
187 | |||
188 | [Q:doc/examples]|3> lines |
|
188 | [Q:doc/examples]|3> lines | |
189 | <3> SList (.p, .n, .l, .s, .grep(), .fields() available). Value: |
|
189 | <3> SList (.p, .n, .l, .s, .grep(), .fields() available). Value: | |
190 |
|
190 | |||
191 | 0: total 23 |
|
191 | 0: total 23 | |
192 | 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py |
|
192 | 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py | |
193 | 2: -rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py |
|
193 | 2: -rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py | |
194 | 3: -rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py |
|
194 | 3: -rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py | |
195 | 4: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py |
|
195 | 4: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py | |
196 | 5: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py |
|
196 | 5: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py | |
197 | 6: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py |
|
197 | 6: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py | |
198 | 7: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc |
|
198 | 7: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc | |
199 |
|
199 | |||
200 | Now, let's filter out the 'embed' lines:: |
|
200 | Now, let's filter out the 'embed' lines:: | |
201 |
|
201 | |||
202 | [Q:doc/examples]|4> l2 = lines.grep('embed',prune=1) |
|
202 | [Q:doc/examples]|4> l2 = lines.grep('embed',prune=1) | |
203 | [Q:doc/examples]|5> l2 |
|
203 | [Q:doc/examples]|5> l2 | |
204 | <5> SList (.p, .n, .l, .s, .grep(), .fields() available). Value: |
|
204 | <5> SList (.p, .n, .l, .s, .grep(), .fields() available). Value: | |
205 |
|
205 | |||
206 | 0: total 23 |
|
206 | 0: total 23 | |
207 | 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py |
|
207 | 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py | |
208 | 2: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py |
|
208 | 2: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py | |
209 | 3: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py |
|
209 | 3: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py | |
210 | 4: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py |
|
210 | 4: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py | |
211 | 5: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc |
|
211 | 5: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc | |
212 |
|
212 | |||
213 | Now, we want strings having just file names and permissions:: |
|
213 | Now, we want strings having just file names and permissions:: | |
214 |
|
214 | |||
215 | [Q:doc/examples]|6> l2.fields(8,0) |
|
215 | [Q:doc/examples]|6> l2.fields(8,0) | |
216 | <6> SList (.p, .n, .l, .s, .grep(), .fields() available). Value: |
|
216 | <6> SList (.p, .n, .l, .s, .grep(), .fields() available). Value: | |
217 |
|
217 | |||
218 | 0: total |
|
218 | 0: total | |
219 | 1: example-demo.py -rw-rw-rw- |
|
219 | 1: example-demo.py -rw-rw-rw- | |
220 | 2: example-gnuplot.py -rwxrwxrwx |
|
220 | 2: example-gnuplot.py -rwxrwxrwx | |
221 | 3: extension.py -rwxrwxrwx |
|
221 | 3: extension.py -rwxrwxrwx | |
222 | 4: seteditor.py -rwxrwxrwx |
|
222 | 4: seteditor.py -rwxrwxrwx | |
223 | 5: seteditor.pyc -rwxrwxrwx |
|
223 | 5: seteditor.pyc -rwxrwxrwx | |
224 |
|
224 | |||
225 | Note how the line with 'total' does not raise IndexError. |
|
225 | Note how the line with 'total' does not raise IndexError. | |
226 |
|
226 | |||
227 | If you want to split these (yielding lists), call fields() without |
|
227 | If you want to split these (yielding lists), call fields() without | |
228 | arguments:: |
|
228 | arguments:: | |
229 |
|
229 | |||
230 | [Q:doc/examples]|7> _.fields() |
|
230 | [Q:doc/examples]|7> _.fields() | |
231 | <7> |
|
231 | <7> | |
232 | [['total'], |
|
232 | [['total'], | |
233 | ['example-demo.py', '-rw-rw-rw-'], |
|
233 | ['example-demo.py', '-rw-rw-rw-'], | |
234 | ['example-gnuplot.py', '-rwxrwxrwx'], |
|
234 | ['example-gnuplot.py', '-rwxrwxrwx'], | |
235 | ['extension.py', '-rwxrwxrwx'], |
|
235 | ['extension.py', '-rwxrwxrwx'], | |
236 | ['seteditor.py', '-rwxrwxrwx'], |
|
236 | ['seteditor.py', '-rwxrwxrwx'], | |
237 | ['seteditor.pyc', '-rwxrwxrwx']] |
|
237 | ['seteditor.pyc', '-rwxrwxrwx']] | |
238 |
|
238 | |||
239 | If you want to pass these separated with spaces to a command (typical |
|
239 | If you want to pass these separated with spaces to a command (typical | |
240 | for lists if files), use the .s property:: |
|
240 | for lists if files), use the .s property:: | |
241 |
|
241 | |||
242 |
|
242 | |||
243 | [Q:doc/examples]|13> files = l2.fields(8).s |
|
243 | [Q:doc/examples]|13> files = l2.fields(8).s | |
244 | [Q:doc/examples]|14> files |
|
244 | [Q:doc/examples]|14> files | |
245 | <14> 'example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc' |
|
245 | <14> 'example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc' | |
246 | [Q:doc/examples]|15> ls $files |
|
246 | [Q:doc/examples]|15> ls $files | |
247 | example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc |
|
247 | example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc | |
248 |
|
248 | |||
249 | SLists are inherited from normal python lists, so every list method is |
|
249 | SLists are inherited from normal python lists, so every list method is | |
250 | available:: |
|
250 | available:: | |
251 |
|
251 | |||
252 | [Q:doc/examples]|21> lines.append('hey') |
|
252 | [Q:doc/examples]|21> lines.append('hey') | |
253 |
|
253 | |||
254 |
|
254 | |||
255 | Real world example: remove all files outside version control |
|
255 | Real world example: remove all files outside version control | |
256 | ============================================================ |
|
256 | ============================================================ | |
257 |
|
257 | |||
258 | First, capture output of "hg status":: |
|
258 | First, capture output of "hg status":: | |
259 |
|
259 | |||
260 | [Q:/ipython]|28> out = !hg status |
|
260 | [Q:/ipython]|28> out = !hg status | |
261 | == |
|
261 | == | |
262 | ['M IPython\\extensions\\ipy_kitcfg.py', |
|
262 | ['M IPython\\extensions\\ipy_kitcfg.py', | |
263 | 'M IPython\\extensions\\ipy_rehashdir.py', |
|
263 | 'M IPython\\extensions\\ipy_rehashdir.py', | |
264 | ... |
|
264 | ... | |
265 | '? build\\lib\\IPython\\Debugger.py', |
|
265 | '? build\\lib\\IPython\\Debugger.py', | |
266 | '? build\\lib\\IPython\\extensions\\InterpreterExec.py', |
|
266 | '? build\\lib\\IPython\\extensions\\InterpreterExec.py', | |
267 | '? build\\lib\\IPython\\extensions\\InterpreterPasteInput.py', |
|
267 | '? build\\lib\\IPython\\extensions\\InterpreterPasteInput.py', | |
268 | ... |
|
268 | ... | |
269 |
|
269 | |||
270 | (lines starting with ? are not under version control). |
|
270 | (lines starting with ? are not under version control). | |
271 |
|
271 | |||
272 | :: |
|
272 | :: | |
273 |
|
273 | |||
274 | [Q:/ipython]|35> junk = out.grep(r'^\?').fields(1) |
|
274 | [Q:/ipython]|35> junk = out.grep(r'^\?').fields(1) | |
275 | [Q:/ipython]|36> junk |
|
275 | [Q:/ipython]|36> junk | |
276 | <36> SList (.p, .n, .l, .s, .grep(), .fields() availab |
|
276 | <36> SList (.p, .n, .l, .s, .grep(), .fields() availab | |
277 | ... |
|
277 | ... | |
278 | 10: build\bdist.win32\winexe\temp\_ctypes.py |
|
278 | 10: build\bdist.win32\winexe\temp\_ctypes.py | |
279 | 11: build\bdist.win32\winexe\temp\_hashlib.py |
|
279 | 11: build\bdist.win32\winexe\temp\_hashlib.py | |
280 | 12: build\bdist.win32\winexe\temp\_socket.py |
|
280 | 12: build\bdist.win32\winexe\temp\_socket.py | |
281 |
|
281 | |||
282 | Now we can just remove these files by doing 'rm $junk.s'. |
|
282 | Now we can just remove these files by doing 'rm $junk.s'. | |
283 |
|
283 | |||
284 | The .s, .n, .p properties |
|
284 | The .s, .n, .p properties | |
285 | ========================= |
|
285 | ========================= | |
286 |
|
286 | |||
287 | The '.s' property returns one string where lines are separated by |
|
287 | The '.s' property returns one string where lines are separated by | |
288 | single space (for convenient passing to system commands). The '.n' |
|
288 | single space (for convenient passing to system commands). The '.n' | |
289 | property return one string where the lines are separated by '\n' |
|
289 | property return one string where the lines are separated by '\n' | |
290 | (i.e. the original output of the function). If the items in string |
|
290 | (i.e. the original output of the function). If the items in string | |
291 | list are file names, '.p' can be used to get a list of "path" objects |
|
291 | list are file names, '.p' can be used to get a list of "path" objects | |
292 | for convenient file manipulation. |
|
292 | for convenient file manipulation. | |
293 |
|
293 |
@@ -1,237 +1,237 b'' | |||||
1 | .. _ip1par: |
|
1 | .. _ip1par: | |
2 |
|
2 | |||
3 | ============================ |
|
3 | ============================ | |
4 | Overview and getting started |
|
4 | Overview and getting started | |
5 | ============================ |
|
5 | ============================ | |
6 |
|
6 | |||
7 | Introduction |
|
7 | Introduction | |
8 | ============ |
|
8 | ============ | |
9 |
|
9 | |||
10 | This section gives an overview of IPython's sophisticated and powerful |
|
10 | This section gives an overview of IPython's sophisticated and powerful | |
11 | architecture for parallel and distributed computing. This architecture |
|
11 | architecture for parallel and distributed computing. This architecture | |
12 | abstracts out parallelism in a very general way, which enables IPython to |
|
12 | abstracts out parallelism in a very general way, which enables IPython to | |
13 | support many different styles of parallelism including: |
|
13 | support many different styles of parallelism including: | |
14 |
|
14 | |||
15 | * Single program, multiple data (SPMD) parallelism. |
|
15 | * Single program, multiple data (SPMD) parallelism. | |
16 | * Multiple program, multiple data (MPMD) parallelism. |
|
16 | * Multiple program, multiple data (MPMD) parallelism. | |
17 | * Message passing using MPI. |
|
17 | * Message passing using MPI. | |
18 | * Task farming. |
|
18 | * Task farming. | |
19 | * Data parallel. |
|
19 | * Data parallel. | |
20 | * Combinations of these approaches. |
|
20 | * Combinations of these approaches. | |
21 | * Custom user defined approaches. |
|
21 | * Custom user defined approaches. | |
22 |
|
22 | |||
23 | Most importantly, IPython enables all types of parallel applications to |
|
23 | Most importantly, IPython enables all types of parallel applications to | |
24 | be developed, executed, debugged and monitored *interactively*. Hence, |
|
24 | be developed, executed, debugged and monitored *interactively*. Hence, | |
25 | the ``I`` in IPython. The following are some example usage cases for IPython: |
|
25 | the ``I`` in IPython. The following are some example usage cases for IPython: | |
26 |
|
26 | |||
27 | * Quickly parallelize algorithms that are embarrassingly parallel |
|
27 | * Quickly parallelize algorithms that are embarrassingly parallel | |
28 | using a number of simple approaches. Many simple things can be |
|
28 | using a number of simple approaches. Many simple things can be | |
29 | parallelized interactively in one or two lines of code. |
|
29 | parallelized interactively in one or two lines of code. | |
30 |
|
30 | |||
31 | * Steer traditional MPI applications on a supercomputer from an |
|
31 | * Steer traditional MPI applications on a supercomputer from an | |
32 | IPython session on your laptop. |
|
32 | IPython session on your laptop. | |
33 |
|
33 | |||
34 | * Analyze and visualize large datasets (that could be remote and/or |
|
34 | * Analyze and visualize large datasets (that could be remote and/or | |
35 | distributed) interactively using IPython and tools like |
|
35 | distributed) interactively using IPython and tools like | |
36 | matplotlib/TVTK. |
|
36 | matplotlib/TVTK. | |
37 |
|
37 | |||
38 | * Develop, test and debug new parallel algorithms |
|
38 | * Develop, test and debug new parallel algorithms | |
39 | (that may use MPI) interactively. |
|
39 | (that may use MPI) interactively. | |
40 |
|
40 | |||
41 | * Tie together multiple MPI jobs running on different systems into |
|
41 | * Tie together multiple MPI jobs running on different systems into | |
42 | one giant distributed and parallel system. |
|
42 | one giant distributed and parallel system. | |
43 |
|
43 | |||
44 | * Start a parallel job on your cluster and then have a remote |
|
44 | * Start a parallel job on your cluster and then have a remote | |
45 | collaborator connect to it and pull back data into their |
|
45 | collaborator connect to it and pull back data into their | |
46 | local IPython session for plotting and analysis. |
|
46 | local IPython session for plotting and analysis. | |
47 |
|
47 | |||
48 | * Run a set of tasks on a set of CPUs using dynamic load balancing. |
|
48 | * Run a set of tasks on a set of CPUs using dynamic load balancing. | |
49 |
|
49 | |||
50 | Architecture overview |
|
50 | Architecture overview | |
51 | ===================== |
|
51 | ===================== | |
52 |
|
52 | |||
53 | The IPython architecture consists of three components: |
|
53 | The IPython architecture consists of three components: | |
54 |
|
54 | |||
55 | * The IPython engine. |
|
55 | * The IPython engine. | |
56 | * The IPython controller. |
|
56 | * The IPython controller. | |
57 | * Various controller clients. |
|
57 | * Various controller clients. | |
58 |
|
58 | |||
59 | These components live in the :mod:`IPython.kernel` package and are |
|
59 | These components live in the :mod:`IPython.kernel` package and are | |
60 | installed with IPython. They do, however, have additional dependencies |
|
60 | installed with IPython. They do, however, have additional dependencies | |
61 | that must be installed. For more information, see our |
|
61 | that must be installed. For more information, see our | |
62 | :ref:`installation documentation <install_index>`. |
|
62 | :ref:`installation documentation <install_index>`. | |
63 |
|
63 | |||
64 | IPython engine |
|
64 | IPython engine | |
65 | --------------- |
|
65 | --------------- | |
66 |
|
66 | |||
67 | The IPython engine is a Python instance that takes Python commands over a |
|
67 | The IPython engine is a Python instance that takes Python commands over a | |
68 | network connection. Eventually, the IPython engine will be a full IPython |
|
68 | network connection. Eventually, the IPython engine will be a full IPython | |
69 | interpreter, but for now, it is a regular Python interpreter. The engine |
|
69 | interpreter, but for now, it is a regular Python interpreter. The engine | |
70 | can also handle incoming and outgoing Python objects sent over a network |
|
70 | can also handle incoming and outgoing Python objects sent over a network | |
71 | connection. When multiple engines are started, parallel and distributed |
|
71 | connection. When multiple engines are started, parallel and distributed | |
72 | computing becomes possible. An important feature of an IPython engine is |
|
72 | computing becomes possible. An important feature of an IPython engine is | |
73 | that it blocks while user code is being executed. Read on for how the |
|
73 | that it blocks while user code is being executed. Read on for how the | |
74 | IPython controller solves this problem to expose a clean asynchronous API |
|
74 | IPython controller solves this problem to expose a clean asynchronous API | |
75 | to the user. |
|
75 | to the user. | |
76 |
|
76 | |||
77 | IPython controller |
|
77 | IPython controller | |
78 | ------------------ |
|
78 | ------------------ | |
79 |
|
79 | |||
80 | The IPython controller provides an interface for working with a set of |
|
80 | The IPython controller provides an interface for working with a set of | |
81 | engines. At an general level, the controller is a process to which |
|
81 | engines. At an general level, the controller is a process to which | |
82 | IPython engines can connect. For each connected engine, the controller |
|
82 | IPython engines can connect. For each connected engine, the controller | |
83 | manages a queue. All actions that can be performed on the engine go |
|
83 | manages a queue. All actions that can be performed on the engine go | |
84 | through this queue. While the engines themselves block when user code is |
|
84 | through this queue. While the engines themselves block when user code is | |
85 | run, the controller hides that from the user to provide a fully |
|
85 | run, the controller hides that from the user to provide a fully | |
86 | asynchronous interface to a set of engines. |
|
86 | asynchronous interface to a set of engines. | |
87 |
|
87 | |||
88 | .. note:: |
|
88 | .. note:: | |
89 |
|
89 | |||
90 | Because the controller listens on a network port for engines to |
|
90 | Because the controller listens on a network port for engines to | |
91 | connect to it, it must be started *before* any engines are started. |
|
91 | connect to it, it must be started *before* any engines are started. | |
92 |
|
92 | |||
93 | The controller also provides a single point of contact for users who wish to |
|
93 | The controller also provides a single point of contact for users who wish to | |
94 | utilize the engines connected to the controller. There are different ways of |
|
94 | utilize the engines connected to the controller. There are different ways of | |
95 | working with a controller. In IPython these ways correspond to different |
|
95 | working with a controller. In IPython these ways correspond to different | |
96 | interfaces that the controller is adapted to. Currently we have two default |
|
96 | interfaces that the controller is adapted to. Currently we have two default | |
97 | interfaces to the controller: |
|
97 | interfaces to the controller: | |
98 |
|
98 | |||
99 | * The MultiEngine interface, which provides the simplest possible way of |
|
99 | * The MultiEngine interface, which provides the simplest possible way of | |
100 | working with engines interactively. |
|
100 | working with engines interactively. | |
101 | * The Task interface, which presents the engines as a load balanced |
|
101 | * The Task interface, which presents the engines as a load balanced | |
102 | task farming system. |
|
102 | task farming system. | |
103 |
|
103 | |||
104 | Advanced users can easily add new custom interfaces to enable other |
|
104 | Advanced users can easily add new custom interfaces to enable other | |
105 | styles of parallelism. |
|
105 | styles of parallelism. | |
106 |
|
106 | |||
107 | .. note:: |
|
107 | .. note:: | |
108 |
|
108 | |||
109 | A single controller and set of engines can be accessed |
|
109 | A single controller and set of engines can be accessed | |
110 | through multiple interfaces simultaneously. This opens the |
|
110 | through multiple interfaces simultaneously. This opens the | |
111 | door for lots of interesting things. |
|
111 | door for lots of interesting things. | |
112 |
|
112 | |||
113 | Controller clients |
|
113 | Controller clients | |
114 | ------------------ |
|
114 | ------------------ | |
115 |
|
115 | |||
116 | For each controller interface, there is a corresponding client. These |
|
116 | For each controller interface, there is a corresponding client. These | |
117 | clients allow users to interact with a set of engines through the |
|
117 | clients allow users to interact with a set of engines through the | |
118 | interface. Here are the two default clients: |
|
118 | interface. Here are the two default clients: | |
119 |
|
119 | |||
120 | * The :class:`MultiEngineClient` class. |
|
120 | * The :class:`MultiEngineClient` class. | |
121 | * The :class:`TaskClient` class. |
|
121 | * The :class:`TaskClient` class. | |
122 |
|
122 | |||
123 | Security |
|
123 | Security | |
124 | -------- |
|
124 | -------- | |
125 |
|
125 | |||
126 | By default (as long as `pyOpenSSL` is installed) all network connections |
|
126 | By default (as long as `pyOpenSSL` is installed) all network connections | |
127 | between the controller and engines and the controller and clients are secure. |
|
127 | between the controller and engines and the controller and clients are secure. | |
128 | What does this mean? First of all, all of the connections will be encrypted |
|
128 | What does this mean? First of all, all of the connections will be encrypted | |
129 | using SSL. Second, the connections are authenticated. We handle authentication |
|
129 | using SSL. Second, the connections are authenticated. We handle authentication | |
130 | in a capability based security model [Capability]_. In this model, a |
|
130 | in a capability based security model [Capability]_. In this model, a | |
131 | "capability (known in some systems as a key) is a communicable, unforgeable |
|
131 | "capability (known in some systems as a key) is a communicable, unforgeable | |
132 | token of authority". Put simply, a capability is like a key to your house. If |
|
132 | token of authority". Put simply, a capability is like a key to your house. If | |
133 | you have the key to your house, you can get in. If not, you can't. |
|
133 | you have the key to your house, you can get in. If not, you can't. | |
134 |
|
134 | |||
135 | In our architecture, the controller is the only process that listens on |
|
135 | In our architecture, the controller is the only process that listens on | |
136 | network ports, and is thus responsible to creating these keys. In IPython, |
|
136 | network ports, and is thus responsible to creating these keys. In IPython, | |
137 | these keys are known as Foolscap URLs, or FURLs, because of the underlying |
|
137 | these keys are known as Foolscap URLs, or FURLs, because of the underlying | |
138 | network protocol we are using. As a user, you don't need to know anything |
|
138 | network protocol we are using. As a user, you don't need to know anything | |
139 | about the details of these FURLs, other than that when the controller starts, |
|
139 | about the details of these FURLs, other than that when the controller starts, | |
140 | it saves a set of FURLs to files named :file:`something.furl`. The default |
|
140 | it saves a set of FURLs to files named :file:`something.furl`. The default | |
141 |
location of these files is the :file:` |
|
141 | location of these files is the :file:`$IPYTHON_DIR/cluster_<profile>/security` directory. | |
142 |
|
142 | |||
143 | To connect and authenticate to the controller an engine or client simply needs |
|
143 | To connect and authenticate to the controller an engine or client simply needs | |
144 | to present an appropriate FURL (that was originally created by the controller) |
|
144 | to present an appropriate FURL (that was originally created by the controller) | |
145 | to the controller. Thus, the FURL files need to be copied to a location where |
|
145 | to the controller. Thus, the FURL files need to be copied to a location where | |
146 | the clients and engines can find them. Typically, this is the |
|
146 | the clients and engines can find them. Typically, this is the | |
147 |
:file:` |
|
147 | :file:`$IPYTHON_DIR/cluster_<profile>/security` directory on the host where the client/engine is | |
148 | running (which could be a different host than the controller). Once the FURL |
|
148 | running (which could be a different host than the controller). Once the FURL | |
149 | files are copied over, everything should work fine. |
|
149 | files are copied over, everything should work fine. | |
150 |
|
150 | |||
151 | Currently, there are three FURL files that the controller creates: |
|
151 | Currently, there are three FURL files that the controller creates: | |
152 |
|
152 | |||
153 | ipcontroller-engine.furl |
|
153 | ipcontroller-engine.furl | |
154 | This FURL file is the key that gives an engine the ability to connect |
|
154 | This FURL file is the key that gives an engine the ability to connect | |
155 | to a controller. |
|
155 | to a controller. | |
156 |
|
156 | |||
157 | ipcontroller-tc.furl |
|
157 | ipcontroller-tc.furl | |
158 | This FURL file is the key that a :class:`TaskClient` must use to |
|
158 | This FURL file is the key that a :class:`TaskClient` must use to | |
159 | connect to the task interface of a controller. |
|
159 | connect to the task interface of a controller. | |
160 |
|
160 | |||
161 | ipcontroller-mec.furl |
|
161 | ipcontroller-mec.furl | |
162 | This FURL file is the key that a :class:`MultiEngineClient` must use |
|
162 | This FURL file is the key that a :class:`MultiEngineClient` must use | |
163 | to connect to the multiengine interface of a controller. |
|
163 | to connect to the multiengine interface of a controller. | |
164 |
|
164 | |||
165 | More details of how these FURL files are used are given below. |
|
165 | More details of how these FURL files are used are given below. | |
166 |
|
166 | |||
167 | A detailed description of the security model and its implementation in IPython |
|
167 | A detailed description of the security model and its implementation in IPython | |
168 | can be found :ref:`here <parallelsecurity>`. |
|
168 | can be found :ref:`here <parallelsecurity>`. | |
169 |
|
169 | |||
170 | Getting Started |
|
170 | Getting Started | |
171 | =============== |
|
171 | =============== | |
172 |
|
172 | |||
173 | To use IPython for parallel computing, you need to start one instance of the |
|
173 | To use IPython for parallel computing, you need to start one instance of the | |
174 | controller and one or more instances of the engine. Initially, it is best to |
|
174 | controller and one or more instances of the engine. Initially, it is best to | |
175 | simply start a controller and engines on a single host using the |
|
175 | simply start a controller and engines on a single host using the | |
176 | :command:`ipcluster` command. To start a controller and 4 engines on your |
|
176 | :command:`ipcluster` command. To start a controller and 4 engines on your | |
177 | localhost, just do:: |
|
177 | localhost, just do:: | |
178 |
|
178 | |||
179 | $ ipcluster local -n 4 |
|
179 | $ ipcluster local -n 4 | |
180 |
|
180 | |||
181 | More details about starting the IPython controller and engines can be found |
|
181 | More details about starting the IPython controller and engines can be found | |
182 | :ref:`here <parallel_process>` |
|
182 | :ref:`here <parallel_process>` | |
183 |
|
183 | |||
184 | Once you have started the IPython controller and one or more engines, you |
|
184 | Once you have started the IPython controller and one or more engines, you | |
185 | are ready to use the engines to do something useful. To make sure |
|
185 | are ready to use the engines to do something useful. To make sure | |
186 | everything is working correctly, try the following commands: |
|
186 | everything is working correctly, try the following commands: | |
187 |
|
187 | |||
188 | .. sourcecode:: ipython |
|
188 | .. sourcecode:: ipython | |
189 |
|
189 | |||
190 | In [1]: from IPython.kernel import client |
|
190 | In [1]: from IPython.kernel import client | |
191 |
|
191 | |||
192 | In [2]: mec = client.MultiEngineClient() |
|
192 | In [2]: mec = client.MultiEngineClient() | |
193 |
|
193 | |||
194 | In [4]: mec.get_ids() |
|
194 | In [4]: mec.get_ids() | |
195 | Out[4]: [0, 1, 2, 3] |
|
195 | Out[4]: [0, 1, 2, 3] | |
196 |
|
196 | |||
197 | In [5]: mec.execute('print "Hello World"') |
|
197 | In [5]: mec.execute('print "Hello World"') | |
198 | Out[5]: |
|
198 | Out[5]: | |
199 | <Results List> |
|
199 | <Results List> | |
200 | [0] In [1]: print "Hello World" |
|
200 | [0] In [1]: print "Hello World" | |
201 | [0] Out[1]: Hello World |
|
201 | [0] Out[1]: Hello World | |
202 |
|
202 | |||
203 | [1] In [1]: print "Hello World" |
|
203 | [1] In [1]: print "Hello World" | |
204 | [1] Out[1]: Hello World |
|
204 | [1] Out[1]: Hello World | |
205 |
|
205 | |||
206 | [2] In [1]: print "Hello World" |
|
206 | [2] In [1]: print "Hello World" | |
207 | [2] Out[1]: Hello World |
|
207 | [2] Out[1]: Hello World | |
208 |
|
208 | |||
209 | [3] In [1]: print "Hello World" |
|
209 | [3] In [1]: print "Hello World" | |
210 | [3] Out[1]: Hello World |
|
210 | [3] Out[1]: Hello World | |
211 |
|
211 | |||
212 | Remember, a client also needs to present a FURL file to the controller. How |
|
212 | Remember, a client also needs to present a FURL file to the controller. How | |
213 | does this happen? When a multiengine client is created with no arguments, the |
|
213 | does this happen? When a multiengine client is created with no arguments, the | |
214 | client tries to find the corresponding FURL file in the local |
|
214 | client tries to find the corresponding FURL file in the local | |
215 |
:file:` |
|
215 | :file:`$IPYTHON_DIR/cluster_<profile>/security` directory. If it finds it, you are set. If you | |
216 | have put the FURL file in a different location or it has a different name, |
|
216 | have put the FURL file in a different location or it has a different name, | |
217 | create the client like this:: |
|
217 | create the client like this:: | |
218 |
|
218 | |||
219 | mec = client.MultiEngineClient('/path/to/my/ipcontroller-mec.furl') |
|
219 | mec = client.MultiEngineClient('/path/to/my/ipcontroller-mec.furl') | |
220 |
|
220 | |||
221 | Same thing hold true of creating a task client:: |
|
221 | Same thing hold true of creating a task client:: | |
222 |
|
222 | |||
223 | tc = client.TaskClient('/path/to/my/ipcontroller-tc.furl') |
|
223 | tc = client.TaskClient('/path/to/my/ipcontroller-tc.furl') | |
224 |
|
224 | |||
225 | You are now ready to learn more about the :ref:`MultiEngine |
|
225 | You are now ready to learn more about the :ref:`MultiEngine | |
226 | <parallelmultiengine>` and :ref:`Task <paralleltask>` interfaces to the |
|
226 | <parallelmultiengine>` and :ref:`Task <paralleltask>` interfaces to the | |
227 | controller. |
|
227 | controller. | |
228 |
|
228 | |||
229 | .. note:: |
|
229 | .. note:: | |
230 |
|
230 | |||
231 | Don't forget that the engine, multiengine client and task client all have |
|
231 | Don't forget that the engine, multiengine client and task client all have | |
232 | *different* furl files. You must move *each* of these around to an |
|
232 | *different* furl files. You must move *each* of these around to an | |
233 | appropriate location so that the engines and clients can use them to |
|
233 | appropriate location so that the engines and clients can use them to | |
234 | connect to the controller. |
|
234 | connect to the controller. | |
235 |
|
235 | |||
236 | .. [Capability] Capability-based security, http://en.wikipedia.org/wiki/Capability-based_security |
|
236 | .. [Capability] Capability-based security, http://en.wikipedia.org/wiki/Capability-based_security | |
237 |
|
237 |
@@ -1,835 +1,835 b'' | |||||
1 | .. _parallelmultiengine: |
|
1 | .. _parallelmultiengine: | |
2 |
|
2 | |||
3 | =============================== |
|
3 | =============================== | |
4 | IPython's multiengine interface |
|
4 | IPython's multiengine interface | |
5 | =============================== |
|
5 | =============================== | |
6 |
|
6 | |||
7 | The multiengine interface represents one possible way of working with a set of |
|
7 | The multiengine interface represents one possible way of working with a set of | |
8 | IPython engines. The basic idea behind the multiengine interface is that the |
|
8 | IPython engines. The basic idea behind the multiengine interface is that the | |
9 | capabilities of each engine are directly and explicitly exposed to the user. |
|
9 | capabilities of each engine are directly and explicitly exposed to the user. | |
10 | Thus, in the multiengine interface, each engine is given an id that is used to |
|
10 | Thus, in the multiengine interface, each engine is given an id that is used to | |
11 | identify the engine and give it work to do. This interface is very intuitive |
|
11 | identify the engine and give it work to do. This interface is very intuitive | |
12 | and is designed with interactive usage in mind, and is thus the best place for |
|
12 | and is designed with interactive usage in mind, and is thus the best place for | |
13 | new users of IPython to begin. |
|
13 | new users of IPython to begin. | |
14 |
|
14 | |||
15 | Starting the IPython controller and engines |
|
15 | Starting the IPython controller and engines | |
16 | =========================================== |
|
16 | =========================================== | |
17 |
|
17 | |||
18 | To follow along with this tutorial, you will need to start the IPython |
|
18 | To follow along with this tutorial, you will need to start the IPython | |
19 | controller and four IPython engines. The simplest way of doing this is to use |
|
19 | controller and four IPython engines. The simplest way of doing this is to use | |
20 | the :command:`ipcluster` command:: |
|
20 | the :command:`ipcluster` command:: | |
21 |
|
21 | |||
22 | $ ipcluster local -n 4 |
|
22 | $ ipcluster local -n 4 | |
23 |
|
23 | |||
24 | For more detailed information about starting the controller and engines, see |
|
24 | For more detailed information about starting the controller and engines, see | |
25 | our :ref:`introduction <ip1par>` to using IPython for parallel computing. |
|
25 | our :ref:`introduction <ip1par>` to using IPython for parallel computing. | |
26 |
|
26 | |||
27 | Creating a ``MultiEngineClient`` instance |
|
27 | Creating a ``MultiEngineClient`` instance | |
28 | ========================================= |
|
28 | ========================================= | |
29 |
|
29 | |||
30 | The first step is to import the IPython :mod:`IPython.kernel.client` module |
|
30 | The first step is to import the IPython :mod:`IPython.kernel.client` module | |
31 | and then create a :class:`MultiEngineClient` instance: |
|
31 | and then create a :class:`MultiEngineClient` instance: | |
32 |
|
32 | |||
33 | .. sourcecode:: ipython |
|
33 | .. sourcecode:: ipython | |
34 |
|
34 | |||
35 | In [1]: from IPython.kernel import client |
|
35 | In [1]: from IPython.kernel import client | |
36 |
|
36 | |||
37 | In [2]: mec = client.MultiEngineClient() |
|
37 | In [2]: mec = client.MultiEngineClient() | |
38 |
|
38 | |||
39 | This form assumes that the :file:`ipcontroller-mec.furl` is in the |
|
39 | This form assumes that the :file:`ipcontroller-mec.furl` is in the | |
40 |
:file:` |
|
40 | :file:`$IPYTHON_DIR/cluster_<profile>/security` directory on the client's host. If not, the | |
41 | location of the FURL file must be given as an argument to the |
|
41 | location of the FURL file must be given as an argument to the | |
42 | constructor: |
|
42 | constructor: | |
43 |
|
43 | |||
44 | .. sourcecode:: ipython |
|
44 | .. sourcecode:: ipython | |
45 |
|
45 | |||
46 | In [2]: mec = client.MultiEngineClient('/path/to/my/ipcontroller-mec.furl') |
|
46 | In [2]: mec = client.MultiEngineClient('/path/to/my/ipcontroller-mec.furl') | |
47 |
|
47 | |||
48 | To make sure there are engines connected to the controller, use can get a list |
|
48 | To make sure there are engines connected to the controller, use can get a list | |
49 | of engine ids: |
|
49 | of engine ids: | |
50 |
|
50 | |||
51 | .. sourcecode:: ipython |
|
51 | .. sourcecode:: ipython | |
52 |
|
52 | |||
53 | In [3]: mec.get_ids() |
|
53 | In [3]: mec.get_ids() | |
54 | Out[3]: [0, 1, 2, 3] |
|
54 | Out[3]: [0, 1, 2, 3] | |
55 |
|
55 | |||
56 | Here we see that there are four engines ready to do work for us. |
|
56 | Here we see that there are four engines ready to do work for us. | |
57 |
|
57 | |||
58 | Quick and easy parallelism |
|
58 | Quick and easy parallelism | |
59 | ========================== |
|
59 | ========================== | |
60 |
|
60 | |||
61 | In many cases, you simply want to apply a Python function to a sequence of |
|
61 | In many cases, you simply want to apply a Python function to a sequence of | |
62 | objects, but *in parallel*. The multiengine interface provides two simple ways |
|
62 | objects, but *in parallel*. The multiengine interface provides two simple ways | |
63 | of accomplishing this: a parallel version of :func:`map` and ``@parallel`` |
|
63 | of accomplishing this: a parallel version of :func:`map` and ``@parallel`` | |
64 | function decorator. |
|
64 | function decorator. | |
65 |
|
65 | |||
66 | Parallel map |
|
66 | Parallel map | |
67 | ------------ |
|
67 | ------------ | |
68 |
|
68 | |||
69 | Python's builtin :func:`map` functions allows a function to be applied to a |
|
69 | Python's builtin :func:`map` functions allows a function to be applied to a | |
70 | sequence element-by-element. This type of code is typically trivial to |
|
70 | sequence element-by-element. This type of code is typically trivial to | |
71 | parallelize. In fact, the multiengine interface in IPython already has a |
|
71 | parallelize. In fact, the multiengine interface in IPython already has a | |
72 | parallel version of :meth:`map` that works just like its serial counterpart: |
|
72 | parallel version of :meth:`map` that works just like its serial counterpart: | |
73 |
|
73 | |||
74 | .. sourcecode:: ipython |
|
74 | .. sourcecode:: ipython | |
75 |
|
75 | |||
76 | In [63]: serial_result = map(lambda x:x**10, range(32)) |
|
76 | In [63]: serial_result = map(lambda x:x**10, range(32)) | |
77 |
|
77 | |||
78 | In [64]: parallel_result = mec.map(lambda x:x**10, range(32)) |
|
78 | In [64]: parallel_result = mec.map(lambda x:x**10, range(32)) | |
79 |
|
79 | |||
80 | In [65]: serial_result==parallel_result |
|
80 | In [65]: serial_result==parallel_result | |
81 | Out[65]: True |
|
81 | Out[65]: True | |
82 |
|
82 | |||
83 | .. note:: |
|
83 | .. note:: | |
84 |
|
84 | |||
85 | The multiengine interface version of :meth:`map` does not do any load |
|
85 | The multiengine interface version of :meth:`map` does not do any load | |
86 | balancing. For a load balanced version, see the task interface. |
|
86 | balancing. For a load balanced version, see the task interface. | |
87 |
|
87 | |||
88 | .. seealso:: |
|
88 | .. seealso:: | |
89 |
|
89 | |||
90 | The :meth:`map` method has a number of options that can be controlled by |
|
90 | The :meth:`map` method has a number of options that can be controlled by | |
91 | the :meth:`mapper` method. See its docstring for more information. |
|
91 | the :meth:`mapper` method. See its docstring for more information. | |
92 |
|
92 | |||
93 | Parallel function decorator |
|
93 | Parallel function decorator | |
94 | --------------------------- |
|
94 | --------------------------- | |
95 |
|
95 | |||
96 | Parallel functions are just like normal function, but they can be called on |
|
96 | Parallel functions are just like normal function, but they can be called on | |
97 | sequences and *in parallel*. The multiengine interface provides a decorator |
|
97 | sequences and *in parallel*. The multiengine interface provides a decorator | |
98 | that turns any Python function into a parallel function: |
|
98 | that turns any Python function into a parallel function: | |
99 |
|
99 | |||
100 | .. sourcecode:: ipython |
|
100 | .. sourcecode:: ipython | |
101 |
|
101 | |||
102 | In [10]: @mec.parallel() |
|
102 | In [10]: @mec.parallel() | |
103 | ....: def f(x): |
|
103 | ....: def f(x): | |
104 | ....: return 10.0*x**4 |
|
104 | ....: return 10.0*x**4 | |
105 | ....: |
|
105 | ....: | |
106 |
|
106 | |||
107 | In [11]: f(range(32)) # this is done in parallel |
|
107 | In [11]: f(range(32)) # this is done in parallel | |
108 | Out[11]: |
|
108 | Out[11]: | |
109 | [0.0,10.0,160.0,...] |
|
109 | [0.0,10.0,160.0,...] | |
110 |
|
110 | |||
111 | See the docstring for the :meth:`parallel` decorator for options. |
|
111 | See the docstring for the :meth:`parallel` decorator for options. | |
112 |
|
112 | |||
113 | Running Python commands |
|
113 | Running Python commands | |
114 | ======================= |
|
114 | ======================= | |
115 |
|
115 | |||
116 | The most basic type of operation that can be performed on the engines is to |
|
116 | The most basic type of operation that can be performed on the engines is to | |
117 | execute Python code. Executing Python code can be done in blocking or |
|
117 | execute Python code. Executing Python code can be done in blocking or | |
118 | non-blocking mode (blocking is default) using the :meth:`execute` method. |
|
118 | non-blocking mode (blocking is default) using the :meth:`execute` method. | |
119 |
|
119 | |||
120 | Blocking execution |
|
120 | Blocking execution | |
121 | ------------------ |
|
121 | ------------------ | |
122 |
|
122 | |||
123 | In blocking mode, the :class:`MultiEngineClient` object (called ``mec`` in |
|
123 | In blocking mode, the :class:`MultiEngineClient` object (called ``mec`` in | |
124 | these examples) submits the command to the controller, which places the |
|
124 | these examples) submits the command to the controller, which places the | |
125 | command in the engines' queues for execution. The :meth:`execute` call then |
|
125 | command in the engines' queues for execution. The :meth:`execute` call then | |
126 | blocks until the engines are done executing the command: |
|
126 | blocks until the engines are done executing the command: | |
127 |
|
127 | |||
128 | .. sourcecode:: ipython |
|
128 | .. sourcecode:: ipython | |
129 |
|
129 | |||
130 | # The default is to run on all engines |
|
130 | # The default is to run on all engines | |
131 | In [4]: mec.execute('a=5') |
|
131 | In [4]: mec.execute('a=5') | |
132 | Out[4]: |
|
132 | Out[4]: | |
133 | <Results List> |
|
133 | <Results List> | |
134 | [0] In [1]: a=5 |
|
134 | [0] In [1]: a=5 | |
135 | [1] In [1]: a=5 |
|
135 | [1] In [1]: a=5 | |
136 | [2] In [1]: a=5 |
|
136 | [2] In [1]: a=5 | |
137 | [3] In [1]: a=5 |
|
137 | [3] In [1]: a=5 | |
138 |
|
138 | |||
139 | In [5]: mec.execute('b=10') |
|
139 | In [5]: mec.execute('b=10') | |
140 | Out[5]: |
|
140 | Out[5]: | |
141 | <Results List> |
|
141 | <Results List> | |
142 | [0] In [2]: b=10 |
|
142 | [0] In [2]: b=10 | |
143 | [1] In [2]: b=10 |
|
143 | [1] In [2]: b=10 | |
144 | [2] In [2]: b=10 |
|
144 | [2] In [2]: b=10 | |
145 | [3] In [2]: b=10 |
|
145 | [3] In [2]: b=10 | |
146 |
|
146 | |||
147 | Python commands can be executed on specific engines by calling execute using |
|
147 | Python commands can be executed on specific engines by calling execute using | |
148 | the ``targets`` keyword argument: |
|
148 | the ``targets`` keyword argument: | |
149 |
|
149 | |||
150 | .. sourcecode:: ipython |
|
150 | .. sourcecode:: ipython | |
151 |
|
151 | |||
152 | In [6]: mec.execute('c=a+b',targets=[0,2]) |
|
152 | In [6]: mec.execute('c=a+b',targets=[0,2]) | |
153 | Out[6]: |
|
153 | Out[6]: | |
154 | <Results List> |
|
154 | <Results List> | |
155 | [0] In [3]: c=a+b |
|
155 | [0] In [3]: c=a+b | |
156 | [2] In [3]: c=a+b |
|
156 | [2] In [3]: c=a+b | |
157 |
|
157 | |||
158 |
|
158 | |||
159 | In [7]: mec.execute('c=a-b',targets=[1,3]) |
|
159 | In [7]: mec.execute('c=a-b',targets=[1,3]) | |
160 | Out[7]: |
|
160 | Out[7]: | |
161 | <Results List> |
|
161 | <Results List> | |
162 | [1] In [3]: c=a-b |
|
162 | [1] In [3]: c=a-b | |
163 | [3] In [3]: c=a-b |
|
163 | [3] In [3]: c=a-b | |
164 |
|
164 | |||
165 |
|
165 | |||
166 | In [8]: mec.execute('print c') |
|
166 | In [8]: mec.execute('print c') | |
167 | Out[8]: |
|
167 | Out[8]: | |
168 | <Results List> |
|
168 | <Results List> | |
169 | [0] In [4]: print c |
|
169 | [0] In [4]: print c | |
170 | [0] Out[4]: 15 |
|
170 | [0] Out[4]: 15 | |
171 |
|
171 | |||
172 | [1] In [4]: print c |
|
172 | [1] In [4]: print c | |
173 | [1] Out[4]: -5 |
|
173 | [1] Out[4]: -5 | |
174 |
|
174 | |||
175 | [2] In [4]: print c |
|
175 | [2] In [4]: print c | |
176 | [2] Out[4]: 15 |
|
176 | [2] Out[4]: 15 | |
177 |
|
177 | |||
178 | [3] In [4]: print c |
|
178 | [3] In [4]: print c | |
179 | [3] Out[4]: -5 |
|
179 | [3] Out[4]: -5 | |
180 |
|
180 | |||
181 | This example also shows one of the most important things about the IPython |
|
181 | This example also shows one of the most important things about the IPython | |
182 | engines: they have a persistent user namespaces. The :meth:`execute` method |
|
182 | engines: they have a persistent user namespaces. The :meth:`execute` method | |
183 | returns a Python ``dict`` that contains useful information: |
|
183 | returns a Python ``dict`` that contains useful information: | |
184 |
|
184 | |||
185 | .. sourcecode:: ipython |
|
185 | .. sourcecode:: ipython | |
186 |
|
186 | |||
187 | In [9]: result_dict = mec.execute('d=10; print d') |
|
187 | In [9]: result_dict = mec.execute('d=10; print d') | |
188 |
|
188 | |||
189 | In [10]: for r in result_dict: |
|
189 | In [10]: for r in result_dict: | |
190 | ....: print r |
|
190 | ....: print r | |
191 | ....: |
|
191 | ....: | |
192 | ....: |
|
192 | ....: | |
193 | {'input': {'translated': 'd=10; print d', 'raw': 'd=10; print d'}, 'number': 5, 'id': 0, 'stdout': '10\n'} |
|
193 | {'input': {'translated': 'd=10; print d', 'raw': 'd=10; print d'}, 'number': 5, 'id': 0, 'stdout': '10\n'} | |
194 | {'input': {'translated': 'd=10; print d', 'raw': 'd=10; print d'}, 'number': 5, 'id': 1, 'stdout': '10\n'} |
|
194 | {'input': {'translated': 'd=10; print d', 'raw': 'd=10; print d'}, 'number': 5, 'id': 1, 'stdout': '10\n'} | |
195 | {'input': {'translated': 'd=10; print d', 'raw': 'd=10; print d'}, 'number': 5, 'id': 2, 'stdout': '10\n'} |
|
195 | {'input': {'translated': 'd=10; print d', 'raw': 'd=10; print d'}, 'number': 5, 'id': 2, 'stdout': '10\n'} | |
196 | {'input': {'translated': 'd=10; print d', 'raw': 'd=10; print d'}, 'number': 5, 'id': 3, 'stdout': '10\n'} |
|
196 | {'input': {'translated': 'd=10; print d', 'raw': 'd=10; print d'}, 'number': 5, 'id': 3, 'stdout': '10\n'} | |
197 |
|
197 | |||
198 | Non-blocking execution |
|
198 | Non-blocking execution | |
199 | ---------------------- |
|
199 | ---------------------- | |
200 |
|
200 | |||
201 | In non-blocking mode, :meth:`execute` submits the command to be executed and |
|
201 | In non-blocking mode, :meth:`execute` submits the command to be executed and | |
202 | then returns a :class:`PendingResult` object immediately. The |
|
202 | then returns a :class:`PendingResult` object immediately. The | |
203 | :class:`PendingResult` object gives you a way of getting a result at a later |
|
203 | :class:`PendingResult` object gives you a way of getting a result at a later | |
204 | time through its :meth:`get_result` method or :attr:`r` attribute. This allows |
|
204 | time through its :meth:`get_result` method or :attr:`r` attribute. This allows | |
205 | you to quickly submit long running commands without blocking your local |
|
205 | you to quickly submit long running commands without blocking your local | |
206 | Python/IPython session: |
|
206 | Python/IPython session: | |
207 |
|
207 | |||
208 | .. sourcecode:: ipython |
|
208 | .. sourcecode:: ipython | |
209 |
|
209 | |||
210 | # In blocking mode |
|
210 | # In blocking mode | |
211 | In [6]: mec.execute('import time') |
|
211 | In [6]: mec.execute('import time') | |
212 | Out[6]: |
|
212 | Out[6]: | |
213 | <Results List> |
|
213 | <Results List> | |
214 | [0] In [1]: import time |
|
214 | [0] In [1]: import time | |
215 | [1] In [1]: import time |
|
215 | [1] In [1]: import time | |
216 | [2] In [1]: import time |
|
216 | [2] In [1]: import time | |
217 | [3] In [1]: import time |
|
217 | [3] In [1]: import time | |
218 |
|
218 | |||
219 | # In non-blocking mode |
|
219 | # In non-blocking mode | |
220 | In [7]: pr = mec.execute('time.sleep(10)',block=False) |
|
220 | In [7]: pr = mec.execute('time.sleep(10)',block=False) | |
221 |
|
221 | |||
222 | # Now block for the result |
|
222 | # Now block for the result | |
223 | In [8]: pr.get_result() |
|
223 | In [8]: pr.get_result() | |
224 | Out[8]: |
|
224 | Out[8]: | |
225 | <Results List> |
|
225 | <Results List> | |
226 | [0] In [2]: time.sleep(10) |
|
226 | [0] In [2]: time.sleep(10) | |
227 | [1] In [2]: time.sleep(10) |
|
227 | [1] In [2]: time.sleep(10) | |
228 | [2] In [2]: time.sleep(10) |
|
228 | [2] In [2]: time.sleep(10) | |
229 | [3] In [2]: time.sleep(10) |
|
229 | [3] In [2]: time.sleep(10) | |
230 |
|
230 | |||
231 | # Again in non-blocking mode |
|
231 | # Again in non-blocking mode | |
232 | In [9]: pr = mec.execute('time.sleep(10)',block=False) |
|
232 | In [9]: pr = mec.execute('time.sleep(10)',block=False) | |
233 |
|
233 | |||
234 | # Poll to see if the result is ready |
|
234 | # Poll to see if the result is ready | |
235 | In [10]: pr.get_result(block=False) |
|
235 | In [10]: pr.get_result(block=False) | |
236 |
|
236 | |||
237 | # A shorthand for get_result(block=True) |
|
237 | # A shorthand for get_result(block=True) | |
238 | In [11]: pr.r |
|
238 | In [11]: pr.r | |
239 | Out[11]: |
|
239 | Out[11]: | |
240 | <Results List> |
|
240 | <Results List> | |
241 | [0] In [3]: time.sleep(10) |
|
241 | [0] In [3]: time.sleep(10) | |
242 | [1] In [3]: time.sleep(10) |
|
242 | [1] In [3]: time.sleep(10) | |
243 | [2] In [3]: time.sleep(10) |
|
243 | [2] In [3]: time.sleep(10) | |
244 | [3] In [3]: time.sleep(10) |
|
244 | [3] In [3]: time.sleep(10) | |
245 |
|
245 | |||
246 | Often, it is desirable to wait until a set of :class:`PendingResult` objects |
|
246 | Often, it is desirable to wait until a set of :class:`PendingResult` objects | |
247 | are done. For this, there is a the method :meth:`barrier`. This method takes a |
|
247 | are done. For this, there is a the method :meth:`barrier`. This method takes a | |
248 | tuple of :class:`PendingResult` objects and blocks until all of the associated |
|
248 | tuple of :class:`PendingResult` objects and blocks until all of the associated | |
249 | results are ready: |
|
249 | results are ready: | |
250 |
|
250 | |||
251 | .. sourcecode:: ipython |
|
251 | .. sourcecode:: ipython | |
252 |
|
252 | |||
253 | In [72]: mec.block=False |
|
253 | In [72]: mec.block=False | |
254 |
|
254 | |||
255 | # A trivial list of PendingResults objects |
|
255 | # A trivial list of PendingResults objects | |
256 | In [73]: pr_list = [mec.execute('time.sleep(3)') for i in range(10)] |
|
256 | In [73]: pr_list = [mec.execute('time.sleep(3)') for i in range(10)] | |
257 |
|
257 | |||
258 | # Wait until all of them are done |
|
258 | # Wait until all of them are done | |
259 | In [74]: mec.barrier(pr_list) |
|
259 | In [74]: mec.barrier(pr_list) | |
260 |
|
260 | |||
261 | # Then, their results are ready using get_result or the r attribute |
|
261 | # Then, their results are ready using get_result or the r attribute | |
262 | In [75]: pr_list[0].r |
|
262 | In [75]: pr_list[0].r | |
263 | Out[75]: |
|
263 | Out[75]: | |
264 | <Results List> |
|
264 | <Results List> | |
265 | [0] In [20]: time.sleep(3) |
|
265 | [0] In [20]: time.sleep(3) | |
266 | [1] In [19]: time.sleep(3) |
|
266 | [1] In [19]: time.sleep(3) | |
267 | [2] In [20]: time.sleep(3) |
|
267 | [2] In [20]: time.sleep(3) | |
268 | [3] In [19]: time.sleep(3) |
|
268 | [3] In [19]: time.sleep(3) | |
269 |
|
269 | |||
270 |
|
270 | |||
271 | The ``block`` and ``targets`` keyword arguments and attributes |
|
271 | The ``block`` and ``targets`` keyword arguments and attributes | |
272 | -------------------------------------------------------------- |
|
272 | -------------------------------------------------------------- | |
273 |
|
273 | |||
274 | Most methods in the multiengine interface (like :meth:`execute`) accept |
|
274 | Most methods in the multiengine interface (like :meth:`execute`) accept | |
275 | ``block`` and ``targets`` as keyword arguments. As we have seen above, these |
|
275 | ``block`` and ``targets`` as keyword arguments. As we have seen above, these | |
276 | keyword arguments control the blocking mode and which engines the command is |
|
276 | keyword arguments control the blocking mode and which engines the command is | |
277 | applied to. The :class:`MultiEngineClient` class also has :attr:`block` and |
|
277 | applied to. The :class:`MultiEngineClient` class also has :attr:`block` and | |
278 | :attr:`targets` attributes that control the default behavior when the keyword |
|
278 | :attr:`targets` attributes that control the default behavior when the keyword | |
279 | arguments are not provided. Thus the following logic is used for :attr:`block` |
|
279 | arguments are not provided. Thus the following logic is used for :attr:`block` | |
280 | and :attr:`targets`: |
|
280 | and :attr:`targets`: | |
281 |
|
281 | |||
282 | * If no keyword argument is provided, the instance attributes are used. |
|
282 | * If no keyword argument is provided, the instance attributes are used. | |
283 | * Keyword argument, if provided override the instance attributes. |
|
283 | * Keyword argument, if provided override the instance attributes. | |
284 |
|
284 | |||
285 | The following examples demonstrate how to use the instance attributes: |
|
285 | The following examples demonstrate how to use the instance attributes: | |
286 |
|
286 | |||
287 | .. sourcecode:: ipython |
|
287 | .. sourcecode:: ipython | |
288 |
|
288 | |||
289 | In [16]: mec.targets = [0,2] |
|
289 | In [16]: mec.targets = [0,2] | |
290 |
|
290 | |||
291 | In [17]: mec.block = False |
|
291 | In [17]: mec.block = False | |
292 |
|
292 | |||
293 | In [18]: pr = mec.execute('a=5') |
|
293 | In [18]: pr = mec.execute('a=5') | |
294 |
|
294 | |||
295 | In [19]: pr.r |
|
295 | In [19]: pr.r | |
296 | Out[19]: |
|
296 | Out[19]: | |
297 | <Results List> |
|
297 | <Results List> | |
298 | [0] In [6]: a=5 |
|
298 | [0] In [6]: a=5 | |
299 | [2] In [6]: a=5 |
|
299 | [2] In [6]: a=5 | |
300 |
|
300 | |||
301 | # Note targets='all' means all engines |
|
301 | # Note targets='all' means all engines | |
302 | In [20]: mec.targets = 'all' |
|
302 | In [20]: mec.targets = 'all' | |
303 |
|
303 | |||
304 | In [21]: mec.block = True |
|
304 | In [21]: mec.block = True | |
305 |
|
305 | |||
306 | In [22]: mec.execute('b=10; print b') |
|
306 | In [22]: mec.execute('b=10; print b') | |
307 | Out[22]: |
|
307 | Out[22]: | |
308 | <Results List> |
|
308 | <Results List> | |
309 | [0] In [7]: b=10; print b |
|
309 | [0] In [7]: b=10; print b | |
310 | [0] Out[7]: 10 |
|
310 | [0] Out[7]: 10 | |
311 |
|
311 | |||
312 | [1] In [6]: b=10; print b |
|
312 | [1] In [6]: b=10; print b | |
313 | [1] Out[6]: 10 |
|
313 | [1] Out[6]: 10 | |
314 |
|
314 | |||
315 | [2] In [7]: b=10; print b |
|
315 | [2] In [7]: b=10; print b | |
316 | [2] Out[7]: 10 |
|
316 | [2] Out[7]: 10 | |
317 |
|
317 | |||
318 | [3] In [6]: b=10; print b |
|
318 | [3] In [6]: b=10; print b | |
319 | [3] Out[6]: 10 |
|
319 | [3] Out[6]: 10 | |
320 |
|
320 | |||
321 | The :attr:`block` and :attr:`targets` instance attributes also determine the |
|
321 | The :attr:`block` and :attr:`targets` instance attributes also determine the | |
322 | behavior of the parallel magic commands. |
|
322 | behavior of the parallel magic commands. | |
323 |
|
323 | |||
324 |
|
324 | |||
325 | Parallel magic commands |
|
325 | Parallel magic commands | |
326 | ----------------------- |
|
326 | ----------------------- | |
327 |
|
327 | |||
328 | We provide a few IPython magic commands (``%px``, ``%autopx`` and ``%result``) |
|
328 | We provide a few IPython magic commands (``%px``, ``%autopx`` and ``%result``) | |
329 | that make it more pleasant to execute Python commands on the engines |
|
329 | that make it more pleasant to execute Python commands on the engines | |
330 | interactively. These are simply shortcuts to :meth:`execute` and |
|
330 | interactively. These are simply shortcuts to :meth:`execute` and | |
331 | :meth:`get_result`. The ``%px`` magic executes a single Python command on the |
|
331 | :meth:`get_result`. The ``%px`` magic executes a single Python command on the | |
332 | engines specified by the :attr:`targets` attribute of the |
|
332 | engines specified by the :attr:`targets` attribute of the | |
333 | :class:`MultiEngineClient` instance (by default this is ``'all'``): |
|
333 | :class:`MultiEngineClient` instance (by default this is ``'all'``): | |
334 |
|
334 | |||
335 | .. sourcecode:: ipython |
|
335 | .. sourcecode:: ipython | |
336 |
|
336 | |||
337 | # Make this MultiEngineClient active for parallel magic commands |
|
337 | # Make this MultiEngineClient active for parallel magic commands | |
338 | In [23]: mec.activate() |
|
338 | In [23]: mec.activate() | |
339 |
|
339 | |||
340 | In [24]: mec.block=True |
|
340 | In [24]: mec.block=True | |
341 |
|
341 | |||
342 | In [25]: import numpy |
|
342 | In [25]: import numpy | |
343 |
|
343 | |||
344 | In [26]: %px import numpy |
|
344 | In [26]: %px import numpy | |
345 | Executing command on Controller |
|
345 | Executing command on Controller | |
346 | Out[26]: |
|
346 | Out[26]: | |
347 | <Results List> |
|
347 | <Results List> | |
348 | [0] In [8]: import numpy |
|
348 | [0] In [8]: import numpy | |
349 | [1] In [7]: import numpy |
|
349 | [1] In [7]: import numpy | |
350 | [2] In [8]: import numpy |
|
350 | [2] In [8]: import numpy | |
351 | [3] In [7]: import numpy |
|
351 | [3] In [7]: import numpy | |
352 |
|
352 | |||
353 |
|
353 | |||
354 | In [27]: %px a = numpy.random.rand(2,2) |
|
354 | In [27]: %px a = numpy.random.rand(2,2) | |
355 | Executing command on Controller |
|
355 | Executing command on Controller | |
356 | Out[27]: |
|
356 | Out[27]: | |
357 | <Results List> |
|
357 | <Results List> | |
358 | [0] In [9]: a = numpy.random.rand(2,2) |
|
358 | [0] In [9]: a = numpy.random.rand(2,2) | |
359 | [1] In [8]: a = numpy.random.rand(2,2) |
|
359 | [1] In [8]: a = numpy.random.rand(2,2) | |
360 | [2] In [9]: a = numpy.random.rand(2,2) |
|
360 | [2] In [9]: a = numpy.random.rand(2,2) | |
361 | [3] In [8]: a = numpy.random.rand(2,2) |
|
361 | [3] In [8]: a = numpy.random.rand(2,2) | |
362 |
|
362 | |||
363 |
|
363 | |||
364 | In [28]: %px print numpy.linalg.eigvals(a) |
|
364 | In [28]: %px print numpy.linalg.eigvals(a) | |
365 | Executing command on Controller |
|
365 | Executing command on Controller | |
366 | Out[28]: |
|
366 | Out[28]: | |
367 | <Results List> |
|
367 | <Results List> | |
368 | [0] In [10]: print numpy.linalg.eigvals(a) |
|
368 | [0] In [10]: print numpy.linalg.eigvals(a) | |
369 | [0] Out[10]: [ 1.28167017 0.14197338] |
|
369 | [0] Out[10]: [ 1.28167017 0.14197338] | |
370 |
|
370 | |||
371 | [1] In [9]: print numpy.linalg.eigvals(a) |
|
371 | [1] In [9]: print numpy.linalg.eigvals(a) | |
372 | [1] Out[9]: [-0.14093616 1.27877273] |
|
372 | [1] Out[9]: [-0.14093616 1.27877273] | |
373 |
|
373 | |||
374 | [2] In [10]: print numpy.linalg.eigvals(a) |
|
374 | [2] In [10]: print numpy.linalg.eigvals(a) | |
375 | [2] Out[10]: [-0.37023573 1.06779409] |
|
375 | [2] Out[10]: [-0.37023573 1.06779409] | |
376 |
|
376 | |||
377 | [3] In [9]: print numpy.linalg.eigvals(a) |
|
377 | [3] In [9]: print numpy.linalg.eigvals(a) | |
378 | [3] Out[9]: [ 0.83664764 -0.25602658] |
|
378 | [3] Out[9]: [ 0.83664764 -0.25602658] | |
379 |
|
379 | |||
380 | The ``%result`` magic gets and prints the stdin/stdout/stderr of the last |
|
380 | The ``%result`` magic gets and prints the stdin/stdout/stderr of the last | |
381 | command executed on each engine. It is simply a shortcut to the |
|
381 | command executed on each engine. It is simply a shortcut to the | |
382 | :meth:`get_result` method: |
|
382 | :meth:`get_result` method: | |
383 |
|
383 | |||
384 | .. sourcecode:: ipython |
|
384 | .. sourcecode:: ipython | |
385 |
|
385 | |||
386 | In [29]: %result |
|
386 | In [29]: %result | |
387 | Out[29]: |
|
387 | Out[29]: | |
388 | <Results List> |
|
388 | <Results List> | |
389 | [0] In [10]: print numpy.linalg.eigvals(a) |
|
389 | [0] In [10]: print numpy.linalg.eigvals(a) | |
390 | [0] Out[10]: [ 1.28167017 0.14197338] |
|
390 | [0] Out[10]: [ 1.28167017 0.14197338] | |
391 |
|
391 | |||
392 | [1] In [9]: print numpy.linalg.eigvals(a) |
|
392 | [1] In [9]: print numpy.linalg.eigvals(a) | |
393 | [1] Out[9]: [-0.14093616 1.27877273] |
|
393 | [1] Out[9]: [-0.14093616 1.27877273] | |
394 |
|
394 | |||
395 | [2] In [10]: print numpy.linalg.eigvals(a) |
|
395 | [2] In [10]: print numpy.linalg.eigvals(a) | |
396 | [2] Out[10]: [-0.37023573 1.06779409] |
|
396 | [2] Out[10]: [-0.37023573 1.06779409] | |
397 |
|
397 | |||
398 | [3] In [9]: print numpy.linalg.eigvals(a) |
|
398 | [3] In [9]: print numpy.linalg.eigvals(a) | |
399 | [3] Out[9]: [ 0.83664764 -0.25602658] |
|
399 | [3] Out[9]: [ 0.83664764 -0.25602658] | |
400 |
|
400 | |||
401 | The ``%autopx`` magic switches to a mode where everything you type is executed |
|
401 | The ``%autopx`` magic switches to a mode where everything you type is executed | |
402 | on the engines given by the :attr:`targets` attribute: |
|
402 | on the engines given by the :attr:`targets` attribute: | |
403 |
|
403 | |||
404 | .. sourcecode:: ipython |
|
404 | .. sourcecode:: ipython | |
405 |
|
405 | |||
406 | In [30]: mec.block=False |
|
406 | In [30]: mec.block=False | |
407 |
|
407 | |||
408 | In [31]: %autopx |
|
408 | In [31]: %autopx | |
409 | Auto Parallel Enabled |
|
409 | Auto Parallel Enabled | |
410 | Type %autopx to disable |
|
410 | Type %autopx to disable | |
411 |
|
411 | |||
412 | In [32]: max_evals = [] |
|
412 | In [32]: max_evals = [] | |
413 | <IPython.kernel.multiengineclient.PendingResult object at 0x17b8a70> |
|
413 | <IPython.kernel.multiengineclient.PendingResult object at 0x17b8a70> | |
414 |
|
414 | |||
415 | In [33]: for i in range(100): |
|
415 | In [33]: for i in range(100): | |
416 | ....: a = numpy.random.rand(10,10) |
|
416 | ....: a = numpy.random.rand(10,10) | |
417 | ....: a = a+a.transpose() |
|
417 | ....: a = a+a.transpose() | |
418 | ....: evals = numpy.linalg.eigvals(a) |
|
418 | ....: evals = numpy.linalg.eigvals(a) | |
419 | ....: max_evals.append(evals[0].real) |
|
419 | ....: max_evals.append(evals[0].real) | |
420 | ....: |
|
420 | ....: | |
421 | ....: |
|
421 | ....: | |
422 | <IPython.kernel.multiengineclient.PendingResult object at 0x17af8f0> |
|
422 | <IPython.kernel.multiengineclient.PendingResult object at 0x17af8f0> | |
423 |
|
423 | |||
424 | In [34]: %autopx |
|
424 | In [34]: %autopx | |
425 | Auto Parallel Disabled |
|
425 | Auto Parallel Disabled | |
426 |
|
426 | |||
427 | In [35]: mec.block=True |
|
427 | In [35]: mec.block=True | |
428 |
|
428 | |||
429 | In [36]: px print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) |
|
429 | In [36]: px print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) | |
430 | Executing command on Controller |
|
430 | Executing command on Controller | |
431 | Out[36]: |
|
431 | Out[36]: | |
432 | <Results List> |
|
432 | <Results List> | |
433 | [0] In [13]: print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) |
|
433 | [0] In [13]: print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) | |
434 | [0] Out[13]: Average max eigenvalue is: 10.1387247332 |
|
434 | [0] Out[13]: Average max eigenvalue is: 10.1387247332 | |
435 |
|
435 | |||
436 | [1] In [12]: print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) |
|
436 | [1] In [12]: print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) | |
437 | [1] Out[12]: Average max eigenvalue is: 10.2076902286 |
|
437 | [1] Out[12]: Average max eigenvalue is: 10.2076902286 | |
438 |
|
438 | |||
439 | [2] In [13]: print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) |
|
439 | [2] In [13]: print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) | |
440 | [2] Out[13]: Average max eigenvalue is: 10.1891484655 |
|
440 | [2] Out[13]: Average max eigenvalue is: 10.1891484655 | |
441 |
|
441 | |||
442 | [3] In [12]: print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) |
|
442 | [3] In [12]: print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) | |
443 | [3] Out[12]: Average max eigenvalue is: 10.1158837784 |
|
443 | [3] Out[12]: Average max eigenvalue is: 10.1158837784 | |
444 |
|
444 | |||
445 |
|
445 | |||
446 | Moving Python objects around |
|
446 | Moving Python objects around | |
447 | ============================ |
|
447 | ============================ | |
448 |
|
448 | |||
449 | In addition to executing code on engines, you can transfer Python objects to |
|
449 | In addition to executing code on engines, you can transfer Python objects to | |
450 | and from your IPython session and the engines. In IPython, these operations |
|
450 | and from your IPython session and the engines. In IPython, these operations | |
451 | are called :meth:`push` (sending an object to the engines) and :meth:`pull` |
|
451 | are called :meth:`push` (sending an object to the engines) and :meth:`pull` | |
452 | (getting an object from the engines). |
|
452 | (getting an object from the engines). | |
453 |
|
453 | |||
454 | Basic push and pull |
|
454 | Basic push and pull | |
455 | ------------------- |
|
455 | ------------------- | |
456 |
|
456 | |||
457 | Here are some examples of how you use :meth:`push` and :meth:`pull`: |
|
457 | Here are some examples of how you use :meth:`push` and :meth:`pull`: | |
458 |
|
458 | |||
459 | .. sourcecode:: ipython |
|
459 | .. sourcecode:: ipython | |
460 |
|
460 | |||
461 | In [38]: mec.push(dict(a=1.03234,b=3453)) |
|
461 | In [38]: mec.push(dict(a=1.03234,b=3453)) | |
462 | Out[38]: [None, None, None, None] |
|
462 | Out[38]: [None, None, None, None] | |
463 |
|
463 | |||
464 | In [39]: mec.pull('a') |
|
464 | In [39]: mec.pull('a') | |
465 | Out[39]: [1.03234, 1.03234, 1.03234, 1.03234] |
|
465 | Out[39]: [1.03234, 1.03234, 1.03234, 1.03234] | |
466 |
|
466 | |||
467 | In [40]: mec.pull('b',targets=0) |
|
467 | In [40]: mec.pull('b',targets=0) | |
468 | Out[40]: [3453] |
|
468 | Out[40]: [3453] | |
469 |
|
469 | |||
470 | In [41]: mec.pull(('a','b')) |
|
470 | In [41]: mec.pull(('a','b')) | |
471 | Out[41]: [[1.03234, 3453], [1.03234, 3453], [1.03234, 3453], [1.03234, 3453]] |
|
471 | Out[41]: [[1.03234, 3453], [1.03234, 3453], [1.03234, 3453], [1.03234, 3453]] | |
472 |
|
472 | |||
473 | In [42]: mec.zip_pull(('a','b')) |
|
473 | In [42]: mec.zip_pull(('a','b')) | |
474 | Out[42]: [(1.03234, 1.03234, 1.03234, 1.03234), (3453, 3453, 3453, 3453)] |
|
474 | Out[42]: [(1.03234, 1.03234, 1.03234, 1.03234), (3453, 3453, 3453, 3453)] | |
475 |
|
475 | |||
476 | In [43]: mec.push(dict(c='speed')) |
|
476 | In [43]: mec.push(dict(c='speed')) | |
477 | Out[43]: [None, None, None, None] |
|
477 | Out[43]: [None, None, None, None] | |
478 |
|
478 | |||
479 | In [44]: %px print c |
|
479 | In [44]: %px print c | |
480 | Executing command on Controller |
|
480 | Executing command on Controller | |
481 | Out[44]: |
|
481 | Out[44]: | |
482 | <Results List> |
|
482 | <Results List> | |
483 | [0] In [14]: print c |
|
483 | [0] In [14]: print c | |
484 | [0] Out[14]: speed |
|
484 | [0] Out[14]: speed | |
485 |
|
485 | |||
486 | [1] In [13]: print c |
|
486 | [1] In [13]: print c | |
487 | [1] Out[13]: speed |
|
487 | [1] Out[13]: speed | |
488 |
|
488 | |||
489 | [2] In [14]: print c |
|
489 | [2] In [14]: print c | |
490 | [2] Out[14]: speed |
|
490 | [2] Out[14]: speed | |
491 |
|
491 | |||
492 | [3] In [13]: print c |
|
492 | [3] In [13]: print c | |
493 | [3] Out[13]: speed |
|
493 | [3] Out[13]: speed | |
494 |
|
494 | |||
495 | In non-blocking mode :meth:`push` and :meth:`pull` also return |
|
495 | In non-blocking mode :meth:`push` and :meth:`pull` also return | |
496 | :class:`PendingResult` objects: |
|
496 | :class:`PendingResult` objects: | |
497 |
|
497 | |||
498 | .. sourcecode:: ipython |
|
498 | .. sourcecode:: ipython | |
499 |
|
499 | |||
500 | In [47]: mec.block=False |
|
500 | In [47]: mec.block=False | |
501 |
|
501 | |||
502 | In [48]: pr = mec.pull('a') |
|
502 | In [48]: pr = mec.pull('a') | |
503 |
|
503 | |||
504 | In [49]: pr.r |
|
504 | In [49]: pr.r | |
505 | Out[49]: [1.03234, 1.03234, 1.03234, 1.03234] |
|
505 | Out[49]: [1.03234, 1.03234, 1.03234, 1.03234] | |
506 |
|
506 | |||
507 |
|
507 | |||
508 | Push and pull for functions |
|
508 | Push and pull for functions | |
509 | --------------------------- |
|
509 | --------------------------- | |
510 |
|
510 | |||
511 | Functions can also be pushed and pulled using :meth:`push_function` and |
|
511 | Functions can also be pushed and pulled using :meth:`push_function` and | |
512 | :meth:`pull_function`: |
|
512 | :meth:`pull_function`: | |
513 |
|
513 | |||
514 | .. sourcecode:: ipython |
|
514 | .. sourcecode:: ipython | |
515 |
|
515 | |||
516 | In [52]: mec.block=True |
|
516 | In [52]: mec.block=True | |
517 |
|
517 | |||
518 | In [53]: def f(x): |
|
518 | In [53]: def f(x): | |
519 | ....: return 2.0*x**4 |
|
519 | ....: return 2.0*x**4 | |
520 | ....: |
|
520 | ....: | |
521 |
|
521 | |||
522 | In [54]: mec.push_function(dict(f=f)) |
|
522 | In [54]: mec.push_function(dict(f=f)) | |
523 | Out[54]: [None, None, None, None] |
|
523 | Out[54]: [None, None, None, None] | |
524 |
|
524 | |||
525 | In [55]: mec.execute('y = f(4.0)') |
|
525 | In [55]: mec.execute('y = f(4.0)') | |
526 | Out[55]: |
|
526 | Out[55]: | |
527 | <Results List> |
|
527 | <Results List> | |
528 | [0] In [15]: y = f(4.0) |
|
528 | [0] In [15]: y = f(4.0) | |
529 | [1] In [14]: y = f(4.0) |
|
529 | [1] In [14]: y = f(4.0) | |
530 | [2] In [15]: y = f(4.0) |
|
530 | [2] In [15]: y = f(4.0) | |
531 | [3] In [14]: y = f(4.0) |
|
531 | [3] In [14]: y = f(4.0) | |
532 |
|
532 | |||
533 |
|
533 | |||
534 | In [56]: px print y |
|
534 | In [56]: px print y | |
535 | Executing command on Controller |
|
535 | Executing command on Controller | |
536 | Out[56]: |
|
536 | Out[56]: | |
537 | <Results List> |
|
537 | <Results List> | |
538 | [0] In [16]: print y |
|
538 | [0] In [16]: print y | |
539 | [0] Out[16]: 512.0 |
|
539 | [0] Out[16]: 512.0 | |
540 |
|
540 | |||
541 | [1] In [15]: print y |
|
541 | [1] In [15]: print y | |
542 | [1] Out[15]: 512.0 |
|
542 | [1] Out[15]: 512.0 | |
543 |
|
543 | |||
544 | [2] In [16]: print y |
|
544 | [2] In [16]: print y | |
545 | [2] Out[16]: 512.0 |
|
545 | [2] Out[16]: 512.0 | |
546 |
|
546 | |||
547 | [3] In [15]: print y |
|
547 | [3] In [15]: print y | |
548 | [3] Out[15]: 512.0 |
|
548 | [3] Out[15]: 512.0 | |
549 |
|
549 | |||
550 |
|
550 | |||
551 | Dictionary interface |
|
551 | Dictionary interface | |
552 | -------------------- |
|
552 | -------------------- | |
553 |
|
553 | |||
554 | As a shorthand to :meth:`push` and :meth:`pull`, the |
|
554 | As a shorthand to :meth:`push` and :meth:`pull`, the | |
555 | :class:`MultiEngineClient` class implements some of the Python dictionary |
|
555 | :class:`MultiEngineClient` class implements some of the Python dictionary | |
556 | interface. This make the remote namespaces of the engines appear as a local |
|
556 | interface. This make the remote namespaces of the engines appear as a local | |
557 | dictionary. Underneath, this uses :meth:`push` and :meth:`pull`: |
|
557 | dictionary. Underneath, this uses :meth:`push` and :meth:`pull`: | |
558 |
|
558 | |||
559 | .. sourcecode:: ipython |
|
559 | .. sourcecode:: ipython | |
560 |
|
560 | |||
561 | In [50]: mec.block=True |
|
561 | In [50]: mec.block=True | |
562 |
|
562 | |||
563 | In [51]: mec['a']=['foo','bar'] |
|
563 | In [51]: mec['a']=['foo','bar'] | |
564 |
|
564 | |||
565 | In [52]: mec['a'] |
|
565 | In [52]: mec['a'] | |
566 | Out[52]: [['foo', 'bar'], ['foo', 'bar'], ['foo', 'bar'], ['foo', 'bar']] |
|
566 | Out[52]: [['foo', 'bar'], ['foo', 'bar'], ['foo', 'bar'], ['foo', 'bar']] | |
567 |
|
567 | |||
568 | Scatter and gather |
|
568 | Scatter and gather | |
569 | ------------------ |
|
569 | ------------------ | |
570 |
|
570 | |||
571 | Sometimes it is useful to partition a sequence and push the partitions to |
|
571 | Sometimes it is useful to partition a sequence and push the partitions to | |
572 | different engines. In MPI language, this is know as scatter/gather and we |
|
572 | different engines. In MPI language, this is know as scatter/gather and we | |
573 | follow that terminology. However, it is important to remember that in |
|
573 | follow that terminology. However, it is important to remember that in | |
574 | IPython's :class:`MultiEngineClient` class, :meth:`scatter` is from the |
|
574 | IPython's :class:`MultiEngineClient` class, :meth:`scatter` is from the | |
575 | interactive IPython session to the engines and :meth:`gather` is from the |
|
575 | interactive IPython session to the engines and :meth:`gather` is from the | |
576 | engines back to the interactive IPython session. For scatter/gather operations |
|
576 | engines back to the interactive IPython session. For scatter/gather operations | |
577 | between engines, MPI should be used: |
|
577 | between engines, MPI should be used: | |
578 |
|
578 | |||
579 | .. sourcecode:: ipython |
|
579 | .. sourcecode:: ipython | |
580 |
|
580 | |||
581 | In [58]: mec.scatter('a',range(16)) |
|
581 | In [58]: mec.scatter('a',range(16)) | |
582 | Out[58]: [None, None, None, None] |
|
582 | Out[58]: [None, None, None, None] | |
583 |
|
583 | |||
584 | In [59]: px print a |
|
584 | In [59]: px print a | |
585 | Executing command on Controller |
|
585 | Executing command on Controller | |
586 | Out[59]: |
|
586 | Out[59]: | |
587 | <Results List> |
|
587 | <Results List> | |
588 | [0] In [17]: print a |
|
588 | [0] In [17]: print a | |
589 | [0] Out[17]: [0, 1, 2, 3] |
|
589 | [0] Out[17]: [0, 1, 2, 3] | |
590 |
|
590 | |||
591 | [1] In [16]: print a |
|
591 | [1] In [16]: print a | |
592 | [1] Out[16]: [4, 5, 6, 7] |
|
592 | [1] Out[16]: [4, 5, 6, 7] | |
593 |
|
593 | |||
594 | [2] In [17]: print a |
|
594 | [2] In [17]: print a | |
595 | [2] Out[17]: [8, 9, 10, 11] |
|
595 | [2] Out[17]: [8, 9, 10, 11] | |
596 |
|
596 | |||
597 | [3] In [16]: print a |
|
597 | [3] In [16]: print a | |
598 | [3] Out[16]: [12, 13, 14, 15] |
|
598 | [3] Out[16]: [12, 13, 14, 15] | |
599 |
|
599 | |||
600 |
|
600 | |||
601 | In [60]: mec.gather('a') |
|
601 | In [60]: mec.gather('a') | |
602 | Out[60]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] |
|
602 | Out[60]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] | |
603 |
|
603 | |||
604 | Other things to look at |
|
604 | Other things to look at | |
605 | ======================= |
|
605 | ======================= | |
606 |
|
606 | |||
607 | How to do parallel list comprehensions |
|
607 | How to do parallel list comprehensions | |
608 | -------------------------------------- |
|
608 | -------------------------------------- | |
609 |
|
609 | |||
610 | In many cases list comprehensions are nicer than using the map function. While |
|
610 | In many cases list comprehensions are nicer than using the map function. While | |
611 | we don't have fully parallel list comprehensions, it is simple to get the |
|
611 | we don't have fully parallel list comprehensions, it is simple to get the | |
612 | basic effect using :meth:`scatter` and :meth:`gather`: |
|
612 | basic effect using :meth:`scatter` and :meth:`gather`: | |
613 |
|
613 | |||
614 | .. sourcecode:: ipython |
|
614 | .. sourcecode:: ipython | |
615 |
|
615 | |||
616 | In [66]: mec.scatter('x',range(64)) |
|
616 | In [66]: mec.scatter('x',range(64)) | |
617 | Out[66]: [None, None, None, None] |
|
617 | Out[66]: [None, None, None, None] | |
618 |
|
618 | |||
619 | In [67]: px y = [i**10 for i in x] |
|
619 | In [67]: px y = [i**10 for i in x] | |
620 | Executing command on Controller |
|
620 | Executing command on Controller | |
621 | Out[67]: |
|
621 | Out[67]: | |
622 | <Results List> |
|
622 | <Results List> | |
623 | [0] In [19]: y = [i**10 for i in x] |
|
623 | [0] In [19]: y = [i**10 for i in x] | |
624 | [1] In [18]: y = [i**10 for i in x] |
|
624 | [1] In [18]: y = [i**10 for i in x] | |
625 | [2] In [19]: y = [i**10 for i in x] |
|
625 | [2] In [19]: y = [i**10 for i in x] | |
626 | [3] In [18]: y = [i**10 for i in x] |
|
626 | [3] In [18]: y = [i**10 for i in x] | |
627 |
|
627 | |||
628 |
|
628 | |||
629 | In [68]: y = mec.gather('y') |
|
629 | In [68]: y = mec.gather('y') | |
630 |
|
630 | |||
631 | In [69]: print y |
|
631 | In [69]: print y | |
632 | [0, 1, 1024, 59049, 1048576, 9765625, 60466176, 282475249, 1073741824,...] |
|
632 | [0, 1, 1024, 59049, 1048576, 9765625, 60466176, 282475249, 1073741824,...] | |
633 |
|
633 | |||
634 | Parallel exceptions |
|
634 | Parallel exceptions | |
635 | ------------------- |
|
635 | ------------------- | |
636 |
|
636 | |||
637 | In the multiengine interface, parallel commands can raise Python exceptions, |
|
637 | In the multiengine interface, parallel commands can raise Python exceptions, | |
638 | just like serial commands. But, it is a little subtle, because a single |
|
638 | just like serial commands. But, it is a little subtle, because a single | |
639 | parallel command can actually raise multiple exceptions (one for each engine |
|
639 | parallel command can actually raise multiple exceptions (one for each engine | |
640 | the command was run on). To express this idea, the MultiEngine interface has a |
|
640 | the command was run on). To express this idea, the MultiEngine interface has a | |
641 | :exc:`CompositeError` exception class that will be raised in most cases. The |
|
641 | :exc:`CompositeError` exception class that will be raised in most cases. The | |
642 | :exc:`CompositeError` class is a special type of exception that wraps one or |
|
642 | :exc:`CompositeError` class is a special type of exception that wraps one or | |
643 | more other types of exceptions. Here is how it works: |
|
643 | more other types of exceptions. Here is how it works: | |
644 |
|
644 | |||
645 | .. sourcecode:: ipython |
|
645 | .. sourcecode:: ipython | |
646 |
|
646 | |||
647 | In [76]: mec.block=True |
|
647 | In [76]: mec.block=True | |
648 |
|
648 | |||
649 | In [77]: mec.execute('1/0') |
|
649 | In [77]: mec.execute('1/0') | |
650 | --------------------------------------------------------------------------- |
|
650 | --------------------------------------------------------------------------- | |
651 | CompositeError Traceback (most recent call last) |
|
651 | CompositeError Traceback (most recent call last) | |
652 |
|
652 | |||
653 | /ipython1-client-r3021/docs/examples/<ipython console> in <module>() |
|
653 | /ipython1-client-r3021/docs/examples/<ipython console> in <module>() | |
654 |
|
654 | |||
655 | /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in execute(self, lines, targets, block) |
|
655 | /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in execute(self, lines, targets, block) | |
656 | 432 targets, block = self._findTargetsAndBlock(targets, block) |
|
656 | 432 targets, block = self._findTargetsAndBlock(targets, block) | |
657 | 433 result = blockingCallFromThread(self.smultiengine.execute, lines, |
|
657 | 433 result = blockingCallFromThread(self.smultiengine.execute, lines, | |
658 | --> 434 targets=targets, block=block) |
|
658 | --> 434 targets=targets, block=block) | |
659 | 435 if block: |
|
659 | 435 if block: | |
660 | 436 result = ResultList(result) |
|
660 | 436 result = ResultList(result) | |
661 |
|
661 | |||
662 | /ipython1-client-r3021/ipython1/kernel/twistedutil.pyc in blockingCallFromThread(f, *a, **kw) |
|
662 | /ipython1-client-r3021/ipython1/kernel/twistedutil.pyc in blockingCallFromThread(f, *a, **kw) | |
663 | 72 result.raiseException() |
|
663 | 72 result.raiseException() | |
664 | 73 except Exception, e: |
|
664 | 73 except Exception, e: | |
665 | ---> 74 raise e |
|
665 | ---> 74 raise e | |
666 | 75 return result |
|
666 | 75 return result | |
667 | 76 |
|
667 | 76 | |
668 |
|
668 | |||
669 | CompositeError: one or more exceptions from call to method: execute |
|
669 | CompositeError: one or more exceptions from call to method: execute | |
670 | [0:execute]: ZeroDivisionError: integer division or modulo by zero |
|
670 | [0:execute]: ZeroDivisionError: integer division or modulo by zero | |
671 | [1:execute]: ZeroDivisionError: integer division or modulo by zero |
|
671 | [1:execute]: ZeroDivisionError: integer division or modulo by zero | |
672 | [2:execute]: ZeroDivisionError: integer division or modulo by zero |
|
672 | [2:execute]: ZeroDivisionError: integer division or modulo by zero | |
673 | [3:execute]: ZeroDivisionError: integer division or modulo by zero |
|
673 | [3:execute]: ZeroDivisionError: integer division or modulo by zero | |
674 |
|
674 | |||
675 | Notice how the error message printed when :exc:`CompositeError` is raised has |
|
675 | Notice how the error message printed when :exc:`CompositeError` is raised has | |
676 | information about the individual exceptions that were raised on each engine. |
|
676 | information about the individual exceptions that were raised on each engine. | |
677 | If you want, you can even raise one of these original exceptions: |
|
677 | If you want, you can even raise one of these original exceptions: | |
678 |
|
678 | |||
679 | .. sourcecode:: ipython |
|
679 | .. sourcecode:: ipython | |
680 |
|
680 | |||
681 | In [80]: try: |
|
681 | In [80]: try: | |
682 | ....: mec.execute('1/0') |
|
682 | ....: mec.execute('1/0') | |
683 | ....: except client.CompositeError, e: |
|
683 | ....: except client.CompositeError, e: | |
684 | ....: e.raise_exception() |
|
684 | ....: e.raise_exception() | |
685 | ....: |
|
685 | ....: | |
686 | ....: |
|
686 | ....: | |
687 | --------------------------------------------------------------------------- |
|
687 | --------------------------------------------------------------------------- | |
688 | ZeroDivisionError Traceback (most recent call last) |
|
688 | ZeroDivisionError Traceback (most recent call last) | |
689 |
|
689 | |||
690 | /ipython1-client-r3021/docs/examples/<ipython console> in <module>() |
|
690 | /ipython1-client-r3021/docs/examples/<ipython console> in <module>() | |
691 |
|
691 | |||
692 | /ipython1-client-r3021/ipython1/kernel/error.pyc in raise_exception(self, excid) |
|
692 | /ipython1-client-r3021/ipython1/kernel/error.pyc in raise_exception(self, excid) | |
693 | 156 raise IndexError("an exception with index %i does not exist"%excid) |
|
693 | 156 raise IndexError("an exception with index %i does not exist"%excid) | |
694 | 157 else: |
|
694 | 157 else: | |
695 | --> 158 raise et, ev, etb |
|
695 | --> 158 raise et, ev, etb | |
696 | 159 |
|
696 | 159 | |
697 | 160 def collect_exceptions(rlist, method): |
|
697 | 160 def collect_exceptions(rlist, method): | |
698 |
|
698 | |||
699 | ZeroDivisionError: integer division or modulo by zero |
|
699 | ZeroDivisionError: integer division or modulo by zero | |
700 |
|
700 | |||
701 | If you are working in IPython, you can simple type ``%debug`` after one of |
|
701 | If you are working in IPython, you can simple type ``%debug`` after one of | |
702 | these :exc:`CompositeError` exceptions is raised, and inspect the exception |
|
702 | these :exc:`CompositeError` exceptions is raised, and inspect the exception | |
703 | instance: |
|
703 | instance: | |
704 |
|
704 | |||
705 | .. sourcecode:: ipython |
|
705 | .. sourcecode:: ipython | |
706 |
|
706 | |||
707 | In [81]: mec.execute('1/0') |
|
707 | In [81]: mec.execute('1/0') | |
708 | --------------------------------------------------------------------------- |
|
708 | --------------------------------------------------------------------------- | |
709 | CompositeError Traceback (most recent call last) |
|
709 | CompositeError Traceback (most recent call last) | |
710 |
|
710 | |||
711 | /ipython1-client-r3021/docs/examples/<ipython console> in <module>() |
|
711 | /ipython1-client-r3021/docs/examples/<ipython console> in <module>() | |
712 |
|
712 | |||
713 | /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in execute(self, lines, targets, block) |
|
713 | /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in execute(self, lines, targets, block) | |
714 | 432 targets, block = self._findTargetsAndBlock(targets, block) |
|
714 | 432 targets, block = self._findTargetsAndBlock(targets, block) | |
715 | 433 result = blockingCallFromThread(self.smultiengine.execute, lines, |
|
715 | 433 result = blockingCallFromThread(self.smultiengine.execute, lines, | |
716 | --> 434 targets=targets, block=block) |
|
716 | --> 434 targets=targets, block=block) | |
717 | 435 if block: |
|
717 | 435 if block: | |
718 | 436 result = ResultList(result) |
|
718 | 436 result = ResultList(result) | |
719 |
|
719 | |||
720 | /ipython1-client-r3021/ipython1/kernel/twistedutil.pyc in blockingCallFromThread(f, *a, **kw) |
|
720 | /ipython1-client-r3021/ipython1/kernel/twistedutil.pyc in blockingCallFromThread(f, *a, **kw) | |
721 | 72 result.raiseException() |
|
721 | 72 result.raiseException() | |
722 | 73 except Exception, e: |
|
722 | 73 except Exception, e: | |
723 | ---> 74 raise e |
|
723 | ---> 74 raise e | |
724 | 75 return result |
|
724 | 75 return result | |
725 | 76 |
|
725 | 76 | |
726 |
|
726 | |||
727 | CompositeError: one or more exceptions from call to method: execute |
|
727 | CompositeError: one or more exceptions from call to method: execute | |
728 | [0:execute]: ZeroDivisionError: integer division or modulo by zero |
|
728 | [0:execute]: ZeroDivisionError: integer division or modulo by zero | |
729 | [1:execute]: ZeroDivisionError: integer division or modulo by zero |
|
729 | [1:execute]: ZeroDivisionError: integer division or modulo by zero | |
730 | [2:execute]: ZeroDivisionError: integer division or modulo by zero |
|
730 | [2:execute]: ZeroDivisionError: integer division or modulo by zero | |
731 | [3:execute]: ZeroDivisionError: integer division or modulo by zero |
|
731 | [3:execute]: ZeroDivisionError: integer division or modulo by zero | |
732 |
|
732 | |||
733 | In [82]: %debug |
|
733 | In [82]: %debug | |
734 | > |
|
734 | > | |
735 |
|
735 | |||
736 | /ipython1-client-r3021/ipython1/kernel/twistedutil.py(74)blockingCallFromThread() |
|
736 | /ipython1-client-r3021/ipython1/kernel/twistedutil.py(74)blockingCallFromThread() | |
737 | 73 except Exception, e: |
|
737 | 73 except Exception, e: | |
738 | ---> 74 raise e |
|
738 | ---> 74 raise e | |
739 | 75 return result |
|
739 | 75 return result | |
740 |
|
740 | |||
741 | # With the debugger running, e is the exceptions instance. We can tab complete |
|
741 | # With the debugger running, e is the exceptions instance. We can tab complete | |
742 | # on it and see the extra methods that are available. |
|
742 | # on it and see the extra methods that are available. | |
743 | ipdb> e. |
|
743 | ipdb> e. | |
744 | e.__class__ e.__getitem__ e.__new__ e.__setstate__ e.args |
|
744 | e.__class__ e.__getitem__ e.__new__ e.__setstate__ e.args | |
745 | e.__delattr__ e.__getslice__ e.__reduce__ e.__str__ e.elist |
|
745 | e.__delattr__ e.__getslice__ e.__reduce__ e.__str__ e.elist | |
746 | e.__dict__ e.__hash__ e.__reduce_ex__ e.__weakref__ e.message |
|
746 | e.__dict__ e.__hash__ e.__reduce_ex__ e.__weakref__ e.message | |
747 | e.__doc__ e.__init__ e.__repr__ e._get_engine_str e.print_tracebacks |
|
747 | e.__doc__ e.__init__ e.__repr__ e._get_engine_str e.print_tracebacks | |
748 | e.__getattribute__ e.__module__ e.__setattr__ e._get_traceback e.raise_exception |
|
748 | e.__getattribute__ e.__module__ e.__setattr__ e._get_traceback e.raise_exception | |
749 | ipdb> e.print_tracebacks() |
|
749 | ipdb> e.print_tracebacks() | |
750 | [0:execute]: |
|
750 | [0:execute]: | |
751 | --------------------------------------------------------------------------- |
|
751 | --------------------------------------------------------------------------- | |
752 | ZeroDivisionError Traceback (most recent call last) |
|
752 | ZeroDivisionError Traceback (most recent call last) | |
753 |
|
753 | |||
754 | /ipython1-client-r3021/docs/examples/<string> in <module>() |
|
754 | /ipython1-client-r3021/docs/examples/<string> in <module>() | |
755 |
|
755 | |||
756 | ZeroDivisionError: integer division or modulo by zero |
|
756 | ZeroDivisionError: integer division or modulo by zero | |
757 |
|
757 | |||
758 | [1:execute]: |
|
758 | [1:execute]: | |
759 | --------------------------------------------------------------------------- |
|
759 | --------------------------------------------------------------------------- | |
760 | ZeroDivisionError Traceback (most recent call last) |
|
760 | ZeroDivisionError Traceback (most recent call last) | |
761 |
|
761 | |||
762 | /ipython1-client-r3021/docs/examples/<string> in <module>() |
|
762 | /ipython1-client-r3021/docs/examples/<string> in <module>() | |
763 |
|
763 | |||
764 | ZeroDivisionError: integer division or modulo by zero |
|
764 | ZeroDivisionError: integer division or modulo by zero | |
765 |
|
765 | |||
766 | [2:execute]: |
|
766 | [2:execute]: | |
767 | --------------------------------------------------------------------------- |
|
767 | --------------------------------------------------------------------------- | |
768 | ZeroDivisionError Traceback (most recent call last) |
|
768 | ZeroDivisionError Traceback (most recent call last) | |
769 |
|
769 | |||
770 | /ipython1-client-r3021/docs/examples/<string> in <module>() |
|
770 | /ipython1-client-r3021/docs/examples/<string> in <module>() | |
771 |
|
771 | |||
772 | ZeroDivisionError: integer division or modulo by zero |
|
772 | ZeroDivisionError: integer division or modulo by zero | |
773 |
|
773 | |||
774 | [3:execute]: |
|
774 | [3:execute]: | |
775 | --------------------------------------------------------------------------- |
|
775 | --------------------------------------------------------------------------- | |
776 | ZeroDivisionError Traceback (most recent call last) |
|
776 | ZeroDivisionError Traceback (most recent call last) | |
777 |
|
777 | |||
778 | /ipython1-client-r3021/docs/examples/<string> in <module>() |
|
778 | /ipython1-client-r3021/docs/examples/<string> in <module>() | |
779 |
|
779 | |||
780 | ZeroDivisionError: integer division or modulo by zero |
|
780 | ZeroDivisionError: integer division or modulo by zero | |
781 |
|
781 | |||
782 | .. note:: |
|
782 | .. note:: | |
783 |
|
783 | |||
784 | The above example appears to be broken right now because of a change in |
|
784 | The above example appears to be broken right now because of a change in | |
785 | how we are using Twisted. |
|
785 | how we are using Twisted. | |
786 |
|
786 | |||
787 | All of this same error handling magic even works in non-blocking mode: |
|
787 | All of this same error handling magic even works in non-blocking mode: | |
788 |
|
788 | |||
789 | .. sourcecode:: ipython |
|
789 | .. sourcecode:: ipython | |
790 |
|
790 | |||
791 | In [83]: mec.block=False |
|
791 | In [83]: mec.block=False | |
792 |
|
792 | |||
793 | In [84]: pr = mec.execute('1/0') |
|
793 | In [84]: pr = mec.execute('1/0') | |
794 |
|
794 | |||
795 | In [85]: pr.r |
|
795 | In [85]: pr.r | |
796 | --------------------------------------------------------------------------- |
|
796 | --------------------------------------------------------------------------- | |
797 | CompositeError Traceback (most recent call last) |
|
797 | CompositeError Traceback (most recent call last) | |
798 |
|
798 | |||
799 | /ipython1-client-r3021/docs/examples/<ipython console> in <module>() |
|
799 | /ipython1-client-r3021/docs/examples/<ipython console> in <module>() | |
800 |
|
800 | |||
801 | /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in _get_r(self) |
|
801 | /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in _get_r(self) | |
802 | 170 |
|
802 | 170 | |
803 | 171 def _get_r(self): |
|
803 | 171 def _get_r(self): | |
804 | --> 172 return self.get_result(block=True) |
|
804 | --> 172 return self.get_result(block=True) | |
805 | 173 |
|
805 | 173 | |
806 | 174 r = property(_get_r) |
|
806 | 174 r = property(_get_r) | |
807 |
|
807 | |||
808 | /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in get_result(self, default, block) |
|
808 | /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in get_result(self, default, block) | |
809 | 131 return self.result |
|
809 | 131 return self.result | |
810 | 132 try: |
|
810 | 132 try: | |
811 | --> 133 result = self.client.get_pending_deferred(self.result_id, block) |
|
811 | --> 133 result = self.client.get_pending_deferred(self.result_id, block) | |
812 | 134 except error.ResultNotCompleted: |
|
812 | 134 except error.ResultNotCompleted: | |
813 | 135 return default |
|
813 | 135 return default | |
814 |
|
814 | |||
815 | /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in get_pending_deferred(self, deferredID, block) |
|
815 | /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in get_pending_deferred(self, deferredID, block) | |
816 | 385 |
|
816 | 385 | |
817 | 386 def get_pending_deferred(self, deferredID, block): |
|
817 | 386 def get_pending_deferred(self, deferredID, block): | |
818 | --> 387 return blockingCallFromThread(self.smultiengine.get_pending_deferred, deferredID, block) |
|
818 | --> 387 return blockingCallFromThread(self.smultiengine.get_pending_deferred, deferredID, block) | |
819 | 388 |
|
819 | 388 | |
820 | 389 def barrier(self, pendingResults): |
|
820 | 389 def barrier(self, pendingResults): | |
821 |
|
821 | |||
822 | /ipython1-client-r3021/ipython1/kernel/twistedutil.pyc in blockingCallFromThread(f, *a, **kw) |
|
822 | /ipython1-client-r3021/ipython1/kernel/twistedutil.pyc in blockingCallFromThread(f, *a, **kw) | |
823 | 72 result.raiseException() |
|
823 | 72 result.raiseException() | |
824 | 73 except Exception, e: |
|
824 | 73 except Exception, e: | |
825 | ---> 74 raise e |
|
825 | ---> 74 raise e | |
826 | 75 return result |
|
826 | 75 return result | |
827 | 76 |
|
827 | 76 | |
828 |
|
828 | |||
829 | CompositeError: one or more exceptions from call to method: execute |
|
829 | CompositeError: one or more exceptions from call to method: execute | |
830 | [0:execute]: ZeroDivisionError: integer division or modulo by zero |
|
830 | [0:execute]: ZeroDivisionError: integer division or modulo by zero | |
831 | [1:execute]: ZeroDivisionError: integer division or modulo by zero |
|
831 | [1:execute]: ZeroDivisionError: integer division or modulo by zero | |
832 | [2:execute]: ZeroDivisionError: integer division or modulo by zero |
|
832 | [2:execute]: ZeroDivisionError: integer division or modulo by zero | |
833 | [3:execute]: ZeroDivisionError: integer division or modulo by zero |
|
833 | [3:execute]: ZeroDivisionError: integer division or modulo by zero | |
834 |
|
834 | |||
835 |
|
835 |
@@ -1,389 +1,389 b'' | |||||
1 | .. _parallel_process: |
|
1 | .. _parallel_process: | |
2 |
|
2 | |||
3 | =========================================== |
|
3 | =========================================== | |
4 | Starting the IPython controller and engines |
|
4 | Starting the IPython controller and engines | |
5 | =========================================== |
|
5 | =========================================== | |
6 |
|
6 | |||
7 | To use IPython for parallel computing, you need to start one instance of |
|
7 | To use IPython for parallel computing, you need to start one instance of | |
8 | the controller and one or more instances of the engine. The controller |
|
8 | the controller and one or more instances of the engine. The controller | |
9 | and each engine can run on different machines or on the same machine. |
|
9 | and each engine can run on different machines or on the same machine. | |
10 | Because of this, there are many different possibilities. |
|
10 | Because of this, there are many different possibilities. | |
11 |
|
11 | |||
12 | Broadly speaking, there are two ways of going about starting a controller and engines: |
|
12 | Broadly speaking, there are two ways of going about starting a controller and engines: | |
13 |
|
13 | |||
14 | * In an automated manner using the :command:`ipcluster` command. |
|
14 | * In an automated manner using the :command:`ipcluster` command. | |
15 | * In a more manual way using the :command:`ipcontroller` and |
|
15 | * In a more manual way using the :command:`ipcontroller` and | |
16 | :command:`ipengine` commands. |
|
16 | :command:`ipengine` commands. | |
17 |
|
17 | |||
18 | This document describes both of these methods. We recommend that new users |
|
18 | This document describes both of these methods. We recommend that new users | |
19 | start with the :command:`ipcluster` command as it simplifies many common usage |
|
19 | start with the :command:`ipcluster` command as it simplifies many common usage | |
20 | cases. |
|
20 | cases. | |
21 |
|
21 | |||
22 | General considerations |
|
22 | General considerations | |
23 | ====================== |
|
23 | ====================== | |
24 |
|
24 | |||
25 | Before delving into the details about how you can start a controller and |
|
25 | Before delving into the details about how you can start a controller and | |
26 | engines using the various methods, we outline some of the general issues that |
|
26 | engines using the various methods, we outline some of the general issues that | |
27 | come up when starting the controller and engines. These things come up no |
|
27 | come up when starting the controller and engines. These things come up no | |
28 | matter which method you use to start your IPython cluster. |
|
28 | matter which method you use to start your IPython cluster. | |
29 |
|
29 | |||
30 | Let's say that you want to start the controller on ``host0`` and engines on |
|
30 | Let's say that you want to start the controller on ``host0`` and engines on | |
31 | hosts ``host1``-``hostn``. The following steps are then required: |
|
31 | hosts ``host1``-``hostn``. The following steps are then required: | |
32 |
|
32 | |||
33 | 1. Start the controller on ``host0`` by running :command:`ipcontroller` on |
|
33 | 1. Start the controller on ``host0`` by running :command:`ipcontroller` on | |
34 | ``host0``. |
|
34 | ``host0``. | |
35 | 2. Move the FURL file (:file:`ipcontroller-engine.furl`) created by the |
|
35 | 2. Move the FURL file (:file:`ipcontroller-engine.furl`) created by the | |
36 | controller from ``host0`` to hosts ``host1``-``hostn``. |
|
36 | controller from ``host0`` to hosts ``host1``-``hostn``. | |
37 | 3. Start the engines on hosts ``host1``-``hostn`` by running |
|
37 | 3. Start the engines on hosts ``host1``-``hostn`` by running | |
38 | :command:`ipengine`. This command has to be told where the FURL file |
|
38 | :command:`ipengine`. This command has to be told where the FURL file | |
39 | (:file:`ipcontroller-engine.furl`) is located. |
|
39 | (:file:`ipcontroller-engine.furl`) is located. | |
40 |
|
40 | |||
41 | At this point, the controller and engines will be connected. By default, the |
|
41 | At this point, the controller and engines will be connected. By default, the | |
42 | FURL files created by the controller are put into the |
|
42 | FURL files created by the controller are put into the | |
43 |
:file:` |
|
43 | :file:`$IPYTHON_DIR/cluster_<profile>/security` directory. If the engines share a filesystem with | |
44 | the controller, step 2 can be skipped as the engines will automatically look |
|
44 | the controller, step 2 can be skipped as the engines will automatically look | |
45 | at that location. |
|
45 | at that location. | |
46 |
|
46 | |||
47 | The final step required required to actually use the running controller from a |
|
47 | The final step required required to actually use the running controller from a | |
48 | client is to move the FURL files :file:`ipcontroller-mec.furl` and |
|
48 | client is to move the FURL files :file:`ipcontroller-mec.furl` and | |
49 | :file:`ipcontroller-tc.furl` from ``host0`` to the host where the clients will |
|
49 | :file:`ipcontroller-tc.furl` from ``host0`` to the host where the clients will | |
50 |
be run. If these file are put into the :file:` |
|
50 | be run. If these file are put into the :file:`$IPYTHON_DIR/cluster_<profile>/security` directory | |
51 | of the client's host, they will be found automatically. Otherwise, the full |
|
51 | of the client's host, they will be found automatically. Otherwise, the full | |
52 | path to them has to be passed to the client's constructor. |
|
52 | path to them has to be passed to the client's constructor. | |
53 |
|
53 | |||
54 | Using :command:`ipcluster` |
|
54 | Using :command:`ipcluster` | |
55 | ========================== |
|
55 | ========================== | |
56 |
|
56 | |||
57 | The :command:`ipcluster` command provides a simple way of starting a |
|
57 | The :command:`ipcluster` command provides a simple way of starting a | |
58 | controller and engines in the following situations: |
|
58 | controller and engines in the following situations: | |
59 |
|
59 | |||
60 | 1. When the controller and engines are all run on localhost. This is useful |
|
60 | 1. When the controller and engines are all run on localhost. This is useful | |
61 | for testing or running on a multicore computer. |
|
61 | for testing or running on a multicore computer. | |
62 | 2. When engines are started using the :command:`mpirun` command that comes |
|
62 | 2. When engines are started using the :command:`mpirun` command that comes | |
63 | with most MPI [MPI]_ implementations |
|
63 | with most MPI [MPI]_ implementations | |
64 | 3. When engines are started using the PBS [PBS]_ batch system. |
|
64 | 3. When engines are started using the PBS [PBS]_ batch system. | |
65 | 4. When the controller is started on localhost and the engines are started on |
|
65 | 4. When the controller is started on localhost and the engines are started on | |
66 | remote nodes using :command:`ssh`. |
|
66 | remote nodes using :command:`ssh`. | |
67 |
|
67 | |||
68 | .. note:: |
|
68 | .. note:: | |
69 |
|
69 | |||
70 | It is also possible for advanced users to add support to |
|
70 | It is also possible for advanced users to add support to | |
71 | :command:`ipcluster` for starting controllers and engines using other |
|
71 | :command:`ipcluster` for starting controllers and engines using other | |
72 | methods (like Sun's Grid Engine for example). |
|
72 | methods (like Sun's Grid Engine for example). | |
73 |
|
73 | |||
74 | .. note:: |
|
74 | .. note:: | |
75 |
|
75 | |||
76 | Currently :command:`ipcluster` requires that the |
|
76 | Currently :command:`ipcluster` requires that the | |
77 |
:file:` |
|
77 | :file:`$IPYTHON_DIR/cluster_<profile>/security` directory live on a shared filesystem that is | |
78 | seen by both the controller and engines. If you don't have a shared file |
|
78 | seen by both the controller and engines. If you don't have a shared file | |
79 | system you will need to use :command:`ipcontroller` and |
|
79 | system you will need to use :command:`ipcontroller` and | |
80 | :command:`ipengine` directly. This constraint can be relaxed if you are |
|
80 | :command:`ipengine` directly. This constraint can be relaxed if you are | |
81 | using the :command:`ssh` method to start the cluster. |
|
81 | using the :command:`ssh` method to start the cluster. | |
82 |
|
82 | |||
83 | Underneath the hood, :command:`ipcluster` just uses :command:`ipcontroller` |
|
83 | Underneath the hood, :command:`ipcluster` just uses :command:`ipcontroller` | |
84 | and :command:`ipengine` to perform the steps described above. |
|
84 | and :command:`ipengine` to perform the steps described above. | |
85 |
|
85 | |||
86 | Using :command:`ipcluster` in local mode |
|
86 | Using :command:`ipcluster` in local mode | |
87 | ---------------------------------------- |
|
87 | ---------------------------------------- | |
88 |
|
88 | |||
89 | To start one controller and 4 engines on localhost, just do:: |
|
89 | To start one controller and 4 engines on localhost, just do:: | |
90 |
|
90 | |||
91 | $ ipcluster local -n 4 |
|
91 | $ ipcluster local -n 4 | |
92 |
|
92 | |||
93 | To see other command line options for the local mode, do:: |
|
93 | To see other command line options for the local mode, do:: | |
94 |
|
94 | |||
95 | $ ipcluster local -h |
|
95 | $ ipcluster local -h | |
96 |
|
96 | |||
97 | Using :command:`ipcluster` in mpiexec/mpirun mode |
|
97 | Using :command:`ipcluster` in mpiexec/mpirun mode | |
98 | ------------------------------------------------- |
|
98 | ------------------------------------------------- | |
99 |
|
99 | |||
100 | The mpiexec/mpirun mode is useful if you: |
|
100 | The mpiexec/mpirun mode is useful if you: | |
101 |
|
101 | |||
102 | 1. Have MPI installed. |
|
102 | 1. Have MPI installed. | |
103 | 2. Your systems are configured to use the :command:`mpiexec` or |
|
103 | 2. Your systems are configured to use the :command:`mpiexec` or | |
104 | :command:`mpirun` commands to start MPI processes. |
|
104 | :command:`mpirun` commands to start MPI processes. | |
105 |
|
105 | |||
106 | .. note:: |
|
106 | .. note:: | |
107 |
|
107 | |||
108 | The preferred command to use is :command:`mpiexec`. However, we also |
|
108 | The preferred command to use is :command:`mpiexec`. However, we also | |
109 | support :command:`mpirun` for backwards compatibility. The underlying |
|
109 | support :command:`mpirun` for backwards compatibility. The underlying | |
110 | logic used is exactly the same, the only difference being the name of the |
|
110 | logic used is exactly the same, the only difference being the name of the | |
111 | command line program that is called. |
|
111 | command line program that is called. | |
112 |
|
112 | |||
113 | If these are satisfied, you can start an IPython cluster using:: |
|
113 | If these are satisfied, you can start an IPython cluster using:: | |
114 |
|
114 | |||
115 | $ ipcluster mpiexec -n 4 |
|
115 | $ ipcluster mpiexec -n 4 | |
116 |
|
116 | |||
117 | This does the following: |
|
117 | This does the following: | |
118 |
|
118 | |||
119 | 1. Starts the IPython controller on current host. |
|
119 | 1. Starts the IPython controller on current host. | |
120 | 2. Uses :command:`mpiexec` to start 4 engines. |
|
120 | 2. Uses :command:`mpiexec` to start 4 engines. | |
121 |
|
121 | |||
122 | On newer MPI implementations (such as OpenMPI), this will work even if you |
|
122 | On newer MPI implementations (such as OpenMPI), this will work even if you | |
123 | don't make any calls to MPI or call :func:`MPI_Init`. However, older MPI |
|
123 | don't make any calls to MPI or call :func:`MPI_Init`. However, older MPI | |
124 | implementations actually require each process to call :func:`MPI_Init` upon |
|
124 | implementations actually require each process to call :func:`MPI_Init` upon | |
125 | starting. The easiest way of having this done is to install the mpi4py |
|
125 | starting. The easiest way of having this done is to install the mpi4py | |
126 | [mpi4py]_ package and then call ipcluster with the ``--mpi`` option:: |
|
126 | [mpi4py]_ package and then call ipcluster with the ``--mpi`` option:: | |
127 |
|
127 | |||
128 | $ ipcluster mpiexec -n 4 --mpi=mpi4py |
|
128 | $ ipcluster mpiexec -n 4 --mpi=mpi4py | |
129 |
|
129 | |||
130 | Unfortunately, even this won't work for some MPI implementations. If you are |
|
130 | Unfortunately, even this won't work for some MPI implementations. If you are | |
131 | having problems with this, you will likely have to use a custom Python |
|
131 | having problems with this, you will likely have to use a custom Python | |
132 | executable that itself calls :func:`MPI_Init` at the appropriate time. |
|
132 | executable that itself calls :func:`MPI_Init` at the appropriate time. | |
133 | Fortunately, mpi4py comes with such a custom Python executable that is easy to |
|
133 | Fortunately, mpi4py comes with such a custom Python executable that is easy to | |
134 | install and use. However, this custom Python executable approach will not work |
|
134 | install and use. However, this custom Python executable approach will not work | |
135 | with :command:`ipcluster` currently. |
|
135 | with :command:`ipcluster` currently. | |
136 |
|
136 | |||
137 | Additional command line options for this mode can be found by doing:: |
|
137 | Additional command line options for this mode can be found by doing:: | |
138 |
|
138 | |||
139 | $ ipcluster mpiexec -h |
|
139 | $ ipcluster mpiexec -h | |
140 |
|
140 | |||
141 | More details on using MPI with IPython can be found :ref:`here <parallelmpi>`. |
|
141 | More details on using MPI with IPython can be found :ref:`here <parallelmpi>`. | |
142 |
|
142 | |||
143 |
|
143 | |||
144 | Using :command:`ipcluster` in PBS mode |
|
144 | Using :command:`ipcluster` in PBS mode | |
145 | -------------------------------------- |
|
145 | -------------------------------------- | |
146 |
|
146 | |||
147 | The PBS mode uses the Portable Batch System [PBS]_ to start the engines. To |
|
147 | The PBS mode uses the Portable Batch System [PBS]_ to start the engines. To | |
148 | use this mode, you first need to create a PBS script template that will be |
|
148 | use this mode, you first need to create a PBS script template that will be | |
149 | used to start the engines. Here is a sample PBS script template: |
|
149 | used to start the engines. Here is a sample PBS script template: | |
150 |
|
150 | |||
151 | .. sourcecode:: bash |
|
151 | .. sourcecode:: bash | |
152 |
|
152 | |||
153 | #PBS -N ipython |
|
153 | #PBS -N ipython | |
154 | #PBS -j oe |
|
154 | #PBS -j oe | |
155 | #PBS -l walltime=00:10:00 |
|
155 | #PBS -l walltime=00:10:00 | |
156 | #PBS -l nodes=${n/4}:ppn=4 |
|
156 | #PBS -l nodes=${n/4}:ppn=4 | |
157 | #PBS -q parallel |
|
157 | #PBS -q parallel | |
158 |
|
158 | |||
159 | cd $$PBS_O_WORKDIR |
|
159 | cd $$PBS_O_WORKDIR | |
160 | export PATH=$$HOME/usr/local/bin |
|
160 | export PATH=$$HOME/usr/local/bin | |
161 | export PYTHONPATH=$$HOME/usr/local/lib/python2.4/site-packages |
|
161 | export PYTHONPATH=$$HOME/usr/local/lib/python2.4/site-packages | |
162 | /usr/local/bin/mpiexec -n ${n} ipengine --logfile=$$PBS_O_WORKDIR/ipengine |
|
162 | /usr/local/bin/mpiexec -n ${n} ipengine --logfile=$$PBS_O_WORKDIR/ipengine | |
163 |
|
163 | |||
164 | There are a few important points about this template: |
|
164 | There are a few important points about this template: | |
165 |
|
165 | |||
166 | 1. This template will be rendered at runtime using IPython's :mod:`Itpl` |
|
166 | 1. This template will be rendered at runtime using IPython's :mod:`Itpl` | |
167 | template engine. |
|
167 | template engine. | |
168 |
|
168 | |||
169 | 2. Instead of putting in the actual number of engines, use the notation |
|
169 | 2. Instead of putting in the actual number of engines, use the notation | |
170 | ``${n}`` to indicate the number of engines to be started. You can also uses |
|
170 | ``${n}`` to indicate the number of engines to be started. You can also uses | |
171 | expressions like ``${n/4}`` in the template to indicate the number of |
|
171 | expressions like ``${n/4}`` in the template to indicate the number of | |
172 | nodes. |
|
172 | nodes. | |
173 |
|
173 | |||
174 | 3. Because ``$`` is a special character used by the template engine, you must |
|
174 | 3. Because ``$`` is a special character used by the template engine, you must | |
175 | escape any ``$`` by using ``$$``. This is important when referring to |
|
175 | escape any ``$`` by using ``$$``. This is important when referring to | |
176 | environment variables in the template. |
|
176 | environment variables in the template. | |
177 |
|
177 | |||
178 | 4. Any options to :command:`ipengine` should be given in the batch script |
|
178 | 4. Any options to :command:`ipengine` should be given in the batch script | |
179 | template. |
|
179 | template. | |
180 |
|
180 | |||
181 | 5. Depending on the configuration of you system, you may have to set |
|
181 | 5. Depending on the configuration of you system, you may have to set | |
182 | environment variables in the script template. |
|
182 | environment variables in the script template. | |
183 |
|
183 | |||
184 | Once you have created such a script, save it with a name like |
|
184 | Once you have created such a script, save it with a name like | |
185 | :file:`pbs.template`. Now you are ready to start your job:: |
|
185 | :file:`pbs.template`. Now you are ready to start your job:: | |
186 |
|
186 | |||
187 | $ ipcluster pbs -n 128 --pbs-script=pbs.template |
|
187 | $ ipcluster pbs -n 128 --pbs-script=pbs.template | |
188 |
|
188 | |||
189 | Additional command line options for this mode can be found by doing:: |
|
189 | Additional command line options for this mode can be found by doing:: | |
190 |
|
190 | |||
191 | $ ipcluster pbs -h |
|
191 | $ ipcluster pbs -h | |
192 |
|
192 | |||
193 | Using :command:`ipcluster` in SSH mode |
|
193 | Using :command:`ipcluster` in SSH mode | |
194 | -------------------------------------- |
|
194 | -------------------------------------- | |
195 |
|
195 | |||
196 | The SSH mode uses :command:`ssh` to execute :command:`ipengine` on remote |
|
196 | The SSH mode uses :command:`ssh` to execute :command:`ipengine` on remote | |
197 | nodes and the :command:`ipcontroller` on localhost. |
|
197 | nodes and the :command:`ipcontroller` on localhost. | |
198 |
|
198 | |||
199 | When using using this mode it highly recommended that you have set up SSH keys |
|
199 | When using using this mode it highly recommended that you have set up SSH keys | |
200 | and are using ssh-agent [SSH]_ for password-less logins. |
|
200 | and are using ssh-agent [SSH]_ for password-less logins. | |
201 |
|
201 | |||
202 | To use this mode you need a python file describing the cluster, here is an |
|
202 | To use this mode you need a python file describing the cluster, here is an | |
203 | example of such a "clusterfile": |
|
203 | example of such a "clusterfile": | |
204 |
|
204 | |||
205 | .. sourcecode:: python |
|
205 | .. sourcecode:: python | |
206 |
|
206 | |||
207 | send_furl = True |
|
207 | send_furl = True | |
208 | engines = { 'host1.example.com' : 2, |
|
208 | engines = { 'host1.example.com' : 2, | |
209 | 'host2.example.com' : 5, |
|
209 | 'host2.example.com' : 5, | |
210 | 'host3.example.com' : 1, |
|
210 | 'host3.example.com' : 1, | |
211 | 'host4.example.com' : 8 } |
|
211 | 'host4.example.com' : 8 } | |
212 |
|
212 | |||
213 | Since this is a regular python file usual python syntax applies. Things to |
|
213 | Since this is a regular python file usual python syntax applies. Things to | |
214 | note: |
|
214 | note: | |
215 |
|
215 | |||
216 | * The `engines` dict, where the keys is the host we want to run engines on and |
|
216 | * The `engines` dict, where the keys is the host we want to run engines on and | |
217 | the value is the number of engines to run on that host. |
|
217 | the value is the number of engines to run on that host. | |
218 | * send_furl can either be `True` or `False`, if `True` it will copy over the |
|
218 | * send_furl can either be `True` or `False`, if `True` it will copy over the | |
219 | furl needed for :command:`ipengine` to each host. |
|
219 | furl needed for :command:`ipengine` to each host. | |
220 |
|
220 | |||
221 | The ``--clusterfile`` command line option lets you specify the file to use for |
|
221 | The ``--clusterfile`` command line option lets you specify the file to use for | |
222 | the cluster definition. Once you have your cluster file and you can |
|
222 | the cluster definition. Once you have your cluster file and you can | |
223 | :command:`ssh` into the remote hosts with out an password you are ready to |
|
223 | :command:`ssh` into the remote hosts with out an password you are ready to | |
224 | start your cluster like so: |
|
224 | start your cluster like so: | |
225 |
|
225 | |||
226 | .. sourcecode:: bash |
|
226 | .. sourcecode:: bash | |
227 |
|
227 | |||
228 | $ ipcluster ssh --clusterfile /path/to/my/clusterfile.py |
|
228 | $ ipcluster ssh --clusterfile /path/to/my/clusterfile.py | |
229 |
|
229 | |||
230 |
|
230 | |||
231 | Two helper shell scripts are used to start and stop :command:`ipengine` on |
|
231 | Two helper shell scripts are used to start and stop :command:`ipengine` on | |
232 | remote hosts: |
|
232 | remote hosts: | |
233 |
|
233 | |||
234 | * sshx.sh |
|
234 | * sshx.sh | |
235 | * engine_killer.sh |
|
235 | * engine_killer.sh | |
236 |
|
236 | |||
237 | Defaults for both of these are contained in the source code for |
|
237 | Defaults for both of these are contained in the source code for | |
238 | :command:`ipcluster`. The default scripts are written to a local file in a |
|
238 | :command:`ipcluster`. The default scripts are written to a local file in a | |
239 | tmep directory and then copied to a temp directory on the remote host and |
|
239 | tmep directory and then copied to a temp directory on the remote host and | |
240 | executed from there. On most Unix, Linux and OS X systems this is /tmp. |
|
240 | executed from there. On most Unix, Linux and OS X systems this is /tmp. | |
241 |
|
241 | |||
242 | The default sshx.sh is the following: |
|
242 | The default sshx.sh is the following: | |
243 |
|
243 | |||
244 | .. sourcecode:: bash |
|
244 | .. sourcecode:: bash | |
245 |
|
245 | |||
246 | #!/bin/sh |
|
246 | #!/bin/sh | |
247 | "$@" &> /dev/null & |
|
247 | "$@" &> /dev/null & | |
248 | echo $! |
|
248 | echo $! | |
249 |
|
249 | |||
250 | If you want to use a custom sshx.sh script you need to use the ``--sshx`` |
|
250 | If you want to use a custom sshx.sh script you need to use the ``--sshx`` | |
251 | option and specify the file to use. Using a custom sshx.sh file could be |
|
251 | option and specify the file to use. Using a custom sshx.sh file could be | |
252 | helpful when you need to setup the environment on the remote host before |
|
252 | helpful when you need to setup the environment on the remote host before | |
253 | executing :command:`ipengine`. |
|
253 | executing :command:`ipengine`. | |
254 |
|
254 | |||
255 | For a detailed options list: |
|
255 | For a detailed options list: | |
256 |
|
256 | |||
257 | .. sourcecode:: bash |
|
257 | .. sourcecode:: bash | |
258 |
|
258 | |||
259 | $ ipcluster ssh -h |
|
259 | $ ipcluster ssh -h | |
260 |
|
260 | |||
261 | Current limitations of the SSH mode of :command:`ipcluster` are: |
|
261 | Current limitations of the SSH mode of :command:`ipcluster` are: | |
262 |
|
262 | |||
263 | * Untested on Windows. Would require a working :command:`ssh` on Windows. |
|
263 | * Untested on Windows. Would require a working :command:`ssh` on Windows. | |
264 | Also, we are using shell scripts to setup and execute commands on remote |
|
264 | Also, we are using shell scripts to setup and execute commands on remote | |
265 | hosts. |
|
265 | hosts. | |
266 | * :command:`ipcontroller` is started on localhost, with no option to start it |
|
266 | * :command:`ipcontroller` is started on localhost, with no option to start it | |
267 | on a remote node. |
|
267 | on a remote node. | |
268 |
|
268 | |||
269 | Using the :command:`ipcontroller` and :command:`ipengine` commands |
|
269 | Using the :command:`ipcontroller` and :command:`ipengine` commands | |
270 | ================================================================== |
|
270 | ================================================================== | |
271 |
|
271 | |||
272 | It is also possible to use the :command:`ipcontroller` and :command:`ipengine` |
|
272 | It is also possible to use the :command:`ipcontroller` and :command:`ipengine` | |
273 | commands to start your controller and engines. This approach gives you full |
|
273 | commands to start your controller and engines. This approach gives you full | |
274 | control over all aspects of the startup process. |
|
274 | control over all aspects of the startup process. | |
275 |
|
275 | |||
276 | Starting the controller and engine on your local machine |
|
276 | Starting the controller and engine on your local machine | |
277 | -------------------------------------------------------- |
|
277 | -------------------------------------------------------- | |
278 |
|
278 | |||
279 | To use :command:`ipcontroller` and :command:`ipengine` to start things on your |
|
279 | To use :command:`ipcontroller` and :command:`ipengine` to start things on your | |
280 | local machine, do the following. |
|
280 | local machine, do the following. | |
281 |
|
281 | |||
282 | First start the controller:: |
|
282 | First start the controller:: | |
283 |
|
283 | |||
284 | $ ipcontroller |
|
284 | $ ipcontroller | |
285 |
|
285 | |||
286 | Next, start however many instances of the engine you want using (repeatedly) |
|
286 | Next, start however many instances of the engine you want using (repeatedly) | |
287 | the command:: |
|
287 | the command:: | |
288 |
|
288 | |||
289 | $ ipengine |
|
289 | $ ipengine | |
290 |
|
290 | |||
291 | The engines should start and automatically connect to the controller using the |
|
291 | The engines should start and automatically connect to the controller using the | |
292 |
FURL files in :file:` |
|
292 | FURL files in :file:`$IPYTHON_DIR/cluster_<profile>/security`. You are now ready to use the | |
293 | controller and engines from IPython. |
|
293 | controller and engines from IPython. | |
294 |
|
294 | |||
295 | .. warning:: |
|
295 | .. warning:: | |
296 |
|
296 | |||
297 | The order of the above operations is very important. You *must* |
|
297 | The order of the above operations is very important. You *must* | |
298 | start the controller before the engines, since the engines connect |
|
298 | start the controller before the engines, since the engines connect | |
299 | to the controller as they get started. |
|
299 | to the controller as they get started. | |
300 |
|
300 | |||
301 | .. note:: |
|
301 | .. note:: | |
302 |
|
302 | |||
303 | On some platforms (OS X), to put the controller and engine into the |
|
303 | On some platforms (OS X), to put the controller and engine into the | |
304 | background you may need to give these commands in the form ``(ipcontroller |
|
304 | background you may need to give these commands in the form ``(ipcontroller | |
305 | &)`` and ``(ipengine &)`` (with the parentheses) for them to work |
|
305 | &)`` and ``(ipengine &)`` (with the parentheses) for them to work | |
306 | properly. |
|
306 | properly. | |
307 |
|
307 | |||
308 | Starting the controller and engines on different hosts |
|
308 | Starting the controller and engines on different hosts | |
309 | ------------------------------------------------------ |
|
309 | ------------------------------------------------------ | |
310 |
|
310 | |||
311 | When the controller and engines are running on different hosts, things are |
|
311 | When the controller and engines are running on different hosts, things are | |
312 | slightly more complicated, but the underlying ideas are the same: |
|
312 | slightly more complicated, but the underlying ideas are the same: | |
313 |
|
313 | |||
314 | 1. Start the controller on a host using :command:`ipcontroller`. |
|
314 | 1. Start the controller on a host using :command:`ipcontroller`. | |
315 |
2. Copy :file:`ipcontroller-engine.furl` from :file:` |
|
315 | 2. Copy :file:`ipcontroller-engine.furl` from :file:`$IPYTHON_DIR/cluster_<profile>/security` on | |
316 | the controller's host to the host where the engines will run. |
|
316 | the controller's host to the host where the engines will run. | |
317 | 3. Use :command:`ipengine` on the engine's hosts to start the engines. |
|
317 | 3. Use :command:`ipengine` on the engine's hosts to start the engines. | |
318 |
|
318 | |||
319 | The only thing you have to be careful of is to tell :command:`ipengine` where |
|
319 | The only thing you have to be careful of is to tell :command:`ipengine` where | |
320 | the :file:`ipcontroller-engine.furl` file is located. There are two ways you |
|
320 | the :file:`ipcontroller-engine.furl` file is located. There are two ways you | |
321 | can do this: |
|
321 | can do this: | |
322 |
|
322 | |||
323 |
* Put :file:`ipcontroller-engine.furl` in the :file:` |
|
323 | * Put :file:`ipcontroller-engine.furl` in the :file:`$IPYTHON_DIR/cluster_<profile>/security` | |
324 | directory on the engine's host, where it will be found automatically. |
|
324 | directory on the engine's host, where it will be found automatically. | |
325 | * Call :command:`ipengine` with the ``--furl-file=full_path_to_the_file`` |
|
325 | * Call :command:`ipengine` with the ``--furl-file=full_path_to_the_file`` | |
326 | flag. |
|
326 | flag. | |
327 |
|
327 | |||
328 | The ``--furl-file`` flag works like this:: |
|
328 | The ``--furl-file`` flag works like this:: | |
329 |
|
329 | |||
330 | $ ipengine --furl-file=/path/to/my/ipcontroller-engine.furl |
|
330 | $ ipengine --furl-file=/path/to/my/ipcontroller-engine.furl | |
331 |
|
331 | |||
332 | .. note:: |
|
332 | .. note:: | |
333 |
|
333 | |||
334 | If the controller's and engine's hosts all have a shared file system |
|
334 | If the controller's and engine's hosts all have a shared file system | |
335 |
(:file:` |
|
335 | (:file:`$IPYTHON_DIR/cluster_<profile>/security` is the same on all of them), then things | |
336 | will just work! |
|
336 | will just work! | |
337 |
|
337 | |||
338 | Make FURL files persistent |
|
338 | Make FURL files persistent | |
339 | --------------------------- |
|
339 | --------------------------- | |
340 |
|
340 | |||
341 | At fist glance it may seem that that managing the FURL files is a bit |
|
341 | At fist glance it may seem that that managing the FURL files is a bit | |
342 | annoying. Going back to the house and key analogy, copying the FURL around |
|
342 | annoying. Going back to the house and key analogy, copying the FURL around | |
343 | each time you start the controller is like having to make a new key every time |
|
343 | each time you start the controller is like having to make a new key every time | |
344 | you want to unlock the door and enter your house. As with your house, you want |
|
344 | you want to unlock the door and enter your house. As with your house, you want | |
345 | to be able to create the key (or FURL file) once, and then simply use it at |
|
345 | to be able to create the key (or FURL file) once, and then simply use it at | |
346 | any point in the future. |
|
346 | any point in the future. | |
347 |
|
347 | |||
348 | This is possible, but before you do this, you **must** remove any old FURL |
|
348 | This is possible, but before you do this, you **must** remove any old FURL | |
349 |
files in the :file:` |
|
349 | files in the :file:`$IPYTHON_DIR/cluster_<profile>/security` directory. | |
350 |
|
350 | |||
351 | .. warning:: |
|
351 | .. warning:: | |
352 |
|
352 | |||
353 | You **must** remove old FURL files before using persistent FURL files. |
|
353 | You **must** remove old FURL files before using persistent FURL files. | |
354 |
|
354 | |||
355 | Then, The only thing you have to do is decide what ports the controller will |
|
355 | Then, The only thing you have to do is decide what ports the controller will | |
356 | listen on for the engines and clients. This is done as follows:: |
|
356 | listen on for the engines and clients. This is done as follows:: | |
357 |
|
357 | |||
358 | $ ipcontroller -r --client-port=10101 --engine-port=10102 |
|
358 | $ ipcontroller -r --client-port=10101 --engine-port=10102 | |
359 |
|
359 | |||
360 | These options also work with all of the various modes of |
|
360 | These options also work with all of the various modes of | |
361 | :command:`ipcluster`:: |
|
361 | :command:`ipcluster`:: | |
362 |
|
362 | |||
363 | $ ipcluster local -n 2 -r --client-port=10101 --engine-port=10102 |
|
363 | $ ipcluster local -n 2 -r --client-port=10101 --engine-port=10102 | |
364 |
|
364 | |||
365 | Then, just copy the furl files over the first time and you are set. You can |
|
365 | Then, just copy the furl files over the first time and you are set. You can | |
366 | start and stop the controller and engines any many times as you want in the |
|
366 | start and stop the controller and engines any many times as you want in the | |
367 | future, just make sure to tell the controller to use the *same* ports. |
|
367 | future, just make sure to tell the controller to use the *same* ports. | |
368 |
|
368 | |||
369 | .. note:: |
|
369 | .. note:: | |
370 |
|
370 | |||
371 | You may ask the question: what ports does the controller listen on if you |
|
371 | You may ask the question: what ports does the controller listen on if you | |
372 | don't tell is to use specific ones? The default is to use high random port |
|
372 | don't tell is to use specific ones? The default is to use high random port | |
373 | numbers. We do this for two reasons: i) to increase security through |
|
373 | numbers. We do this for two reasons: i) to increase security through | |
374 | obscurity and ii) to multiple controllers on a given host to start and |
|
374 | obscurity and ii) to multiple controllers on a given host to start and | |
375 | automatically use different ports. |
|
375 | automatically use different ports. | |
376 |
|
376 | |||
377 | Log files |
|
377 | Log files | |
378 | --------- |
|
378 | --------- | |
379 |
|
379 | |||
380 | All of the components of IPython have log files associated with them. |
|
380 | All of the components of IPython have log files associated with them. | |
381 | These log files can be extremely useful in debugging problems with |
|
381 | These log files can be extremely useful in debugging problems with | |
382 |
IPython and can be found in the directory :file:` |
|
382 | IPython and can be found in the directory :file:`$IPYTHON_DIR/cluster_<profile>/log`. Sending | |
383 | the log files to us will often help us to debug any problems. |
|
383 | the log files to us will often help us to debug any problems. | |
384 |
|
384 | |||
385 |
|
385 | |||
386 | .. [PBS] Portable Batch System. http://www.openpbs.org/ |
|
386 | .. [PBS] Portable Batch System. http://www.openpbs.org/ | |
387 | .. [SSH] SSH-Agent http://en.wikipedia.org/wiki/Ssh-agent |
|
387 | .. [SSH] SSH-Agent http://en.wikipedia.org/wiki/Ssh-agent | |
388 |
|
388 | |||
389 |
|
389 |
@@ -1,366 +1,366 b'' | |||||
1 | .. _parallelsecurity: |
|
1 | .. _parallelsecurity: | |
2 |
|
2 | |||
3 | =========================== |
|
3 | =========================== | |
4 | Security details of IPython |
|
4 | Security details of IPython | |
5 | =========================== |
|
5 | =========================== | |
6 |
|
6 | |||
7 | IPython's :mod:`IPython.kernel` package exposes the full power of the Python |
|
7 | IPython's :mod:`IPython.kernel` package exposes the full power of the Python | |
8 | interpreter over a TCP/IP network for the purposes of parallel computing. This |
|
8 | interpreter over a TCP/IP network for the purposes of parallel computing. This | |
9 | feature brings up the important question of IPython's security model. This |
|
9 | feature brings up the important question of IPython's security model. This | |
10 | document gives details about this model and how it is implemented in IPython's |
|
10 | document gives details about this model and how it is implemented in IPython's | |
11 | architecture. |
|
11 | architecture. | |
12 |
|
12 | |||
13 | Processs and network topology |
|
13 | Processs and network topology | |
14 | ============================= |
|
14 | ============================= | |
15 |
|
15 | |||
16 | To enable parallel computing, IPython has a number of different processes that |
|
16 | To enable parallel computing, IPython has a number of different processes that | |
17 | run. These processes are discussed at length in the IPython documentation and |
|
17 | run. These processes are discussed at length in the IPython documentation and | |
18 | are summarized here: |
|
18 | are summarized here: | |
19 |
|
19 | |||
20 | * The IPython *engine*. This process is a full blown Python |
|
20 | * The IPython *engine*. This process is a full blown Python | |
21 | interpreter in which user code is executed. Multiple |
|
21 | interpreter in which user code is executed. Multiple | |
22 | engines are started to make parallel computing possible. |
|
22 | engines are started to make parallel computing possible. | |
23 | * The IPython *controller*. This process manages a set of |
|
23 | * The IPython *controller*. This process manages a set of | |
24 | engines, maintaining a queue for each and presenting |
|
24 | engines, maintaining a queue for each and presenting | |
25 | an asynchronous interface to the set of engines. |
|
25 | an asynchronous interface to the set of engines. | |
26 | * The IPython *client*. This process is typically an |
|
26 | * The IPython *client*. This process is typically an | |
27 | interactive Python process that is used to coordinate the |
|
27 | interactive Python process that is used to coordinate the | |
28 | engines to get a parallel computation done. |
|
28 | engines to get a parallel computation done. | |
29 |
|
29 | |||
30 | Collectively, these three processes are called the IPython *kernel*. |
|
30 | Collectively, these three processes are called the IPython *kernel*. | |
31 |
|
31 | |||
32 | These three processes communicate over TCP/IP connections with a well defined |
|
32 | These three processes communicate over TCP/IP connections with a well defined | |
33 | topology. The IPython controller is the only process that listens on TCP/IP |
|
33 | topology. The IPython controller is the only process that listens on TCP/IP | |
34 | sockets. Upon starting, an engine connects to a controller and registers |
|
34 | sockets. Upon starting, an engine connects to a controller and registers | |
35 | itself with the controller. These engine/controller TCP/IP connections persist |
|
35 | itself with the controller. These engine/controller TCP/IP connections persist | |
36 | for the lifetime of each engine. |
|
36 | for the lifetime of each engine. | |
37 |
|
37 | |||
38 | The IPython client also connects to the controller using one or more TCP/IP |
|
38 | The IPython client also connects to the controller using one or more TCP/IP | |
39 | connections. These connections persist for the lifetime of the client only. |
|
39 | connections. These connections persist for the lifetime of the client only. | |
40 |
|
40 | |||
41 | A given IPython controller and set of engines typically has a relatively short |
|
41 | A given IPython controller and set of engines typically has a relatively short | |
42 | lifetime. Typically this lifetime corresponds to the duration of a single |
|
42 | lifetime. Typically this lifetime corresponds to the duration of a single | |
43 | parallel simulation performed by a single user. Finally, the controller, |
|
43 | parallel simulation performed by a single user. Finally, the controller, | |
44 | engines and client processes typically execute with the permissions of that |
|
44 | engines and client processes typically execute with the permissions of that | |
45 | same user. More specifically, the controller and engines are *not* executed as |
|
45 | same user. More specifically, the controller and engines are *not* executed as | |
46 | root or with any other superuser permissions. |
|
46 | root or with any other superuser permissions. | |
47 |
|
47 | |||
48 | Application logic |
|
48 | Application logic | |
49 | ================= |
|
49 | ================= | |
50 |
|
50 | |||
51 | When running the IPython kernel to perform a parallel computation, a user |
|
51 | When running the IPython kernel to perform a parallel computation, a user | |
52 | utilizes the IPython client to send Python commands and data through the |
|
52 | utilizes the IPython client to send Python commands and data through the | |
53 | IPython controller to the IPython engines, where those commands are executed |
|
53 | IPython controller to the IPython engines, where those commands are executed | |
54 | and the data processed. The design of IPython ensures that the client is the |
|
54 | and the data processed. The design of IPython ensures that the client is the | |
55 | only access point for the capabilities of the engines. That is, the only way |
|
55 | only access point for the capabilities of the engines. That is, the only way | |
56 | of addressing the engines is through a client. |
|
56 | of addressing the engines is through a client. | |
57 |
|
57 | |||
58 | A user can utilize the client to instruct the IPython engines to execute |
|
58 | A user can utilize the client to instruct the IPython engines to execute | |
59 | arbitrary Python commands. These Python commands can include calls to the |
|
59 | arbitrary Python commands. These Python commands can include calls to the | |
60 | system shell, access the filesystem, etc., as required by the user's |
|
60 | system shell, access the filesystem, etc., as required by the user's | |
61 | application code. From this perspective, when a user runs an IPython engine on |
|
61 | application code. From this perspective, when a user runs an IPython engine on | |
62 | a host, that engine has the same capabilities and permissions as the user |
|
62 | a host, that engine has the same capabilities and permissions as the user | |
63 | themselves (as if they were logged onto the engine's host with a terminal). |
|
63 | themselves (as if they were logged onto the engine's host with a terminal). | |
64 |
|
64 | |||
65 | Secure network connections |
|
65 | Secure network connections | |
66 | ========================== |
|
66 | ========================== | |
67 |
|
67 | |||
68 | Overview |
|
68 | Overview | |
69 | -------- |
|
69 | -------- | |
70 |
|
70 | |||
71 | All TCP/IP connections between the client and controller as well as the |
|
71 | All TCP/IP connections between the client and controller as well as the | |
72 | engines and controller are fully encrypted and authenticated. This section |
|
72 | engines and controller are fully encrypted and authenticated. This section | |
73 | describes the details of the encryption and authentication approached used |
|
73 | describes the details of the encryption and authentication approached used | |
74 | within IPython. |
|
74 | within IPython. | |
75 |
|
75 | |||
76 | IPython uses the Foolscap network protocol [Foolscap]_ for all communications |
|
76 | IPython uses the Foolscap network protocol [Foolscap]_ for all communications | |
77 | between processes. Thus, the details of IPython's security model are directly |
|
77 | between processes. Thus, the details of IPython's security model are directly | |
78 | related to those of Foolscap. Thus, much of the following discussion is |
|
78 | related to those of Foolscap. Thus, much of the following discussion is | |
79 | actually just a discussion of the security that is built in to Foolscap. |
|
79 | actually just a discussion of the security that is built in to Foolscap. | |
80 |
|
80 | |||
81 | Encryption |
|
81 | Encryption | |
82 | ---------- |
|
82 | ---------- | |
83 |
|
83 | |||
84 | For encryption purposes, IPython and Foolscap use the well known Secure Socket |
|
84 | For encryption purposes, IPython and Foolscap use the well known Secure Socket | |
85 | Layer (SSL) protocol [RFC5246]_. We use the implementation of this protocol |
|
85 | Layer (SSL) protocol [RFC5246]_. We use the implementation of this protocol | |
86 | provided by the OpenSSL project through the pyOpenSSL [pyOpenSSL]_ Python |
|
86 | provided by the OpenSSL project through the pyOpenSSL [pyOpenSSL]_ Python | |
87 | bindings to OpenSSL. |
|
87 | bindings to OpenSSL. | |
88 |
|
88 | |||
89 | Authentication |
|
89 | Authentication | |
90 | -------------- |
|
90 | -------------- | |
91 |
|
91 | |||
92 | IPython clients and engines must also authenticate themselves with the |
|
92 | IPython clients and engines must also authenticate themselves with the | |
93 | controller. This is handled in a capabilities based security model |
|
93 | controller. This is handled in a capabilities based security model | |
94 | [Capability]_. In this model, the controller creates a strong cryptographic |
|
94 | [Capability]_. In this model, the controller creates a strong cryptographic | |
95 | key or token that represents each set of capability that the controller |
|
95 | key or token that represents each set of capability that the controller | |
96 | offers. Any party who has this key and presents it to the controller has full |
|
96 | offers. Any party who has this key and presents it to the controller has full | |
97 | access to the corresponding capabilities of the controller. This model is |
|
97 | access to the corresponding capabilities of the controller. This model is | |
98 | analogous to using a physical key to gain access to physical items |
|
98 | analogous to using a physical key to gain access to physical items | |
99 | (capabilities) behind a locked door. |
|
99 | (capabilities) behind a locked door. | |
100 |
|
100 | |||
101 | For a capabilities based authentication system to prevent unauthorized access, |
|
101 | For a capabilities based authentication system to prevent unauthorized access, | |
102 | two things must be ensured: |
|
102 | two things must be ensured: | |
103 |
|
103 | |||
104 | * The keys must be cryptographically strong. Otherwise attackers could gain |
|
104 | * The keys must be cryptographically strong. Otherwise attackers could gain | |
105 | access by a simple brute force key guessing attack. |
|
105 | access by a simple brute force key guessing attack. | |
106 | * The actual keys must be distributed only to authorized parties. |
|
106 | * The actual keys must be distributed only to authorized parties. | |
107 |
|
107 | |||
108 | The keys in Foolscap are called Foolscap URL's or FURLs. The following section |
|
108 | The keys in Foolscap are called Foolscap URL's or FURLs. The following section | |
109 | gives details about how these FURLs are created in Foolscap. The IPython |
|
109 | gives details about how these FURLs are created in Foolscap. The IPython | |
110 | controller creates a number of FURLs for different purposes: |
|
110 | controller creates a number of FURLs for different purposes: | |
111 |
|
111 | |||
112 | * One FURL that grants IPython engines access to the controller. Also |
|
112 | * One FURL that grants IPython engines access to the controller. Also | |
113 | implicit in this access is permission to execute code sent by an |
|
113 | implicit in this access is permission to execute code sent by an | |
114 | authenticated IPython client. |
|
114 | authenticated IPython client. | |
115 | * Two or more FURLs that grant IPython clients access to the controller. |
|
115 | * Two or more FURLs that grant IPython clients access to the controller. | |
116 | Implicit in this access is permission to give the controller's engine code |
|
116 | Implicit in this access is permission to give the controller's engine code | |
117 | to execute. |
|
117 | to execute. | |
118 |
|
118 | |||
119 | Upon starting, the controller creates these different FURLS and writes them |
|
119 | Upon starting, the controller creates these different FURLS and writes them | |
120 |
files in the user-read-only directory :file:`$ |
|
120 | files in the user-read-only directory :file:`$IPYTHON_DIR/cluster_default/security`. Thus, | |
121 | only the user who starts the controller has access to the FURLs. |
|
121 | only the user who starts the controller has access to the FURLs. | |
122 |
|
122 | |||
123 | For an IPython client or engine to authenticate with a controller, it must |
|
123 | For an IPython client or engine to authenticate with a controller, it must | |
124 | present the appropriate FURL to the controller upon connecting. If the |
|
124 | present the appropriate FURL to the controller upon connecting. If the | |
125 | FURL matches what the controller expects for a given capability, access is |
|
125 | FURL matches what the controller expects for a given capability, access is | |
126 | granted. If not, access is denied. The exchange of FURLs is done after |
|
126 | granted. If not, access is denied. The exchange of FURLs is done after | |
127 | encrypted communications channels have been established to prevent attackers |
|
127 | encrypted communications channels have been established to prevent attackers | |
128 | from capturing them. |
|
128 | from capturing them. | |
129 |
|
129 | |||
130 | .. note:: |
|
130 | .. note:: | |
131 |
|
131 | |||
132 | The FURL is similar to an unsigned private key in SSH. |
|
132 | The FURL is similar to an unsigned private key in SSH. | |
133 |
|
133 | |||
134 | Details of the Foolscap handshake |
|
134 | Details of the Foolscap handshake | |
135 | --------------------------------- |
|
135 | --------------------------------- | |
136 |
|
136 | |||
137 | In this section we detail the precise security handshake that takes place at |
|
137 | In this section we detail the precise security handshake that takes place at | |
138 | the beginning of any network connection in IPython. For the purposes of this |
|
138 | the beginning of any network connection in IPython. For the purposes of this | |
139 | discussion, the SERVER is the IPython controller process and the CLIENT is the |
|
139 | discussion, the SERVER is the IPython controller process and the CLIENT is the | |
140 | IPython engine or client process. |
|
140 | IPython engine or client process. | |
141 |
|
141 | |||
142 | Upon starting, all IPython processes do the following: |
|
142 | Upon starting, all IPython processes do the following: | |
143 |
|
143 | |||
144 | 1. Create a public key x509 certificate (ISO/IEC 9594). |
|
144 | 1. Create a public key x509 certificate (ISO/IEC 9594). | |
145 | 2. Create a hash of the contents of the certificate using the SHA-1 algorithm. |
|
145 | 2. Create a hash of the contents of the certificate using the SHA-1 algorithm. | |
146 | The base-32 encoded version of this hash is saved by the process as its |
|
146 | The base-32 encoded version of this hash is saved by the process as its | |
147 | process id (actually in Foolscap, this is the Tub id, but here refer to |
|
147 | process id (actually in Foolscap, this is the Tub id, but here refer to | |
148 | it as the process id). |
|
148 | it as the process id). | |
149 |
|
149 | |||
150 | Upon starting, the IPython controller also does the following: |
|
150 | Upon starting, the IPython controller also does the following: | |
151 |
|
151 | |||
152 | 1. Save the x509 certificate to disk in a secure location. The CLIENT |
|
152 | 1. Save the x509 certificate to disk in a secure location. The CLIENT | |
153 | certificate is never saved to disk. |
|
153 | certificate is never saved to disk. | |
154 | 2. Create a FURL for each capability that the controller has. There are |
|
154 | 2. Create a FURL for each capability that the controller has. There are | |
155 | separate capabilities the controller offers for clients and engines. The |
|
155 | separate capabilities the controller offers for clients and engines. The | |
156 | FURL is created using: a) the process id of the SERVER, b) the IP |
|
156 | FURL is created using: a) the process id of the SERVER, b) the IP | |
157 | address and port the SERVER is listening on and c) a 160 bit, |
|
157 | address and port the SERVER is listening on and c) a 160 bit, | |
158 | cryptographically secure string that represents the capability (the |
|
158 | cryptographically secure string that represents the capability (the | |
159 | "capability id"). |
|
159 | "capability id"). | |
160 | 3. The FURLs are saved to disk in a secure location on the SERVER's host. |
|
160 | 3. The FURLs are saved to disk in a secure location on the SERVER's host. | |
161 |
|
161 | |||
162 | For a CLIENT to be able to connect to the SERVER and access a capability of |
|
162 | For a CLIENT to be able to connect to the SERVER and access a capability of | |
163 | that SERVER, the CLIENT must have knowledge of the FURL for that SERVER's |
|
163 | that SERVER, the CLIENT must have knowledge of the FURL for that SERVER's | |
164 | capability. This typically requires that the file containing the FURL be |
|
164 | capability. This typically requires that the file containing the FURL be | |
165 | moved from the SERVER's host to the CLIENT's host. This is done by the end |
|
165 | moved from the SERVER's host to the CLIENT's host. This is done by the end | |
166 | user who started the SERVER and wishes to have a CLIENT connect to the SERVER. |
|
166 | user who started the SERVER and wishes to have a CLIENT connect to the SERVER. | |
167 |
|
167 | |||
168 | When a CLIENT connects to the SERVER, the following handshake protocol takes |
|
168 | When a CLIENT connects to the SERVER, the following handshake protocol takes | |
169 | place: |
|
169 | place: | |
170 |
|
170 | |||
171 | 1. The CLIENT tells the SERVER what process (or Tub) id it expects the SERVER |
|
171 | 1. The CLIENT tells the SERVER what process (or Tub) id it expects the SERVER | |
172 | to have. |
|
172 | to have. | |
173 | 2. If the SERVER has that process id, it notifies the CLIENT that it will now |
|
173 | 2. If the SERVER has that process id, it notifies the CLIENT that it will now | |
174 | enter encrypted mode. If the SERVER has a different id, the SERVER aborts. |
|
174 | enter encrypted mode. If the SERVER has a different id, the SERVER aborts. | |
175 | 3. Both CLIENT and SERVER initiate the SSL handshake protocol. |
|
175 | 3. Both CLIENT and SERVER initiate the SSL handshake protocol. | |
176 | 4. Both CLIENT and SERVER request the certificate of their peer and verify |
|
176 | 4. Both CLIENT and SERVER request the certificate of their peer and verify | |
177 | that certificate. If this succeeds, all further communications are |
|
177 | that certificate. If this succeeds, all further communications are | |
178 | encrypted. |
|
178 | encrypted. | |
179 | 5. Both CLIENT and SERVER send a hello block containing connection parameters |
|
179 | 5. Both CLIENT and SERVER send a hello block containing connection parameters | |
180 | and their process id. |
|
180 | and their process id. | |
181 | 6. The CLIENT and SERVER check that their peer's stated process id matches the |
|
181 | 6. The CLIENT and SERVER check that their peer's stated process id matches the | |
182 | hash of the x509 certificate the peer presented. If not, the connection is |
|
182 | hash of the x509 certificate the peer presented. If not, the connection is | |
183 | aborted. |
|
183 | aborted. | |
184 | 7. The CLIENT verifies that the SERVER's stated id matches the id of the |
|
184 | 7. The CLIENT verifies that the SERVER's stated id matches the id of the | |
185 | SERVER the CLIENT is intending to connect to. If not, the connection is |
|
185 | SERVER the CLIENT is intending to connect to. If not, the connection is | |
186 | aborted. |
|
186 | aborted. | |
187 | 8. The CLIENT and SERVER elect a master who decides on the final connection |
|
187 | 8. The CLIENT and SERVER elect a master who decides on the final connection | |
188 | parameters. |
|
188 | parameters. | |
189 |
|
189 | |||
190 | The public/private key pair associated with each process's x509 certificate |
|
190 | The public/private key pair associated with each process's x509 certificate | |
191 | are completely hidden from this handshake protocol. There are however, used |
|
191 | are completely hidden from this handshake protocol. There are however, used | |
192 | internally by OpenSSL as part of the SSL handshake protocol. Each process |
|
192 | internally by OpenSSL as part of the SSL handshake protocol. Each process | |
193 | keeps their own private key hidden and sends its peer only the public key |
|
193 | keeps their own private key hidden and sends its peer only the public key | |
194 | (embedded in the certificate). |
|
194 | (embedded in the certificate). | |
195 |
|
195 | |||
196 | Finally, when the CLIENT requests access to a particular SERVER capability, |
|
196 | Finally, when the CLIENT requests access to a particular SERVER capability, | |
197 | the following happens: |
|
197 | the following happens: | |
198 |
|
198 | |||
199 | 1. The CLIENT asks the SERVER for access to a capability by presenting that |
|
199 | 1. The CLIENT asks the SERVER for access to a capability by presenting that | |
200 | capabilities id. |
|
200 | capabilities id. | |
201 | 2. If the SERVER has a capability with that id, access is granted. If not, |
|
201 | 2. If the SERVER has a capability with that id, access is granted. If not, | |
202 | access is not granted. |
|
202 | access is not granted. | |
203 | 3. Once access has been gained, the CLIENT can use the capability. |
|
203 | 3. Once access has been gained, the CLIENT can use the capability. | |
204 |
|
204 | |||
205 | Specific security vulnerabilities |
|
205 | Specific security vulnerabilities | |
206 | ================================= |
|
206 | ================================= | |
207 |
|
207 | |||
208 | There are a number of potential security vulnerabilities present in IPython's |
|
208 | There are a number of potential security vulnerabilities present in IPython's | |
209 | architecture. In this section we discuss those vulnerabilities and detail how |
|
209 | architecture. In this section we discuss those vulnerabilities and detail how | |
210 | the security architecture described above prevents them from being exploited. |
|
210 | the security architecture described above prevents them from being exploited. | |
211 |
|
211 | |||
212 | Unauthorized clients |
|
212 | Unauthorized clients | |
213 | -------------------- |
|
213 | -------------------- | |
214 |
|
214 | |||
215 | The IPython client can instruct the IPython engines to execute arbitrary |
|
215 | The IPython client can instruct the IPython engines to execute arbitrary | |
216 | Python code with the permissions of the user who started the engines. If an |
|
216 | Python code with the permissions of the user who started the engines. If an | |
217 | attacker were able to connect their own hostile IPython client to the IPython |
|
217 | attacker were able to connect their own hostile IPython client to the IPython | |
218 | controller, they could instruct the engines to execute code. |
|
218 | controller, they could instruct the engines to execute code. | |
219 |
|
219 | |||
220 | This attack is prevented by the capabilities based client authentication |
|
220 | This attack is prevented by the capabilities based client authentication | |
221 | performed after the encrypted channel has been established. The relevant |
|
221 | performed after the encrypted channel has been established. The relevant | |
222 | authentication information is encoded into the FURL that clients must |
|
222 | authentication information is encoded into the FURL that clients must | |
223 | present to gain access to the IPython controller. By limiting the distribution |
|
223 | present to gain access to the IPython controller. By limiting the distribution | |
224 | of those FURLs, a user can grant access to only authorized persons. |
|
224 | of those FURLs, a user can grant access to only authorized persons. | |
225 |
|
225 | |||
226 | It is highly unlikely that a client FURL could be guessed by an attacker |
|
226 | It is highly unlikely that a client FURL could be guessed by an attacker | |
227 | in a brute force guessing attack. A given instance of the IPython controller |
|
227 | in a brute force guessing attack. A given instance of the IPython controller | |
228 | only runs for a relatively short amount of time (on the order of hours). Thus |
|
228 | only runs for a relatively short amount of time (on the order of hours). Thus | |
229 | an attacker would have only a limited amount of time to test a search space of |
|
229 | an attacker would have only a limited amount of time to test a search space of | |
230 | size 2**320. Furthermore, even if a controller were to run for a longer amount |
|
230 | size 2**320. Furthermore, even if a controller were to run for a longer amount | |
231 | of time, this search space is quite large (larger for instance than that of |
|
231 | of time, this search space is quite large (larger for instance than that of | |
232 | typical username/password pair). |
|
232 | typical username/password pair). | |
233 |
|
233 | |||
234 | Unauthorized engines |
|
234 | Unauthorized engines | |
235 | -------------------- |
|
235 | -------------------- | |
236 |
|
236 | |||
237 | If an attacker were able to connect a hostile engine to a user's controller, |
|
237 | If an attacker were able to connect a hostile engine to a user's controller, | |
238 | the user might unknowingly send sensitive code or data to the hostile engine. |
|
238 | the user might unknowingly send sensitive code or data to the hostile engine. | |
239 | This attacker's engine would then have full access to that code and data. |
|
239 | This attacker's engine would then have full access to that code and data. | |
240 |
|
240 | |||
241 | This type of attack is prevented in the same way as the unauthorized client |
|
241 | This type of attack is prevented in the same way as the unauthorized client | |
242 | attack, through the usage of the capabilities based authentication scheme. |
|
242 | attack, through the usage of the capabilities based authentication scheme. | |
243 |
|
243 | |||
244 | Unauthorized controllers |
|
244 | Unauthorized controllers | |
245 | ------------------------ |
|
245 | ------------------------ | |
246 |
|
246 | |||
247 | It is also possible that an attacker could try to convince a user's IPython |
|
247 | It is also possible that an attacker could try to convince a user's IPython | |
248 | client or engine to connect to a hostile IPython controller. That controller |
|
248 | client or engine to connect to a hostile IPython controller. That controller | |
249 | would then have full access to the code and data sent between the IPython |
|
249 | would then have full access to the code and data sent between the IPython | |
250 | client and the IPython engines. |
|
250 | client and the IPython engines. | |
251 |
|
251 | |||
252 | Again, this attack is prevented through the FURLs, which ensure that a |
|
252 | Again, this attack is prevented through the FURLs, which ensure that a | |
253 | client or engine connects to the correct controller. It is also important to |
|
253 | client or engine connects to the correct controller. It is also important to | |
254 | note that the FURLs also encode the IP address and port that the |
|
254 | note that the FURLs also encode the IP address and port that the | |
255 | controller is listening on, so there is little chance of mistakenly connecting |
|
255 | controller is listening on, so there is little chance of mistakenly connecting | |
256 | to a controller running on a different IP address and port. |
|
256 | to a controller running on a different IP address and port. | |
257 |
|
257 | |||
258 | When starting an engine or client, a user must specify which FURL to use |
|
258 | When starting an engine or client, a user must specify which FURL to use | |
259 | for that connection. Thus, in order to introduce a hostile controller, the |
|
259 | for that connection. Thus, in order to introduce a hostile controller, the | |
260 | attacker must convince the user to use the FURLs associated with the |
|
260 | attacker must convince the user to use the FURLs associated with the | |
261 | hostile controller. As long as a user is diligent in only using FURLs from |
|
261 | hostile controller. As long as a user is diligent in only using FURLs from | |
262 | trusted sources, this attack is not possible. |
|
262 | trusted sources, this attack is not possible. | |
263 |
|
263 | |||
264 | Other security measures |
|
264 | Other security measures | |
265 | ======================= |
|
265 | ======================= | |
266 |
|
266 | |||
267 | A number of other measures are taken to further limit the security risks |
|
267 | A number of other measures are taken to further limit the security risks | |
268 | involved in running the IPython kernel. |
|
268 | involved in running the IPython kernel. | |
269 |
|
269 | |||
270 | First, by default, the IPython controller listens on random port numbers. |
|
270 | First, by default, the IPython controller listens on random port numbers. | |
271 | While this can be overridden by the user, in the default configuration, an |
|
271 | While this can be overridden by the user, in the default configuration, an | |
272 | attacker would have to do a port scan to even find a controller to attack. |
|
272 | attacker would have to do a port scan to even find a controller to attack. | |
273 | When coupled with the relatively short running time of a typical controller |
|
273 | When coupled with the relatively short running time of a typical controller | |
274 | (on the order of hours), an attacker would have to work extremely hard and |
|
274 | (on the order of hours), an attacker would have to work extremely hard and | |
275 | extremely *fast* to even find a running controller to attack. |
|
275 | extremely *fast* to even find a running controller to attack. | |
276 |
|
276 | |||
277 | Second, much of the time, especially when run on supercomputers or clusters, |
|
277 | Second, much of the time, especially when run on supercomputers or clusters, | |
278 | the controller is running behind a firewall. Thus, for engines or client to |
|
278 | the controller is running behind a firewall. Thus, for engines or client to | |
279 | connect to the controller: |
|
279 | connect to the controller: | |
280 |
|
280 | |||
281 | * The different processes have to all be behind the firewall. |
|
281 | * The different processes have to all be behind the firewall. | |
282 |
|
282 | |||
283 | or: |
|
283 | or: | |
284 |
|
284 | |||
285 | * The user has to use SSH port forwarding to tunnel the |
|
285 | * The user has to use SSH port forwarding to tunnel the | |
286 | connections through the firewall. |
|
286 | connections through the firewall. | |
287 |
|
287 | |||
288 | In either case, an attacker is presented with addition barriers that prevent |
|
288 | In either case, an attacker is presented with addition barriers that prevent | |
289 | attacking or even probing the system. |
|
289 | attacking or even probing the system. | |
290 |
|
290 | |||
291 | Summary |
|
291 | Summary | |
292 | ======= |
|
292 | ======= | |
293 |
|
293 | |||
294 | IPython's architecture has been carefully designed with security in mind. The |
|
294 | IPython's architecture has been carefully designed with security in mind. The | |
295 | capabilities based authentication model, in conjunction with the encrypted |
|
295 | capabilities based authentication model, in conjunction with the encrypted | |
296 | TCP/IP channels, address the core potential vulnerabilities in the system, |
|
296 | TCP/IP channels, address the core potential vulnerabilities in the system, | |
297 | while still enabling user's to use the system in open networks. |
|
297 | while still enabling user's to use the system in open networks. | |
298 |
|
298 | |||
299 | Other questions |
|
299 | Other questions | |
300 | =============== |
|
300 | =============== | |
301 |
|
301 | |||
302 | About keys |
|
302 | About keys | |
303 | ---------- |
|
303 | ---------- | |
304 |
|
304 | |||
305 | Can you clarify the roles of the certificate and its keys versus the FURL, |
|
305 | Can you clarify the roles of the certificate and its keys versus the FURL, | |
306 | which is also called a key? |
|
306 | which is also called a key? | |
307 |
|
307 | |||
308 | The certificate created by IPython processes is a standard public key x509 |
|
308 | The certificate created by IPython processes is a standard public key x509 | |
309 | certificate, that is used by the SSL handshake protocol to setup encrypted |
|
309 | certificate, that is used by the SSL handshake protocol to setup encrypted | |
310 | channel between the controller and the IPython engine or client. This public |
|
310 | channel between the controller and the IPython engine or client. This public | |
311 | and private key associated with this certificate are used only by the SSL |
|
311 | and private key associated with this certificate are used only by the SSL | |
312 | handshake protocol in setting up this encrypted channel. |
|
312 | handshake protocol in setting up this encrypted channel. | |
313 |
|
313 | |||
314 | The FURL serves a completely different and independent purpose from the |
|
314 | The FURL serves a completely different and independent purpose from the | |
315 | key pair associated with the certificate. When we refer to a FURL as a |
|
315 | key pair associated with the certificate. When we refer to a FURL as a | |
316 | key, we are using the word "key" in the capabilities based security model |
|
316 | key, we are using the word "key" in the capabilities based security model | |
317 | sense. This has nothing to do with "key" in the public/private key sense used |
|
317 | sense. This has nothing to do with "key" in the public/private key sense used | |
318 | in the SSL protocol. |
|
318 | in the SSL protocol. | |
319 |
|
319 | |||
320 | With that said the FURL is used as an cryptographic key, to grant |
|
320 | With that said the FURL is used as an cryptographic key, to grant | |
321 | IPython engines and clients access to particular capabilities that the |
|
321 | IPython engines and clients access to particular capabilities that the | |
322 | controller offers. |
|
322 | controller offers. | |
323 |
|
323 | |||
324 | Self signed certificates |
|
324 | Self signed certificates | |
325 | ------------------------ |
|
325 | ------------------------ | |
326 |
|
326 | |||
327 | Is the controller creating a self-signed certificate? Is this created for per |
|
327 | Is the controller creating a self-signed certificate? Is this created for per | |
328 | instance/session, one-time-setup or each-time the controller is started? |
|
328 | instance/session, one-time-setup or each-time the controller is started? | |
329 |
|
329 | |||
330 | The Foolscap network protocol, which handles the SSL protocol details, creates |
|
330 | The Foolscap network protocol, which handles the SSL protocol details, creates | |
331 | a self-signed x509 certificate using OpenSSL for each IPython process. The |
|
331 | a self-signed x509 certificate using OpenSSL for each IPython process. The | |
332 | lifetime of the certificate is handled differently for the IPython controller |
|
332 | lifetime of the certificate is handled differently for the IPython controller | |
333 | and the engines/client. |
|
333 | and the engines/client. | |
334 |
|
334 | |||
335 | For the IPython engines and client, the certificate is only held in memory for |
|
335 | For the IPython engines and client, the certificate is only held in memory for | |
336 | the lifetime of its process. It is never written to disk. |
|
336 | the lifetime of its process. It is never written to disk. | |
337 |
|
337 | |||
338 | For the controller, the certificate can be created anew each time the |
|
338 | For the controller, the certificate can be created anew each time the | |
339 | controller starts or it can be created once and reused each time the |
|
339 | controller starts or it can be created once and reused each time the | |
340 | controller starts. If at any point, the certificate is deleted, a new one is |
|
340 | controller starts. If at any point, the certificate is deleted, a new one is | |
341 | created the next time the controller starts. |
|
341 | created the next time the controller starts. | |
342 |
|
342 | |||
343 | SSL private key |
|
343 | SSL private key | |
344 | --------------- |
|
344 | --------------- | |
345 |
|
345 | |||
346 | How the private key (associated with the certificate) is distributed? |
|
346 | How the private key (associated with the certificate) is distributed? | |
347 |
|
347 | |||
348 | In the usual implementation of the SSL protocol, the private key is never |
|
348 | In the usual implementation of the SSL protocol, the private key is never | |
349 | distributed. We follow this standard always. |
|
349 | distributed. We follow this standard always. | |
350 |
|
350 | |||
351 | SSL versus Foolscap authentication |
|
351 | SSL versus Foolscap authentication | |
352 | ---------------------------------- |
|
352 | ---------------------------------- | |
353 |
|
353 | |||
354 | Many SSL connections only perform one sided authentication (the server to the |
|
354 | Many SSL connections only perform one sided authentication (the server to the | |
355 | client). How is the client authentication in IPython's system related to SSL |
|
355 | client). How is the client authentication in IPython's system related to SSL | |
356 | authentication? |
|
356 | authentication? | |
357 |
|
357 | |||
358 | We perform a two way SSL handshake in which both parties request and verify |
|
358 | We perform a two way SSL handshake in which both parties request and verify | |
359 | the certificate of their peer. This mutual authentication is handled by the |
|
359 | the certificate of their peer. This mutual authentication is handled by the | |
360 | SSL handshake and is separate and independent from the additional |
|
360 | SSL handshake and is separate and independent from the additional | |
361 | authentication steps that the CLIENT and SERVER perform after an encrypted |
|
361 | authentication steps that the CLIENT and SERVER perform after an encrypted | |
362 | channel is established. |
|
362 | channel is established. | |
363 |
|
363 | |||
364 | .. [RFC5246] <http://tools.ietf.org/html/rfc5246> |
|
364 | .. [RFC5246] <http://tools.ietf.org/html/rfc5246> | |
365 |
|
365 | |||
366 |
|
366 |
@@ -1,121 +1,121 b'' | |||||
1 | .. _paralleltask: |
|
1 | .. _paralleltask: | |
2 |
|
2 | |||
3 | ========================== |
|
3 | ========================== | |
4 | The IPython task interface |
|
4 | The IPython task interface | |
5 | ========================== |
|
5 | ========================== | |
6 |
|
6 | |||
7 | The task interface to the controller presents the engines as a fault tolerant, |
|
7 | The task interface to the controller presents the engines as a fault tolerant, | |
8 | dynamic load-balanced system or workers. Unlike the multiengine interface, in |
|
8 | dynamic load-balanced system or workers. Unlike the multiengine interface, in | |
9 | the task interface, the user have no direct access to individual engines. In |
|
9 | the task interface, the user have no direct access to individual engines. In | |
10 | some ways, this interface is simpler, but in other ways it is more powerful. |
|
10 | some ways, this interface is simpler, but in other ways it is more powerful. | |
11 |
|
11 | |||
12 | Best of all the user can use both of these interfaces running at the same time |
|
12 | Best of all the user can use both of these interfaces running at the same time | |
13 | to take advantage or both of their strengths. When the user can break up the |
|
13 | to take advantage or both of their strengths. When the user can break up the | |
14 | user's work into segments that do not depend on previous execution, the task |
|
14 | user's work into segments that do not depend on previous execution, the task | |
15 | interface is ideal. But it also has more power and flexibility, allowing the |
|
15 | interface is ideal. But it also has more power and flexibility, allowing the | |
16 | user to guide the distribution of jobs, without having to assign tasks to |
|
16 | user to guide the distribution of jobs, without having to assign tasks to | |
17 | engines explicitly. |
|
17 | engines explicitly. | |
18 |
|
18 | |||
19 | Starting the IPython controller and engines |
|
19 | Starting the IPython controller and engines | |
20 | =========================================== |
|
20 | =========================================== | |
21 |
|
21 | |||
22 | To follow along with this tutorial, you will need to start the IPython |
|
22 | To follow along with this tutorial, you will need to start the IPython | |
23 | controller and four IPython engines. The simplest way of doing this is to use |
|
23 | controller and four IPython engines. The simplest way of doing this is to use | |
24 | the :command:`ipcluster` command:: |
|
24 | the :command:`ipcluster` command:: | |
25 |
|
25 | |||
26 | $ ipcluster local -n 4 |
|
26 | $ ipcluster local -n 4 | |
27 |
|
27 | |||
28 | For more detailed information about starting the controller and engines, see |
|
28 | For more detailed information about starting the controller and engines, see | |
29 | our :ref:`introduction <ip1par>` to using IPython for parallel computing. |
|
29 | our :ref:`introduction <ip1par>` to using IPython for parallel computing. | |
30 |
|
30 | |||
31 | Creating a ``TaskClient`` instance |
|
31 | Creating a ``TaskClient`` instance | |
32 | ========================================= |
|
32 | ========================================= | |
33 |
|
33 | |||
34 | The first step is to import the IPython :mod:`IPython.kernel.client` module |
|
34 | The first step is to import the IPython :mod:`IPython.kernel.client` module | |
35 | and then create a :class:`TaskClient` instance: |
|
35 | and then create a :class:`TaskClient` instance: | |
36 |
|
36 | |||
37 | .. sourcecode:: ipython |
|
37 | .. sourcecode:: ipython | |
38 |
|
38 | |||
39 | In [1]: from IPython.kernel import client |
|
39 | In [1]: from IPython.kernel import client | |
40 |
|
40 | |||
41 | In [2]: tc = client.TaskClient() |
|
41 | In [2]: tc = client.TaskClient() | |
42 |
|
42 | |||
43 | This form assumes that the :file:`ipcontroller-tc.furl` is in the |
|
43 | This form assumes that the :file:`ipcontroller-tc.furl` is in the | |
44 |
:file:` |
|
44 | :file:`$IPYTHON_DIR/cluster_<profile>/security` directory on the client's host. If not, the | |
45 | location of the FURL file must be given as an argument to the |
|
45 | location of the FURL file must be given as an argument to the | |
46 | constructor: |
|
46 | constructor: | |
47 |
|
47 | |||
48 | .. sourcecode:: ipython |
|
48 | .. sourcecode:: ipython | |
49 |
|
49 | |||
50 | In [2]: mec = client.TaskClient('/path/to/my/ipcontroller-tc.furl') |
|
50 | In [2]: mec = client.TaskClient('/path/to/my/ipcontroller-tc.furl') | |
51 |
|
51 | |||
52 | Quick and easy parallelism |
|
52 | Quick and easy parallelism | |
53 | ========================== |
|
53 | ========================== | |
54 |
|
54 | |||
55 | In many cases, you simply want to apply a Python function to a sequence of |
|
55 | In many cases, you simply want to apply a Python function to a sequence of | |
56 | objects, but *in parallel*. Like the multiengine interface, the task interface |
|
56 | objects, but *in parallel*. Like the multiengine interface, the task interface | |
57 | provides two simple ways of accomplishing this: a parallel version of |
|
57 | provides two simple ways of accomplishing this: a parallel version of | |
58 | :func:`map` and ``@parallel`` function decorator. However, the verions in the |
|
58 | :func:`map` and ``@parallel`` function decorator. However, the verions in the | |
59 | task interface have one important difference: they are dynamically load |
|
59 | task interface have one important difference: they are dynamically load | |
60 | balanced. Thus, if the execution time per item varies significantly, you |
|
60 | balanced. Thus, if the execution time per item varies significantly, you | |
61 | should use the versions in the task interface. |
|
61 | should use the versions in the task interface. | |
62 |
|
62 | |||
63 | Parallel map |
|
63 | Parallel map | |
64 | ------------ |
|
64 | ------------ | |
65 |
|
65 | |||
66 | The parallel :meth:`map` in the task interface is similar to that in the |
|
66 | The parallel :meth:`map` in the task interface is similar to that in the | |
67 | multiengine interface: |
|
67 | multiengine interface: | |
68 |
|
68 | |||
69 | .. sourcecode:: ipython |
|
69 | .. sourcecode:: ipython | |
70 |
|
70 | |||
71 | In [63]: serial_result = map(lambda x:x**10, range(32)) |
|
71 | In [63]: serial_result = map(lambda x:x**10, range(32)) | |
72 |
|
72 | |||
73 | In [64]: parallel_result = tc.map(lambda x:x**10, range(32)) |
|
73 | In [64]: parallel_result = tc.map(lambda x:x**10, range(32)) | |
74 |
|
74 | |||
75 | In [65]: serial_result==parallel_result |
|
75 | In [65]: serial_result==parallel_result | |
76 | Out[65]: True |
|
76 | Out[65]: True | |
77 |
|
77 | |||
78 | Parallel function decorator |
|
78 | Parallel function decorator | |
79 | --------------------------- |
|
79 | --------------------------- | |
80 |
|
80 | |||
81 | Parallel functions are just like normal function, but they can be called on |
|
81 | Parallel functions are just like normal function, but they can be called on | |
82 | sequences and *in parallel*. The multiengine interface provides a decorator |
|
82 | sequences and *in parallel*. The multiengine interface provides a decorator | |
83 | that turns any Python function into a parallel function: |
|
83 | that turns any Python function into a parallel function: | |
84 |
|
84 | |||
85 | .. sourcecode:: ipython |
|
85 | .. sourcecode:: ipython | |
86 |
|
86 | |||
87 | In [10]: @tc.parallel() |
|
87 | In [10]: @tc.parallel() | |
88 | ....: def f(x): |
|
88 | ....: def f(x): | |
89 | ....: return 10.0*x**4 |
|
89 | ....: return 10.0*x**4 | |
90 | ....: |
|
90 | ....: | |
91 |
|
91 | |||
92 | In [11]: f(range(32)) # this is done in parallel |
|
92 | In [11]: f(range(32)) # this is done in parallel | |
93 | Out[11]: |
|
93 | Out[11]: | |
94 | [0.0,10.0,160.0,...] |
|
94 | [0.0,10.0,160.0,...] | |
95 |
|
95 | |||
96 | More details |
|
96 | More details | |
97 | ============ |
|
97 | ============ | |
98 |
|
98 | |||
99 | The :class:`TaskClient` has many more powerful features that allow quite a bit |
|
99 | The :class:`TaskClient` has many more powerful features that allow quite a bit | |
100 | of flexibility in how tasks are defined and run. The next places to look are |
|
100 | of flexibility in how tasks are defined and run. The next places to look are | |
101 | in the following classes: |
|
101 | in the following classes: | |
102 |
|
102 | |||
103 | * :class:`IPython.kernel.client.TaskClient` |
|
103 | * :class:`IPython.kernel.client.TaskClient` | |
104 | * :class:`IPython.kernel.client.StringTask` |
|
104 | * :class:`IPython.kernel.client.StringTask` | |
105 | * :class:`IPython.kernel.client.MapTask` |
|
105 | * :class:`IPython.kernel.client.MapTask` | |
106 |
|
106 | |||
107 | The following is an overview of how to use these classes together: |
|
107 | The following is an overview of how to use these classes together: | |
108 |
|
108 | |||
109 | 1. Create a :class:`TaskClient`. |
|
109 | 1. Create a :class:`TaskClient`. | |
110 | 2. Create one or more instances of :class:`StringTask` or :class:`MapTask` |
|
110 | 2. Create one or more instances of :class:`StringTask` or :class:`MapTask` | |
111 | to define your tasks. |
|
111 | to define your tasks. | |
112 | 3. Submit your tasks to using the :meth:`run` method of your |
|
112 | 3. Submit your tasks to using the :meth:`run` method of your | |
113 | :class:`TaskClient` instance. |
|
113 | :class:`TaskClient` instance. | |
114 | 4. Use :meth:`TaskClient.get_task_result` to get the results of the |
|
114 | 4. Use :meth:`TaskClient.get_task_result` to get the results of the | |
115 | tasks. |
|
115 | tasks. | |
116 |
|
116 | |||
117 | We are in the process of developing more detailed information about the task |
|
117 | We are in the process of developing more detailed information about the task | |
118 | interface. For now, the docstrings of the :class:`TaskClient`, |
|
118 | interface. For now, the docstrings of the :class:`TaskClient`, | |
119 | :class:`StringTask` and :class:`MapTask` classes should be consulted. |
|
119 | :class:`StringTask` and :class:`MapTask` classes should be consulted. | |
120 |
|
120 | |||
121 |
|
121 |
General Comments 0
You need to be logged in to leave comments.
Login now