Skip to content

Commit 59f1196

Browse files
committed
Fix handling of missing command by dotenv run
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.
1 parent c91abd8 commit 59f1196

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

src/dotenv/cli.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -210,9 +210,18 @@ def run_command(command: List[str], env: Dict[str, str]) -> None:
210210
if sys.platform == "win32":
211211
# execvpe on Windows returns control immediately
212212
# rather than once the command has finished.
213-
p = Popen(command, universal_newlines=True, bufsize=0, shell=False, env=cmd_env)
213+
try:
214+
p = Popen(command, universal_newlines=True, bufsize=0, shell=False, env=cmd_env)
215+
except FileNotFoundError:
216+
print(f"Command not found: {command[0]}", file=sys.stderr)
217+
sys.exit(1)
218+
214219
_, _ = p.communicate()
215220

216221
sys.exit(p.returncode)
217222
else:
218-
os.execvpe(command[0], args=command, env=cmd_env)
223+
try:
224+
os.execvpe(command[0], args=command, env=cmd_env)
225+
except FileNotFoundError:
226+
print(f"Command not found: {command[0]}", file=sys.stderr)
227+
sys.exit(1)

tests/test_cli.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,18 @@ def test_run_without_cmd(cli):
246246
assert "Invalid value for '-f'" in result.output
247247

248248

249-
def test_run_with_invalid_cmd(cli):
249+
def test_run_with_invalid_cmd(cli, dotenv_path):
250+
result = cli.invoke(dotenv_cli, ["--file", dotenv_path, "run", "i_do_not_exist"])
251+
252+
assert result.exit_code == 1
253+
assert "Command not found: i_do_not_exist" in result.output
254+
255+
256+
def test_run_with_env_missing_and_invalid_cmd(cli):
257+
"""
258+
Check that an .env file missing takes precedence over a command not found error.
259+
"""
260+
250261
result = cli.invoke(dotenv_cli, ["run", "i_do_not_exist"])
251262

252263
assert result.exit_code == 2

0 commit comments

Comments
 (0)