##// END OF EJS Templates
set profile name from profile_dir...
MinRK -
Show More
@@ -1,382 +1,386 b''
1 1 # encoding: utf-8
2 2 """
3 3 An application for IPython.
4 4
5 5 All top-level applications should use the classes in this module for
6 6 handling configuration and creating configurables.
7 7
8 8 The job of an :class:`Application` is to create the master configuration
9 9 object and then create the configurable objects, passing the config to them.
10 10
11 11 Authors:
12 12
13 13 * Brian Granger
14 14 * Fernando Perez
15 15 * Min RK
16 16
17 17 """
18 18
19 19 #-----------------------------------------------------------------------------
20 20 # Copyright (C) 2008 The IPython Development Team
21 21 #
22 22 # Distributed under the terms of the BSD License. The full license is in
23 23 # the file COPYING, distributed as part of this software.
24 24 #-----------------------------------------------------------------------------
25 25
26 26 #-----------------------------------------------------------------------------
27 27 # Imports
28 28 #-----------------------------------------------------------------------------
29 29
30 30 import atexit
31 31 import errno
32 32 import glob
33 33 import logging
34 34 import os
35 35 import shutil
36 36 import sys
37 37
38 38 from IPython.config.application import Application, catch_config_error
39 39 from IPython.config.loader import ConfigFileNotFound
40 40 from IPython.core import release, crashhandler
41 41 from IPython.core.profiledir import ProfileDir, ProfileDirError
42 42 from IPython.utils.path import get_ipython_dir, get_ipython_package_dir
43 43 from IPython.utils import py3compat
44 44 from IPython.utils.traitlets import List, Unicode, Type, Bool, Dict, Set, Instance
45 45
46 46 #-----------------------------------------------------------------------------
47 47 # Classes and functions
48 48 #-----------------------------------------------------------------------------
49 49
50 50
51 51 #-----------------------------------------------------------------------------
52 52 # Base Application Class
53 53 #-----------------------------------------------------------------------------
54 54
55 55 # aliases and flags
56 56
57 57 base_aliases = {
58 58 'profile-dir' : 'ProfileDir.location',
59 59 'profile' : 'BaseIPythonApplication.profile',
60 60 'ipython-dir' : 'BaseIPythonApplication.ipython_dir',
61 61 'log-level' : 'Application.log_level',
62 62 'config' : 'BaseIPythonApplication.extra_config_file',
63 63 }
64 64
65 65 base_flags = dict(
66 66 debug = ({'Application' : {'log_level' : logging.DEBUG}},
67 67 "set log level to logging.DEBUG (maximize logging output)"),
68 68 quiet = ({'Application' : {'log_level' : logging.CRITICAL}},
69 69 "set log level to logging.CRITICAL (minimize logging output)"),
70 70 init = ({'BaseIPythonApplication' : {
71 71 'copy_config_files' : True,
72 72 'auto_create' : True}
73 73 }, """Initialize profile with default config files. This is equivalent
74 74 to running `ipython profile create <profile>` prior to startup.
75 75 """)
76 76 )
77 77
78 78
79 79 class BaseIPythonApplication(Application):
80 80
81 81 name = Unicode(u'ipython')
82 82 description = Unicode(u'IPython: an enhanced interactive Python shell.')
83 83 version = Unicode(release.version)
84 84
85 85 aliases = Dict(base_aliases)
86 86 flags = Dict(base_flags)
87 87 classes = List([ProfileDir])
88 88
89 89 # Track whether the config_file has changed,
90 90 # because some logic happens only if we aren't using the default.
91 91 config_file_specified = Set()
92 92
93 93 config_file_name = Unicode()
94 94 def _config_file_name_default(self):
95 95 return self.name.replace('-','_') + u'_config.py'
96 96 def _config_file_name_changed(self, name, old, new):
97 97 if new != old:
98 98 self.config_file_specified.add(new)
99 99
100 100 # The directory that contains IPython's builtin profiles.
101 101 builtin_profile_dir = Unicode(
102 102 os.path.join(get_ipython_package_dir(), u'config', u'profile', u'default')
103 103 )
104 104
105 105 config_file_paths = List(Unicode)
106 106 def _config_file_paths_default(self):
107 107 return [py3compat.getcwd()]
108 108
109 109 extra_config_file = Unicode(config=True,
110 110 help="""Path to an extra config file to load.
111 111
112 112 If specified, load this config file in addition to any other IPython config.
113 113 """)
114 114 def _extra_config_file_changed(self, name, old, new):
115 115 try:
116 116 self.config_files.remove(old)
117 117 except ValueError:
118 118 pass
119 119 self.config_file_specified.add(new)
120 120 self.config_files.append(new)
121 121
122 122 profile = Unicode(u'default', config=True,
123 123 help="""The IPython profile to use."""
124 124 )
125 125
126 126 def _profile_changed(self, name, old, new):
127 127 self.builtin_profile_dir = os.path.join(
128 128 get_ipython_package_dir(), u'config', u'profile', new
129 129 )
130 130
131 131 ipython_dir = Unicode(config=True,
132 132 help="""
133 133 The name of the IPython directory. This directory is used for logging
134 134 configuration (through profiles), history storage, etc. The default
135 135 is usually $HOME/.ipython. This options can also be specified through
136 136 the environment variable IPYTHONDIR.
137 137 """
138 138 )
139 139 def _ipython_dir_default(self):
140 140 d = get_ipython_dir()
141 141 self._ipython_dir_changed('ipython_dir', d, d)
142 142 return d
143 143
144 144 _in_init_profile_dir = False
145 145 profile_dir = Instance(ProfileDir)
146 146 def _profile_dir_default(self):
147 147 # avoid recursion
148 148 if self._in_init_profile_dir:
149 149 return
150 150 # profile_dir requested early, force initialization
151 151 self.init_profile_dir()
152 152 return self.profile_dir
153 153
154 154 overwrite = Bool(False, config=True,
155 155 help="""Whether to overwrite existing config files when copying""")
156 156 auto_create = Bool(False, config=True,
157 157 help="""Whether to create profile dir if it doesn't exist""")
158 158
159 159 config_files = List(Unicode)
160 160 def _config_files_default(self):
161 161 return [self.config_file_name]
162 162
163 163 copy_config_files = Bool(False, config=True,
164 164 help="""Whether to install the default config files into the profile dir.
165 165 If a new profile is being created, and IPython contains config files for that
166 166 profile, then they will be staged into the new directory. Otherwise,
167 167 default config files will be automatically generated.
168 168 """)
169 169
170 170 verbose_crash = Bool(False, config=True,
171 171 help="""Create a massive crash report when IPython encounters what may be an
172 172 internal error. The default is to append a short message to the
173 173 usual traceback""")
174 174
175 175 # The class to use as the crash handler.
176 176 crash_handler_class = Type(crashhandler.CrashHandler)
177 177
178 178 @catch_config_error
179 179 def __init__(self, **kwargs):
180 180 super(BaseIPythonApplication, self).__init__(**kwargs)
181 181 # ensure current working directory exists
182 182 try:
183 183 directory = py3compat.getcwd()
184 184 except:
185 185 # raise exception
186 186 self.log.error("Current working directory doesn't exist.")
187 187 raise
188 188
189 189 #-------------------------------------------------------------------------
190 190 # Various stages of Application creation
191 191 #-------------------------------------------------------------------------
192 192
193 193 def init_crash_handler(self):
194 194 """Create a crash handler, typically setting sys.excepthook to it."""
195 195 self.crash_handler = self.crash_handler_class(self)
196 196 sys.excepthook = self.excepthook
197 197 def unset_crashhandler():
198 198 sys.excepthook = sys.__excepthook__
199 199 atexit.register(unset_crashhandler)
200 200
201 201 def excepthook(self, etype, evalue, tb):
202 202 """this is sys.excepthook after init_crashhandler
203 203
204 204 set self.verbose_crash=True to use our full crashhandler, instead of
205 205 a regular traceback with a short message (crash_handler_lite)
206 206 """
207 207
208 208 if self.verbose_crash:
209 209 return self.crash_handler(etype, evalue, tb)
210 210 else:
211 211 return crashhandler.crash_handler_lite(etype, evalue, tb)
212 212
213 213 def _ipython_dir_changed(self, name, old, new):
214 214 if old in sys.path:
215 215 sys.path.remove(old)
216 216 sys.path.append(os.path.abspath(new))
217 217 if not os.path.isdir(new):
218 218 os.makedirs(new, mode=0o777)
219 219 readme = os.path.join(new, 'README')
220 220 readme_src = os.path.join(get_ipython_package_dir(), u'config', u'profile', 'README')
221 221 if not os.path.exists(readme) and os.path.exists(readme_src):
222 222 shutil.copy(readme_src, readme)
223 223 for d in ('extensions', 'nbextensions'):
224 224 path = os.path.join(new, d)
225 225 if not os.path.exists(path):
226 226 try:
227 227 os.mkdir(path)
228 228 except OSError as e:
229 229 if e.errno != errno.EEXIST:
230 230 self.log.error("couldn't create path %s: %s", path, e)
231 231 self.log.debug("IPYTHONDIR set to: %s" % new)
232 232
233 233 def load_config_file(self, suppress_errors=True):
234 234 """Load the config file.
235 235
236 236 By default, errors in loading config are handled, and a warning
237 237 printed on screen. For testing, the suppress_errors option is set
238 238 to False, so errors will make tests fail.
239 239 """
240 240 self.log.debug("Searching path %s for config files", self.config_file_paths)
241 241 base_config = 'ipython_config.py'
242 242 self.log.debug("Attempting to load config file: %s" %
243 243 base_config)
244 244 try:
245 245 Application.load_config_file(
246 246 self,
247 247 base_config,
248 248 path=self.config_file_paths
249 249 )
250 250 except ConfigFileNotFound:
251 251 # ignore errors loading parent
252 252 self.log.debug("Config file %s not found", base_config)
253 253 pass
254 254
255 255 for config_file_name in self.config_files:
256 256 if not config_file_name or config_file_name == base_config:
257 257 continue
258 258 self.log.debug("Attempting to load config file: %s" %
259 259 self.config_file_name)
260 260 try:
261 261 Application.load_config_file(
262 262 self,
263 263 config_file_name,
264 264 path=self.config_file_paths
265 265 )
266 266 except ConfigFileNotFound:
267 267 # Only warn if the default config file was NOT being used.
268 268 if config_file_name in self.config_file_specified:
269 269 msg = self.log.warn
270 270 else:
271 271 msg = self.log.debug
272 272 msg("Config file not found, skipping: %s", config_file_name)
273 273 except:
274 274 # For testing purposes.
275 275 if not suppress_errors:
276 276 raise
277 277 self.log.warn("Error loading config file: %s" %
278 278 self.config_file_name, exc_info=True)
279 279
280 280 def init_profile_dir(self):
281 281 """initialize the profile dir"""
282 282 self._in_init_profile_dir = True
283 283 if self.profile_dir is not None:
284 284 # already ran
285 285 return
286 286 if 'ProfileDir.location' not in self.config:
287 287 # location not specified, find by profile name
288 288 try:
289 289 p = ProfileDir.find_profile_dir_by_name(self.ipython_dir, self.profile, self.config)
290 290 except ProfileDirError:
291 291 # not found, maybe create it (always create default profile)
292 292 if self.auto_create or self.profile == 'default':
293 293 try:
294 294 p = ProfileDir.create_profile_dir_by_name(self.ipython_dir, self.profile, self.config)
295 295 except ProfileDirError:
296 296 self.log.fatal("Could not create profile: %r"%self.profile)
297 297 self.exit(1)
298 298 else:
299 299 self.log.info("Created profile dir: %r"%p.location)
300 300 else:
301 301 self.log.fatal("Profile %r not found."%self.profile)
302 302 self.exit(1)
303 303 else:
304 304 self.log.info("Using existing profile dir: %r"%p.location)
305 305 else:
306 306 location = self.config.ProfileDir.location
307 307 # location is fully specified
308 308 try:
309 309 p = ProfileDir.find_profile_dir(location, self.config)
310 310 except ProfileDirError:
311 311 # not found, maybe create it
312 312 if self.auto_create:
313 313 try:
314 314 p = ProfileDir.create_profile_dir(location, self.config)
315 315 except ProfileDirError:
316 316 self.log.fatal("Could not create profile directory: %r"%location)
317 317 self.exit(1)
318 318 else:
319 319 self.log.info("Creating new profile dir: %r"%location)
320 320 else:
321 321 self.log.fatal("Profile directory %r not found."%location)
322 322 self.exit(1)
323 323 else:
324 324 self.log.info("Using existing profile dir: %r"%location)
325 # if profile_dir is specified explicitly, set profile name
326 dir_name = os.path.basename(p.location)
327 if dir_name.startswith('profile_'):
328 self.profile = dir_name[8:]
325 329
326 330 self.profile_dir = p
327 331 self.config_file_paths.append(p.location)
328 332 self._in_init_profile_dir = False
329 333
330 334 def init_config_files(self):
331 335 """[optionally] copy default config files into profile dir."""
332 336 # copy config files
333 337 path = self.builtin_profile_dir
334 338 if self.copy_config_files:
335 339 src = self.profile
336 340
337 341 cfg = self.config_file_name
338 342 if path and os.path.exists(os.path.join(path, cfg)):
339 343 self.log.warn("Staging %r from %s into %r [overwrite=%s]"%(
340 344 cfg, src, self.profile_dir.location, self.overwrite)
341 345 )
342 346 self.profile_dir.copy_config_file(cfg, path=path, overwrite=self.overwrite)
343 347 else:
344 348 self.stage_default_config_file()
345 349 else:
346 350 # Still stage *bundled* config files, but not generated ones
347 351 # This is necessary for `ipython profile=sympy` to load the profile
348 352 # on the first go
349 353 files = glob.glob(os.path.join(path, '*.py'))
350 354 for fullpath in files:
351 355 cfg = os.path.basename(fullpath)
352 356 if self.profile_dir.copy_config_file(cfg, path=path, overwrite=False):
353 357 # file was copied
354 358 self.log.warn("Staging bundled %s from %s into %r"%(
355 359 cfg, self.profile, self.profile_dir.location)
356 360 )
357 361
358 362
359 363 def stage_default_config_file(self):
360 364 """auto generate default config file, and stage it into the profile."""
361 365 s = self.generate_config_file()
362 366 fname = os.path.join(self.profile_dir.location, self.config_file_name)
363 367 if self.overwrite or not os.path.exists(fname):
364 368 self.log.warn("Generating default config file: %r"%(fname))
365 369 with open(fname, 'w') as f:
366 370 f.write(s)
367 371
368 372 @catch_config_error
369 373 def initialize(self, argv=None):
370 374 # don't hook up crash handler before parsing command-line
371 375 self.parse_command_line(argv)
372 376 self.init_crash_handler()
373 377 if self.subapp is not None:
374 378 # stop here if subapp is taking over
375 379 return
376 380 cl_config = self.config
377 381 self.init_profile_dir()
378 382 self.init_config_files()
379 383 self.load_config_file()
380 384 # enforce cl-opts override configfile opts:
381 385 self.update_config(cl_config)
382 386
General Comments 0
You need to be logged in to leave comments. Login now