Note: I have read this, this, this, and this question. While there is much useful info, none give an exact answer. My knowledge of the language is limited, so I cannot put together pieces from those answers in a way that fit the needed use case (especially point (4) below).
I am looking for a way to run a process with a given set of arguments in current Python (latest version atm is 3.11), with the following requirements:
- The stderr and stdout of the process are displayed in real-time, as they would be if run directly (or through a script) in almost any shell, i.e.
bash
orPowerShell
- Both streams are also separately captured into a string or byte array for accessing later
- The return code is captured on process finish
- This is encapsualted in a function that simply requires the argument list, and returns an object containing both streams and the return code
All points except for (1) are covered by subprocess.run(args, capture_output=True)
. So, I need to define a function
def run_and_output_realtime:
# ???
return result
Which would allow to change just the first line of code like
run_tool_result = subproccess.run(args, capture_output=True)
if run_tool_result.returncode != 0:
if "Unauthorized" in run_tool_result.stderr.decode():
print("Please check authorization")
else:
if "Duration" in run_tool_result.stdout.decode():
# parse to get whatever duration was in the output
To run_tool_result = run_and_output_realtime(args)
, and have all the remaining lines unchanged and working.