application.py 18 KB

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