Created
May 4, 2022 18:32
-
-
Save dgjustice/f5bf1f62b73cbccdcda411805c594297 to your computer and use it in GitHub Desktop.
Compose `async` with `returns`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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