Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH: give "typical" shell behavior when command is not found to be executed #138

Merged
merged 1 commit into from
Aug 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 26 additions & 12 deletions src/con_duct/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import sys
import threading
import time
from typing import IO, Any, TextIO
from typing import IO, Any, Optional, TextIO
from . import __version__

ENV_PREFIXES = ("PBS_", "SLURM_", "OSG")
Expand Down Expand Up @@ -428,7 +428,7 @@ def __post_init__(self) -> None:
)

@classmethod
def from_argv(cls) -> Arguments: # pragma: no cover
def from_argv(cls, cli_args: Optional[list[str]] = None) -> Arguments:
parser = argparse.ArgumentParser(
description="Gathers metrics on a command and all its child processes.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
Expand Down Expand Up @@ -515,7 +515,7 @@ def from_argv(cls) -> Arguments: # pragma: no cover
type=RecordTypes,
help="Record system-summary, processes-samples, or all",
)
args = parser.parse_args()
args = parser.parse_args(args=cli_args)
return cls(
command=args.command,
command_args=args.command_args,
Expand Down Expand Up @@ -649,7 +649,7 @@ def safe_close_files(file_list: Iterable[Any]) -> None:


def duct_print(msg: str) -> None:
print(msg, file=sys.stderr)
print(msg, file=sys.stderr, flush=True)


def main() -> None:
Expand Down Expand Up @@ -677,15 +677,30 @@ def execute(args: Arguments) -> int:
stderr_file = stderr

full_command = " ".join([str(args.command)] + args.command_args)
files_to_close = [stdout_file, stdout, stderr_file, stderr]
try:
process = subprocess.Popen(
[str(args.command)] + args.command_args,
stdout=stdout_file,
stderr=stderr_file,
preexec_fn=os.setsid,
)
except FileNotFoundError:
# We failed to execute due to file not found in PATH
# We should remove log etc files since they are 0-sized
# degenerates etc
safe_close_files(files_to_close)
for _, file_path in log_paths:
if os.path.exists(file_path):
assert os.stat(file_path).st_size == 0
os.remove(file_path)
# mimicking behavior of bash and zsh.
duct_print(f"{args.command}: command not found")
return 127 # seems what zsh and bash return then

if not args.quiet:
duct_print(f"duct is executing {full_command}...")
duct_print(f"Log files will be written to {log_paths.prefix}")
process = subprocess.Popen(
[str(args.command)] + args.command_args,
stdout=stdout_file,
stderr=stderr_file,
preexec_fn=os.setsid,
)
try:
session_id = os.getsid(process.pid) # Get session ID of the new process
except ProcessLookupError: # process has already finished
Expand Down Expand Up @@ -736,8 +751,7 @@ def execute(args: Arguments) -> int:
system_logs.write(report.dump_json())
if not args.quiet:
duct_print(report.execution_summary_formatted)
safe_close_files([stdout_file, stdout, stderr_file, stderr])

safe_close_files(files_to_close)
return report.process.returncode


Expand Down
17 changes: 17 additions & 0 deletions test/test_execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,3 +232,20 @@ def test_run_less_than_report_interval(temp_output_dir: str) -> None:
SUFFIXES["info"],
]
assert_files(temp_output_dir, expected_files, exists=True)


def test_execute_unknown_command(temp_output_dir: str) -> None:
cmd = "this_command_does_not_exist_123abrakadabra"
args = Arguments.from_argv([cmd])
with mock.patch(
"con_duct.__main__.duct_print", new_callable=mock.MagicMock
) as mock_duct_print:
assert execute(args) == 127
mock_duct_print.assert_called_once_with(f"{cmd}: command not found")
expected_files = [
SUFFIXES["stdout"],
SUFFIXES["stderr"],
SUFFIXES["info"],
SUFFIXES["usage"],
]
assert_files(temp_output_dir, expected_files, exists=False)
Loading