From 4ae2b5dede9edead4580b6fd0ed1b95582c8435e Mon Sep 17 00:00:00 2001 From: Josh Meyers Date: Thu, 26 Oct 2023 16:17:35 -0700 Subject: [PATCH] Parse stdout/stderr separately in runProgram --- python/lsst/ts/wep/utils/taskUtils.py | 28 +++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/python/lsst/ts/wep/utils/taskUtils.py b/python/lsst/ts/wep/utils/taskUtils.py index c0938c5ef..02b407bce 100644 --- a/python/lsst/ts/wep/utils/taskUtils.py +++ b/python/lsst/ts/wep/utils/taskUtils.py @@ -29,11 +29,12 @@ import os import shlex import subprocess +from contextlib import ExitStack import lsst.obs.lsst as obs_lsst -def runProgram(command, binDir=None, argstring=None): +def runProgram(command, binDir=None, argstring=None, stdout=None, stderr=None): """Run the program w/o arguments. Parameters @@ -44,6 +45,8 @@ def runProgram(command, binDir=None, argstring=None): Directory of binary application. (the default is None.) argstring : str, optional Arguments of program. (the default is None.) + stdout, stderr : str or _io.TextIOWrapper, optional + Buffered text output/error streams or filenames Raises ------ @@ -59,9 +62,26 @@ def runProgram(command, binDir=None, argstring=None): if argstring is not None: command += " " + argstring - # Call the program w/o arguments - if subprocess.call(shlex.split(command), shell=False) != 0: - raise RuntimeError("Error running: %s" % command) + with ExitStack() as stack: + if isinstance(stdout, str): + stdout = stack.enter_context(open(stdout, "w")) + # Don't open competing filehandles on the same file + if isinstance(stderr, str) and (stderr == stdout.name): + stderr = stdout + if isinstance(stderr, str): + stderr = stack.enter_context(open(stderr, "w")) + + # Call the program w/o arguments + if ( + subprocess.run( + shlex.split(command), + shell=False, + stdout=stdout, + stderr=stderr, + ).returncode + != 0 + ): + raise RuntimeError("Error running: %s" % command) def writePipetaskCmd(