Skip to content

Instantly share code, notes, and snippets.

@dgjustice
Created May 4, 2022 18:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgjustice/f5bf1f62b73cbccdcda411805c594297 to your computer and use it in GitHub Desktop.
Save dgjustice/f5bf1f62b73cbccdcda411805c594297 to your computer and use it in GitHub Desktop.
Compose `async` with `returns`
@future.future_safe
async def run_process(proc: asyncio.subprocess.Process) -> typing.Tuple[bytes, bytes]:
"""Run the async process and check the return code."""
stdout, stderr = await proc.communicate()
if proc.returncode:
logger.error('process exited with returncode {0}'.format(proc.returncode))
raise ValueError('process returned non-zero code')
return stdout, stderr
def a_shell_cmd(cmd: str) -> FutureProc:
"""Run a shell command in subprocess asynchronously.
NOTE: The API for this function is slightly different than the sync one.
"""
ctx = context.RequiresContextFutureResultE.ask()
logger.debug('running async {cmd}'.format(cmd=cmd))
return ctx.bind_future_result(
lambda runner:
future.future_safe(runner.create_subprocess_exec)(
*shlex.split(cmd),
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
).bind_future_result(run_process),
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment