Skip to content

Commit 2fef1da

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 f54d29f commit 2fef1da

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

src/dotenv/cli.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -210,9 +210,20 @@ 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(
215+
command, universal_newlines=True, bufsize=0, shell=False, env=cmd_env
216+
)
217+
except FileNotFoundError:
218+
print(f"Command not found: {command[0]}", file=sys.stderr)
219+
sys.exit(1)
220+
214221
_, _ = p.communicate()
215222

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

tests/test_cli.py

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

239239

240-
def test_run_with_invalid_cmd(cli):
240+
def test_run_with_invalid_cmd(cli, dotenv_path):
241+
result = cli.invoke(dotenv_cli, ["--file", dotenv_path, "run", "i_do_not_exist"])
242+
243+
assert result.exit_code == 1
244+
assert "Command not found: i_do_not_exist" in result.output
245+
246+
247+
def test_run_with_env_missing_and_invalid_cmd(cli):
248+
"""
249+
Check that an .env file missing takes precedence over a command not found error.
250+
"""
251+
241252
result = cli.invoke(dotenv_cli, ["run", "i_do_not_exist"])
242253

243254
assert result.exit_code == 2

0 commit comments

Comments
 (0)