Skip to content

Commit da0c820

Browse files
bbc2theskumar
andauthored
fix: print friendly error for missing command in dotenv run (#606)
Changes for users: - (BREAKING) `dotenv run` exits with status code 1 instead of 2 if the command provided as argument can't be found. - `dotenv run` prints a friendly error message instead of a stack trace if the command provided as argument can't be found. Notes: The existing test case was wrongly testing for that situation: it was actually observing a "missing env file" error, not a "command not found error". I thus added an appropriate test case for full coverage. Co-authored-by: Saurabh Kumar <theskumar@users.noreply.github.com>
1 parent dc71adb commit da0c820

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

src/dotenv/cli.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -228,9 +228,20 @@ def run_command(command: List[str], env: Dict[str, str]) -> None:
228228
if sys.platform == "win32":
229229
# execvpe on Windows returns control immediately
230230
# rather than once the command has finished.
231-
p = Popen(command, universal_newlines=True, bufsize=0, shell=False, env=cmd_env)
231+
try:
232+
p = Popen(
233+
command, universal_newlines=True, bufsize=0, shell=False, env=cmd_env
234+
)
235+
except FileNotFoundError:
236+
print(f"Command not found: {command[0]}", file=sys.stderr)
237+
sys.exit(1)
238+
232239
_, _ = p.communicate()
233240

234241
sys.exit(p.returncode)
235242
else:
236-
os.execvpe(command[0], args=command, env=cmd_env)
243+
try:
244+
os.execvpe(command[0], args=command, env=cmd_env)
245+
except FileNotFoundError:
246+
print(f"Command not found: {command[0]}", file=sys.stderr)
247+
sys.exit(1)

tests/test_cli.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -237,7 +237,21 @@ def test_run_without_cmd(tmp_path):
237237
assert "Invalid value for '-f'" in result.stderr
238238

239239

240-
def test_run_with_invalid_cmd(tmp_path):
240+
def test_run_with_invalid_cmd(dotenv_path, tmp_path):
241+
result = run_dotenv(
242+
["--file", str(dotenv_path), "run", "i_do_not_exist"],
243+
cwd=tmp_path,
244+
)
245+
246+
check_process(result, exit_code=1)
247+
assert "Command not found: i_do_not_exist" in result.stderr
248+
249+
250+
def test_run_with_env_missing_and_invalid_cmd(tmp_path):
251+
"""
252+
Check that an .env file missing takes precedence over a command not found error.
253+
"""
254+
241255
result = run_dotenv(["run", "i_do_not_exist"], cwd=tmp_path)
242256

243257
check_process(result, exit_code=2)

0 commit comments

Comments
 (0)