Если вы используете модуль Python subprocess
, вы можете обрабатывать STDOUT, STDERR и код возврата команды по отдельности. Вы можете увидеть пример полной реализации вызывающей команды. Конечно, вы можете расширить его на try..except
, если хотите.
Следующая функция возвращает код STDOUT, STDERR и Return, чтобы вы могли обрабатывать их в другом скрипте.
import subprocess
def command_caller(command=None)
sp = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=False)
out, err = sp.communicate()
if sp.returncode:
print(
"Return code: %(ret_code)s Error message: %(err_msg)s"
% {"ret_code": sp.returncode, "err_msg": err}
)
# You can raise an error if the return code of command is not zero.
# raise Exception(
# "Return code: %(ret_code)s Error message: %(err_msg)s"
# % {"ret_code": sp.returncode, "err_msg": err}
# )
return sp.returncode, out, err