application.py 18 KB

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