-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add subprocess module with
cmd
and shell
These helper functions makes it easy to run arbitrary commands on the user config file.
- Loading branch information
Showing
1 changed file
with
52 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
# Copyright (c) 2022 Daniel Pereira | ||
# | ||
# SPDX-License-Identifier: Apache-2.0 | ||
|
||
import asyncio | ||
from logging import getLogger | ||
|
||
logger = getLogger(__name__) | ||
|
||
async def cmd(cmd: str, *args: list[str], env: dict = None, output_encoding: str = "utf-8"): | ||
""" | ||
Run a command in the existing thread event loop and return its return code and outputs. | ||
""" | ||
proc = await asyncio.create_subprocess_exec( | ||
cmd, *args, env=env, | ||
stdout=asyncio.subprocess.PIPE, | ||
stderr=asyncio.subprocess.PIPE, | ||
) | ||
|
||
stdout, stderr = await proc.communicate() | ||
|
||
if proc.returncode != 0: | ||
stderr_str = stderr.decode(output_encoding).strip() | ||
logger.warn(f"Process '{cmd}' returned {proc.returncode}: {stderr_str}") | ||
|
||
return dict( | ||
rc=proc.returncode, | ||
stderr=stderr.decode(output_encoding), | ||
stdout=stdout.decode(output_encoding), | ||
) | ||
|
||
async def shell(cmd: str, env: dict = None, output_encoding: str = "utf-8"): | ||
""" | ||
Run a shell command in the existing thread event loop and return its return code and outputs. | ||
""" | ||
proc = await asyncio.create_subprocess_shell( | ||
cmd, env=env, | ||
stdout=asyncio.subprocess.PIPE, | ||
stderr=asyncio.subprocess.PIPE, | ||
) | ||
|
||
stdout, stderr = await proc.communicate() | ||
|
||
if proc.returncode != 0: | ||
stderr_str = stderr.decode(output_encoding).strip() | ||
logger.warn(f"Shell command '{cmd}' returned {proc.returncode}: {stderr_str}") | ||
|
||
return dict( | ||
rc=proc.returncode, | ||
stderr=stderr.decode(output_encoding), | ||
stdout=stdout.decode(output_encoding), | ||
) |