Queer European MD passionate about IT
Browse Source

Async function to run shell commands

Davte 3 years ago
parent
commit
ed05d843bc
2 changed files with 27 additions and 2 deletions
  1. 1 1
      davtelepot/__init__.py
  2. 26 1
      davtelepot/utilities.py

+ 1 - 1
davtelepot/__init__.py

@@ -11,7 +11,7 @@ __author__ = "Davide Testa"
 __email__ = "davide@davte.it"
 __credits__ = ["Marco Origlia", "Nick Lee @Nickoala"]
 __license__ = "GNU General Public License v3.0"
-__version__ = "2.6.5"
+__version__ = "2.6.6"
 __maintainer__ = "Davide Testa"
 __contact__ = "t.me/davte"
 

+ 26 - 1
davtelepot/utilities.py

@@ -18,7 +18,7 @@ import time
 from difflib import SequenceMatcher
 
 # Third party modules
-from typing import Union
+from typing import Tuple, Union
 
 import aiohttp
 from aiohttp import web
@@ -1700,3 +1700,28 @@ def recursive_dictionary_update(one: dict, other: dict) -> dict:
             else:
                 one[key] = val
     return one
+
+
+async def aio_subprocess_shell(command: str) -> Tuple[str, str]:
+    """Run `command` in a subprocess shell.
+
+    Await for the subprocess to end and return standard error and output.
+    On error, log errors.
+    """
+    stdout, stderr = None, None
+    try:
+        _subprocess = await asyncio.create_subprocess_shell(
+            command
+        )
+        stdout, stderr = await _subprocess.communicate()
+        stdout = stdout.decode().strip()
+        stderr = stderr.decode().strip()
+    except Exception as e:
+        logging.error(
+            "Exception {e}:\n{o}\n{er}".format(
+                e=e,
+                o=(stdout.decode().strip() if stdout else ''),
+                er=(stderr.decode().strip() if stderr else '')
+            )
+        )
+    return stdout, stderr