application.py 18 KB

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