Код: Выделить всё
import subprocess
from io import TextIOWrapper
def run_shell_command(command: list, debug: bool = False):
'''
Run shell command
:param command: Shell command
:param debug: Debug mode
:return: Result code and message
'''
try:
process = subprocess.run(
command, check=True, text=True, timeout=5,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT
)
if debug:
for line in TextIOWrapper(process.stdout, encoding='utf-8'):
print(line)
message = 'Shell command executed sucessfully'
return ({'code': 200, 'msg': message, 'stdout': process.stdout})
except subprocess.CalledProcessError as e:
return ({'code': 500, 'msg': e.output})
if __name__ == "__main__":
command = run_shell_command(['ls', '-lah'], True)
print(command)
Код: Выделить всё
Traceback (most recent call last):
File "/tmp/command.py", line 28, in
command = run_shell_command(['ls', '-lah'], True)
File "/tmp/command.py", line 19, in run_shell_command
for line in TextIOWrapper(process.stdout, encoding="utf-8"):
AttributeError: 'str' object has no attribute 'readable'
Изменить: судя по комментариям ниже, исправить это довольно просто:
Код: Выделить всё
if debug:
print(process.stdout.rstrip())
Подробнее здесь: https://stackoverflow.com/questions/788 ... nes-output