Skip to content

Commit

Permalink
fix: don't add extra newline to command stdout/stderr
Browse files Browse the repository at this point in the history
  • Loading branch information
kelly-sovacool committed Sep 10, 2024
1 parent 8de92ce commit 3b4641a
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 5 deletions.
18 changes: 16 additions & 2 deletions src/ccbr_tools/shell.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def shell_run(command_str, capture_output=True, check=True, shell=True, text=Tru
command_str, capture_output=capture_output, shell=shell, text=text, check=check
)
if capture_output:
return "\n".join([out.stdout, out.stderr])
return concat_newline(out.stdout, out.stderr)


def exec_in_context(func: callable, *args: str, **kwargs: str):
Expand All @@ -42,6 +42,7 @@ def exec_in_context(func: callable, *args: str, **kwargs: str):
func (func): The function to be executed.
*args: Variable length argument list to be passed to the function.
**kwargs: Arbitrary keyword arguments to be passed to the function.
Returns:
str: The combined output from both stdout and stderr.
"""
Expand All @@ -50,5 +51,18 @@ def exec_in_context(func: callable, *args: str, **kwargs: str):
contextlib.redirect_stderr(io.StringIO()) as err_f,
):
func(*args, **kwargs)
out_combined = "\n".join([out_f.getvalue(), err_f.getvalue()])
out_combined = concat_newline(out_f.getvalue(), err_f.getvalue())
return out_combined


def concat_newline(*args: str):
"""
Concatenates strings with a newline character between non-empty arguments
Args:
*args: Variable length argument list of strings to be concatenated.
Returns:
str: The concatenated string with newline characters between each non-empty argument.
"""
return "\n".join([arg for arg in args if arg])
2 changes: 1 addition & 1 deletion tests/test_hpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,5 @@ def test_hpc_frce():


def test_hpc_none():
hpc = get_hpc(debug="")
hpc = get_hpc(debug=" ")
assert not any([hpc, hpc.name, *hpc.modules.values(), hpc.singularity_sif_dir])
17 changes: 15 additions & 2 deletions tests/test_shell.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
from ccbr_tools.shell import exec_in_context
from ccbr_tools.shell import shell_run, exec_in_context, concat_newline


def test_exec():
assert exec_in_context(print, "hello", "world") == "hello world\n\n"
assert exec_in_context(print, "hello", "world") == "hello world\n"


def test_shell_run():
assert shell_run("echo hello world") == "hello world\n"


def test_concat_newline():
assert all(
[
concat_newline("hello", "world") == "hello\nworld",
concat_newline("goodbye", "") == "goodbye",
]
)

0 comments on commit 3b4641a

Please sign in to comment.