diff --git a/src/dotenv/cli.py b/src/dotenv/cli.py index 7a4c7adc..20c4da96 100644 --- a/src/dotenv/cli.py +++ b/src/dotenv/cli.py @@ -217,9 +217,20 @@ def run_command(command: List[str], env: Dict[str, str]) -> None: if sys.platform == "win32": # execvpe on Windows returns control immediately # rather than once the command has finished. - p = Popen(command, universal_newlines=True, bufsize=0, shell=False, env=cmd_env) + try: + p = Popen( + command, universal_newlines=True, bufsize=0, shell=False, env=cmd_env + ) + except FileNotFoundError: + print(f"Command not found: {command[0]}", file=sys.stderr) + sys.exit(1) + _, _ = p.communicate() sys.exit(p.returncode) else: - os.execvpe(command[0], args=command, env=cmd_env) + try: + os.execvpe(command[0], args=command, env=cmd_env) + except FileNotFoundError: + print(f"Command not found: {command[0]}", file=sys.stderr) + sys.exit(1) diff --git a/tests/test_cli.py b/tests/test_cli.py index 02bdb764..d4e3ad4d 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -237,7 +237,21 @@ def test_run_without_cmd(tmp_path): assert "Invalid value for '-f'" in result.stderr -def test_run_with_invalid_cmd(tmp_path): +def test_run_with_invalid_cmd(dotenv_path, tmp_path): + result = run_dotenv( + ["--file", str(dotenv_path), "run", "i_do_not_exist"], + cwd=tmp_path, + ) + + check_process(result, exit_code=1) + assert "Command not found: i_do_not_exist" in result.stderr + + +def test_run_with_env_missing_and_invalid_cmd(tmp_path): + """ + Check that an .env file missing takes precedence over a command not found error. + """ + result = run_dotenv(["run", "i_do_not_exist"], cwd=tmp_path) check_process(result, exit_code=2)