-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
execute-shell-command.py
executable file
·87 lines (63 loc) · 2.54 KB
/
execute-shell-command.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/usr/bin/env python
"""
A Python script for executing shell commands and returning the outputs and exit status.
This script defines a function to execute shell commands and a simple test function to
demonstrate its usage.
Classes:
ExecutionResult: A named tuple to store the status, stdout, and stderr of a shell command execution.
Functions:
execute_shell_command(cmd: List[str]) -> ExecutionResult: Executes a shell command and returns the results.
run_tests() -> None: Runs a test to check the 'ls -l' command.
"""
import os
from subprocess import Popen, PIPE # nosec: B404
from typing import Any, NamedTuple, List
class ExecutionResult(NamedTuple):
"""
A named tuple to store the result of executing a shell command.
Attributes:
status (int): The exit status of the executed command.
stdout (str): The standard output produced by the command.
stderr (str): The standard error output produced by the command.
"""
status: int
stdout: str
stderr: str
def execute_shell_command(cmd: List[str]) -> ExecutionResult:
"""
Execute a shell command and returns the status, stdout, and stderr.
Arguments:
cmd (List[str]): The shell command to execute as a list of arguments.
Returns:
ExecutionResult: A named tuple containing the status, stdout, and stderr.
Example:
>>> result = execute_shell_command(['ls', '-l'])
>>> print(result.status)
>>> print(result.stdout)
>>> print(result.stderr)
"""
with Popen(cmd, stdout=PIPE, stderr=PIPE, cwd=os.getcwd()) as process: # nosec: B603
stdout_raw, stderr_raw = process.communicate()
status: int | Any = process.returncode
stdout: str = stdout_raw.decode('utf-8').rstrip()
stderr: str = stderr_raw.decode('utf-8').rstrip()
return ExecutionResult(status, stdout, stderr)
def run_tests() -> None:
"""
Run a test to check if the 'ls -l' command works as required.
This function demonstrates the usage of the execute_shell_command function.
It executes the 'ls -l' command and prints the status, stdout, and stderr.
Example:
>>> run_tests()
Status: 0
Stdout: total 0
-rw-r--r-- 1 user staff 0 Jan 1 00:00 file1
-rw-r--r-- 1 user staff 0 Jan 1 00:00 file2
Stderr:
"""
results: ExecutionResult = execute_shell_command(['ls', '-l'])
print(f'Status: {results.status}')
print(f'Stdout: {results.stdout}')
print(f'Stderr: {results.stderr}')
if __name__ == '__main__':
run_tests()