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