Search in increasingly higher folders for the given file Returns path to the file if found, or an empty string otherwise
(
filename: str = ".env",
raise_error_if_not_found: bool = False,
usecwd: bool = False,
)
| 330 | |
| 331 | |
| 332 | def find_dotenv( |
| 333 | filename: str = ".env", |
| 334 | raise_error_if_not_found: bool = False, |
| 335 | usecwd: bool = False, |
| 336 | ) -> str: |
| 337 | """ |
| 338 | Search in increasingly higher folders for the given file |
| 339 | |
| 340 | Returns path to the file if found, or an empty string otherwise |
| 341 | """ |
| 342 | |
| 343 | def _is_interactive(): |
| 344 | """Decide whether this is running in a REPL or IPython notebook""" |
| 345 | if hasattr(sys, "ps1") or hasattr(sys, "ps2"): |
| 346 | return True |
| 347 | try: |
| 348 | main = __import__("__main__", None, None, fromlist=["__file__"]) |
| 349 | except ModuleNotFoundError: |
| 350 | return False |
| 351 | return not hasattr(main, "__file__") |
| 352 | |
| 353 | def _is_debugger(): |
| 354 | return sys.gettrace() is not None |
| 355 | |
| 356 | if usecwd or _is_interactive() or _is_debugger() or getattr(sys, "frozen", False): |
| 357 | # Should work without __file__, e.g. in REPL or IPython notebook. |
| 358 | path = os.getcwd() |
| 359 | else: |
| 360 | # will work for .py files |
| 361 | frame = sys._getframe() |
| 362 | current_file = __file__ |
| 363 | |
| 364 | while frame.f_code.co_filename == current_file or not os.path.exists( |
| 365 | frame.f_code.co_filename |
| 366 | ): |
| 367 | assert frame.f_back is not None |
| 368 | frame = frame.f_back |
| 369 | frame_filename = frame.f_code.co_filename |
| 370 | path = os.path.dirname(os.path.abspath(frame_filename)) |
| 371 | |
| 372 | for dirname in _walk_to_root(path): |
| 373 | check_path = os.path.join(dirname, filename) |
| 374 | if _is_file_or_fifo(check_path): |
| 375 | return check_path |
| 376 | |
| 377 | if raise_error_if_not_found: |
| 378 | raise IOError("File not found") |
| 379 | |
| 380 | return "" |
| 381 | |
| 382 | |
| 383 | def load_dotenv( |
searching dependent graphs…