Skip to content

Commit

Permalink
Fix Asych io + console output handler
Browse files Browse the repository at this point in the history
  • Loading branch information
lassebje committed Dec 13, 2023
1 parent 2e73f37 commit 7722115
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 17 deletions.
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

setup(
name="simapy",
version="4.6.0",
version="4.6.1.dev1",
author="SINTEF Ocean",
description="Python utilities for SIMA",
url="https://github.com/SINTEF/simapy",
Expand Down
37 changes: 21 additions & 16 deletions src/simapy/sre.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,38 +2,43 @@
import asyncio
import os
from pathlib import Path
from typing import Sequence
from typing import Sequence,Callable
from simapy.sima_writer import SIMAWriter


async def run_command(args, error_file, out_file):
async def run_command(args, error_file, out_file, console_handler):
""""Run a command asynchronously and print output to standard out.
Standard err is piped to stderr.txt in the working directory"""
process = await asyncio.create_subprocess_exec(
*args, stdout=asyncio.subprocess.PIPE, stderr=error_file
)

while True:
stdout, _ = await process.communicate()

if stdout:
for line in stdout.splitlines():
sline = line.decode("utf-8")
if sline.startswith("@STATUS"):
print("STATUS found:" + sline, end="\n")
else:
print(sline, end="\n")
print(sline, end="\n", file=out_file)

if process.returncode is not None:
return process.returncode
# Use an awaitable to read data from stdout
# Read the next line of data from stdout asynchronously
data = await process.stdout.readline()
if not data:
break # Break the loop when there's no more data
sline = data.decode('utf-8')
if console_handler:
console_handler(sline)
else:
# Print the line to standard out
print(sline, end="\n")
print(sline, end="\n", file=out_file)

# Wait for the subprocess to finish
await process.wait()
if process.returncode is not None:
return process.returncode

class SIMA:
""""Run a command using SIMA runtime engine (sre executable)"""

def __init__(self, exe=None, fail_on_error=True):
self.fail_on_error = fail_on_error
# A status handler is a function that can handle standard out from the process
self.console_handler: Callable = None
if exe:
self.exe = exe
else:
Expand All @@ -59,7 +64,7 @@ def run(self, working_dir, command_args: Sequence[str]):
with open(err_file, "w", encoding="utf8") as e_f, open(
out_file, "w", encoding="utf8"
) as o_f:
exit_code = asyncio.run(run_command(arguments, e_f, o_f))
exit_code = asyncio.run(run_command(arguments, e_f, o_f, self.console_handler))
if exit_code != 0 and self.fail_on_error:
raise RuntimeError(f"SIMA exited with error code {exit_code}")

Expand Down

0 comments on commit 7722115

Please sign in to comment.