Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add argument raise_error_if_not_found for read_env #165

Closed
wants to merge 4 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions environs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,7 @@ def read_env(
recurse: _BoolType = True,
verbose: _BoolType = False,
override: _BoolType = False,
raise_error_if_not_found: _BoolType = False,
) -> None:
"""Read a .env file into os.environ.

Expand All @@ -288,6 +289,8 @@ def read_env(
if Path(path).is_dir():
raise ValueError("path must be a filename, not a directory.")
start = Path(path)

is_env_file_found = False
# TODO: Remove str casts when we drop Python 3.5
if recurse:
start_dir, env_name = os.path.split(str(start))
Expand All @@ -296,10 +299,18 @@ def read_env(
for dirname in _walk_to_root(start_dir):
check_path = Path(dirname) / env_name
if check_path.exists():
is_env_file_found = True
load_dotenv(str(check_path), verbose=verbose, override=override)
return
break
else:
load_dotenv(str(start), verbose=verbose, override=override)
if start.exists():
is_env_file_found = True
load_dotenv(str(start), verbose=verbose, override=override)

if verbose:
print("environ: is_env_file_found={}".format(is_env_file_found))
if raise_error_if_not_found and not is_env_file_found:
raise OSError("File not found: {}".format(path or ".env"))

@contextlib.contextmanager
def prefixed(self, prefix: _StrType) -> typing.Iterator["Env"]:
Expand Down