ipython.py 1.3 KB

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