Skip to content

Commit

Permalink
Merge pull request #207 from gerlero/cases
Browse files Browse the repository at this point in the history
Update internal subprocess module
  • Loading branch information
gerlero authored Oct 1, 2024
2 parents a7e4ab9 + 27484f3 commit 93efaa7
Showing 1 changed file with 60 additions and 7 deletions.
67 changes: 60 additions & 7 deletions foamlib/_cases/_subprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,19 @@
else:
from typing import Mapping, Sequence

CalledProcessError = subprocess.CalledProcessError
CompletedProcess = subprocess.CompletedProcess


class CalledProcessError(subprocess.CalledProcessError):
def __str__(self) -> str:
if self.stderr:
if isinstance(self.stderr, bytes):
return super().__str__() + "\n" + self.stderr.decode()
elif isinstance(self.stderr, str):
return super().__str__() + "\n" + self.stderr
return super().__str__()


DEVNULL = subprocess.DEVNULL
PIPE = subprocess.PIPE
STDOUT = subprocess.STDOUT
Expand All @@ -29,14 +39,43 @@ def run_sync(
if not isinstance(cmd, str) and sys.version_info < (3, 8):
cmd = [str(arg) for arg in cmd]

return subprocess.run(
proc = subprocess.Popen(
cmd,
cwd=cwd,
env=env,
stdout=stdout,
stderr=stderr,
stderr=PIPE,
shell=isinstance(cmd, str),
check=check,
)

error = b""

if stderr == STDOUT:
stderr = stdout
if stderr not in (PIPE, DEVNULL):
assert not isinstance(stderr, int)
if stderr is None:
stderr = sys.stderr.buffer

assert proc.stderr is not None
for line in proc.stderr:
error += line
stderr.write(line)

output, _ = proc.communicate()
assert not _
assert proc.returncode is not None

if check and proc.returncode != 0:
raise CalledProcessError(
returncode=proc.returncode,
cmd=cmd,
output=output,
stderr=error,
)

return CompletedProcess(
cmd, returncode=proc.returncode, stdout=output, stderr=error
)


Expand All @@ -55,7 +94,7 @@ async def run_async(
cwd=cwd,
env=env,
stdout=stdout,
stderr=stderr,
stderr=PIPE,
)

else:
Expand All @@ -66,11 +105,25 @@ async def run_async(
cwd=cwd,
env=env,
stdout=stdout,
stderr=stderr,
stderr=PIPE,
)

output, error = await proc.communicate()
error = b""

if stderr == STDOUT:
stderr = stdout
if stderr not in (PIPE, DEVNULL):
assert not isinstance(stderr, int)
if stderr is None:
stderr = sys.stderr.buffer

assert proc.stderr is not None
async for line in proc.stderr:
error += line
stderr.write(line)

output, _ = await proc.communicate()
assert not _
assert proc.returncode is not None

if check and proc.returncode != 0:
Expand Down

0 comments on commit 93efaa7

Please sign in to comment.