Skip to content

Commit 245daf7

Browse files
committed
module for execution or system calls
1 parent f9786a4 commit 245daf7

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

src/utils/shared/exec.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
from shutil import which
2+
from subprocess import run, CalledProcessError, DEVNULL
3+
from typing import NoReturn
4+
5+
from src.utils.log.logger import Logger
6+
7+
8+
def execute_command(
9+
log: Logger, command: list[str], verbose: bool = False
10+
) -> NoReturn | None:
11+
"""For command execution/system calls with error handling
12+
13+
Args:
14+
log -- Logger instance
15+
command -- command to execute with arguments
16+
17+
Returns:
18+
None or raise system exit
19+
"""
20+
21+
try:
22+
if which(command[0]) is None:
23+
log.logger(
24+
"E", f"Program: {command[0]} does not exists, aborting ..."
25+
)
26+
raise SystemExit
27+
28+
if verbose:
29+
return_code: int = run(command).returncode
30+
else:
31+
return_code: int = run(command, stdout=DEVNULL).returncode
32+
33+
if return_code != 0:
34+
raise CalledProcessError(return_code, command)
35+
else:
36+
log.logger("I", f"Successfully executed the command: {command}")
37+
except (OSError, CalledProcessError) as Err:
38+
log.logger(
39+
"E",
40+
(
41+
f"{Err} encountered, cannot execute"
42+
" command: {command}, aborting ..."
43+
)
44+
)
45+
raise SystemExit
46+
47+
return None

0 commit comments

Comments
 (0)