ipython.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. from IPython.core.magic import Magics, line_magic, magics_class # type: ignore
  2. from IPython.core.magic_arguments import (
  3. argument,
  4. magic_arguments,
  5. parse_argstring,
  6. ) # type: ignore
  7. from .main import find_dotenv, load_dotenv
  8. @magics_class
  9. class IPythonDotEnv(Magics):
  10. @magic_arguments()
  11. @argument(
  12. "-o",
  13. "--override",
  14. action="store_true",
  15. help="Indicate to override existing variables",
  16. )
  17. @argument(
  18. "-v",
  19. "--verbose",
  20. action="store_true",
  21. help="Indicate function calls to be verbose",
  22. )
  23. @argument(
  24. "dotenv_path",
  25. nargs="?",
  26. type=str,
  27. default=".env",
  28. help="Search in increasingly higher folders for the `dotenv_path`",
  29. )
  30. @line_magic
  31. def dotenv(self, line):
  32. args = parse_argstring(self.dotenv, line)
  33. # Locate the .env file
  34. dotenv_path = args.dotenv_path
  35. try:
  36. dotenv_path = find_dotenv(dotenv_path, True, True)
  37. except IOError:
  38. print("cannot find .env file")
  39. return
  40. # Load the .env file
  41. load_dotenv(dotenv_path, verbose=args.verbose, override=args.override)
  42. def load_ipython_extension(ipython):
  43. """Register the %dotenv magic."""
  44. ipython.register_magics(IPythonDotEnv)