Skip to content

Commit ceeb066

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 09d7cee commit ceeb066

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
@@ -217,9 +217,20 @@ def run_command(command: List[str], env: Dict[str, str]) -> None:
217217
if sys.platform == "win32":
218218
# execvpe on Windows returns control immediately
219219
# rather than once the command has finished.
220-
p = Popen(command, universal_newlines=True, bufsize=0, shell=False, env=cmd_env)
220+
try:
221+
p = Popen(
222+
command, universal_newlines=True, bufsize=0, shell=False, env=cmd_env
223+
)
224+
except FileNotFoundError:
225+
print(f"Command not found: {command[0]}", file=sys.stderr)
226+
sys.exit(1)
227+
221228
_, _ = p.communicate()
222229

223230
sys.exit(p.returncode)
224231
else:
225-
os.execvpe(command[0], args=command, env=cmd_env)
232+
try:
233+
os.execvpe(command[0], args=command, env=cmd_env)
234+
except FileNotFoundError:
235+
print(f"Command not found: {command[0]}", file=sys.stderr)
236+
sys.exit(1)

tests/test_cli.py

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

264264

265-
def test_run_with_invalid_cmd(cli):
265+
def test_run_with_invalid_cmd(cli, dotenv_path):
266+
result = cli.invoke(dotenv_cli, ["--file", dotenv_path, "run", "i_do_not_exist"])
267+
268+
assert result.exit_code == 1
269+
assert "Command not found: i_do_not_exist" in result.output
270+
271+
272+
def test_run_with_env_missing_and_invalid_cmd(cli):
273+
"""
274+
Check that an .env file missing takes precedence over a command not found error.
275+
"""
276+
266277
result = cli.invoke(dotenv_cli, ["run", "i_do_not_exist"])
267278

268279
assert result.exit_code == 2

0 commit comments

Comments
 (0)